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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b1af6e9a66885fbb858e1b92cc637b4fef58d38c | 9894d3a9056927f97be327942305882e25adf6fe | /Day 04/ex01/SuperMutant.hpp | b42bcb7c02e2108157229540d84278cdb88b0628 | [
"MIT"
] | permissive | akharrou/42-Piscine-CPP | 3c34585cbce5144cc3dd4452e72bd906fb6fbcc2 | 11c80e32f96718946134400435182629470f1439 | refs/heads/master | 2020-06-12T20:32:06.586570 | 2019-08-19T04:53:42 | 2019-08-19T04:53:42 | 194,416,333 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,691 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* SuperMutant.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <akharrou@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/19 15:05:37 by akharrou #+# #+# */
/* Updated: 2019/07/19 15:13:42 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SUPERMUTANT_HPP
# define SUPERMUTANT_HPP
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
#include "Enemy.hpp"
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
class SuperMutant
: public Enemy {
public:
SuperMutant( void );
SuperMutant( const SuperMutant & src );
~SuperMutant( void );
SuperMutant & operator = ( const SuperMutant & rhs );
void takeDamage( int amount );
};
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
#endif /* SUPERMUTANT_HPP */
| [
"idev.aymen@gmail.com"
] | idev.aymen@gmail.com |
05e2ea7fc3d15d8f557efcd47d7327492c98a990 | d782a7a41b7421e0f8156199de5773a5a7778f06 | /vec3.hpp | f16d49a635495b7d74f21406edd74d33dc10713b | [] | no_license | TeDand/Ray-Tracing | f6601fc00b2b8a1745509237e7f334dc1bb9f9bf | ad2cb7b028b501c3cbfa4719bf8ac82b6c9ad759 | refs/heads/master | 2022-12-02T02:10:08.186525 | 2020-08-20T08:54:15 | 2020-08-20T08:54:15 | 288,688,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,318 | hpp | #ifndef VEC3_H
#define VEC3_H
#include <cmath>
#include <iostream>
using std::sqrt;
// class that stores a three dimensional point (or colour)
class vec3 {
public:
vec3() : e{0,0,0} {}
vec3(double e0, double e1, double e2) : e{e0, e1, e2} {}
double x() const { return e[0]; }
double y() const { return e[1]; }
double z() const { return e[2]; }
vec3 operator-() const { return vec3(-e[0], -e[1], -e[2]); }
double operator[](int i) const { return e[i]; }
double& operator[](int i) { return e[i]; }
vec3& operator+=(const vec3 &v) {
e[0] += v.e[0];
e[1] += v.e[1];
e[2] += v.e[2];
return *this;
}
vec3& operator*=(const double t) {
e[0] *= t;
e[1] *= t;
e[2] *= t;
return *this;
}
vec3& operator/=(const double t) {
return *this *= 1/t;
}
double length() const {
return sqrt(length_squared());
}
double length_squared() const {
return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
}
inline static vec3 random() {
return vec3(random_double(), random_double(), random_double());
}
inline static vec3 random(double min, double max) {
return vec3(random_double(min,max), random_double(min,max), random_double(min,max));
}
public:
double e[3];
};
// Type aliases for vec3
using point3 = vec3; // 3D point
using colour = vec3; // RGB color
// vec3 Utility Functions
inline std::ostream& operator<<(std::ostream &out, const vec3 &v) {
return out << v.e[0] << ' ' << v.e[1] << ' ' << v.e[2];
}
inline vec3 operator+(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] + v.e[0], u.e[1] + v.e[1], u.e[2] + v.e[2]);
}
inline vec3 operator-(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] - v.e[0], u.e[1] - v.e[1], u.e[2] - v.e[2]);
}
inline vec3 operator*(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] * v.e[0], u.e[1] * v.e[1], u.e[2] * v.e[2]);
}
inline vec3 operator*(double t, const vec3 &v) {
return vec3(t*v.e[0], t*v.e[1], t*v.e[2]);
}
inline vec3 operator*(const vec3 &v, double t) {
return t * v;
}
inline vec3 operator/(vec3 v, double t) {
return (1/t) * v;
}
inline double dot(const vec3 &u, const vec3 &v) {
return u.e[0] * v.e[0]
+ u.e[1] * v.e[1]
+ u.e[2] * v.e[2];
}
inline vec3 cross(const vec3 &u, const vec3 &v) {
return vec3(u.e[1] * v.e[2] - u.e[2] * v.e[1],
u.e[2] * v.e[0] - u.e[0] * v.e[2],
u.e[0] * v.e[1] - u.e[1] * v.e[0]);
}
inline vec3 unit_vector(vec3 v) {
return v / v.length();
}
// random value within unit sphere (random length)
vec3 random_in_unit_sphere() {
while (true) {
auto p = vec3::random(-1,1);
if (p.length_squared() >= 1) continue;
return p;
}
}
// random value on surface of unit sphere for true lambertian dispersion (unit length)
vec3 random_unit_vector() {
auto a = random_double(0, 2*pi);
auto z = random_double(-1, 1);
auto r = sqrt(1 - z*z);
return vec3(r*cos(a), r*sin(a), z);
}
// random dispersion with no dependence on angle from normal
vec3 random_in_hemisphere(const vec3& normal) {
vec3 in_unit_sphere = random_in_unit_sphere();
if (dot(in_unit_sphere, normal) > 0.0) // In the same hemisphere as the normal
return in_unit_sphere;
else
return -in_unit_sphere;
}
// reflets with an angle equal to angle of incidence
vec3 reflect(const vec3& v, const vec3& n) {
return v - 2*dot(v,n)*n;
}
// reafracts and object using snells law
vec3 refract(const vec3& uv, const vec3& n, double etai_over_etat) {
// since we only have unit vector inputs this fomula works
auto cos_theta = dot(-uv, n);
// calculate the components of the difrections fo the refracted ray wrt inward normal
vec3 r_out_perp = etai_over_etat * (uv + cos_theta*n);
vec3 r_out_parallel = -sqrt(fabs(1.0 - r_out_perp.length_squared())) * n;
return r_out_perp + r_out_parallel;
}
#endif | [
"tejas-d@hotmail.com"
] | tejas-d@hotmail.com |
9e38a185a409af2938d8ce6a33bd902b01f36fb7 | a700ba820b53dd5ca2486e87df1c87376d77c6ee | /src/registry.h | 8da08963d3bd9f64c6fbb26fca0f2e23191494b7 | [] | no_license | Javier090/keylogger- | 6bf645816c015ee2a62cd4dac5ac5fc5d376b192 | 1257d789c47355a2a3a92b02c1f38fd76e81b831 | refs/heads/main | 2023-07-09T09:49:48.091357 | 2021-08-17T19:41:42 | 2021-08-17T19:41:42 | 394,162,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73 | h | #pragma once
namespace registry
{
void add_to_startup() noexcept;
}
| [
"noreply@github.com"
] | noreply@github.com |
418f0269a6e76ad4be87b232e1850b2cb94f7d0d | 97dd176a3f2127dcb3d67412889aa673731b4a42 | /funcprac02.cpp | 624c5164e411e8bcdb57c37db649f4e8c1a09631 | [] | no_license | sunny722122/C-programming-practice | b3a7c2e7d03062cd883aa3ae15c297d720078719 | 8a760980ae129d23325b170bd5e662396393c250 | refs/heads/master | 2021-03-22T09:38:54.352727 | 2020-03-21T23:41:55 | 2020-03-21T23:41:55 | 247,353,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,908 | cpp | /******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void pause();
float get_Side(int);
//float sqr_Number(float);
float calc_Diagonal(float ,float );
void print_Results(float ,float ,float );
int main()
{
float side1,side2,diagnoal;
do
{
side1=get_Side(1);
side2=get_Side(2);
if(side1>=0.5 && side2 >=0.5)
{
diagnoal=calc_Diagonal(side1,side2);
print_Results(side1,side2,diagnoal);
}
//print_Results(num);
if(side1==0||side2==0)
{
exit(1);
}
}while(side1!=0 && side2!=0);
pause();
}
void pause()
{
//flushall();
getchar();
//flushall();
getchar();
}
float get_Side(int nside)
{
float side1;
/*
printf("Enter a positive 3 digit number (or 0 to exit): ");
scanf("%d",&num);
printf("cube number: %d",cube_Number(num));
*/
do
{
printf("\nEnter the length of side %d: ",nside);
//flushall();
scanf("%f",&side1);
if(side1==0)
{
printf("Good-bye");
exit(1);
}
}while(side1 !=0 && side1<0.5);
return side1;
}
float sqr_Number(float num)
{
return num*num;
}
float calc_Diagonal(float side1,float side2)
{
return sqrt(sqr_Number(side1)+sqr_Number(side2));
}
void print_Results(float side1,float side2,float diagnoal)
{
printf("The right angle triangle with sides %0.1f and %0.1f is %0.1f", side1,side2,diagnoal);
}
| [
"noreply@github.com"
] | noreply@github.com |
2be3b3b5e4f9468d23cf3cd83cf33c7bb919b252 | f1571d9d08e18b1bf1c60f8961e0a53107db6db4 | /121A/121A_8415353.cpp | 39ec946ae56ec02c256d53813914ea5907576ff2 | [] | no_license | ahmed-dinar/codeforces-solved-problems | a6d4cc40d210834210043e71a44c72bee927145c | d0fa0462e28cb05c4d26b5a8d5175e62aa2f44d9 | refs/heads/master | 2021-01-18T22:14:00.951801 | 2016-10-30T14:16:33 | 2016-10-30T14:16:33 | 72,353,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,537 | cpp | #include<bits/stdc++.h>
using namespace std;
#define all(x) (x.begin(),x.end())
#define Find(x,n) find(all(x),n)
#define pi acos(-1.0)
#define i64 long long
#define pb(x) push_back(x)
#define mset(x,v) memset(x,v,sizeof(x))
#define sc(n) scanf("%d",&n)
#define scl(n) scanf("%ld",&n)
#define scll(n) scanf("%lld",&n)
#define scd(n,m) scanf("%d %d",&n,&m)
#define scdl(n,m) scanf("%ld %ld",&n,&m)
#define scdll(n,m) scanf("%lld %lld",&n,&m)
#define file freopen("in.txt","r",stdin)
template<class T>T gcd(T a,T b){ return b==0 ? a : gcd(b,a%b); }
template<class T>T lcm(T a,T b){ return (a/gcd(a,b))*b; }
template<class T>T isPrime(T n){ for(T i=2; i*i<=n; i++){ if(n%i==0) return false; } return true; }
vector<i64>lucky;
void gen_lucky(){
lucky.pb(4);
lucky.pb(7);
int j=0;
for(int i=0;i<9; i++){
int sz=lucky.size();
while(j<sz){
i64 l = lucky[j];
lucky.pb(l*10+4);
lucky.pb(l*10+7);
j++;
}
}
}
int main(){
gen_lucky();
int sz=2046;
i64 l,r;
while( scanf("%I64d %I64d",&l,&r) == 2 ){
int index = (int)(lower_bound (lucky.begin(), lucky.end(), l)-lucky.begin());
int index2 = (int)(lower_bound (lucky.begin(), lucky.end(), r)-lucky.begin());
i64 res=0;
i64 tem=l;
for(int i=index; i<index2; i++){
res += lucky[i]*(lucky[i]-tem+1);
tem=lucky[i]+1;
}
res += lucky[index2]*(r-tem+1);
cout << res << endl;
}
return 0;
} | [
"madinar.cse@gmail.com"
] | madinar.cse@gmail.com |
423a3bb9dc4db936f85167c409847a06445d6084 | ea6a9bcf02fe7d72df645302909b1de63cdf7fe0 | /src/test/allocator_tests.cpp | 6318d10f1535c646ac89f25b543f735bb1dcbc8b | [
"MIT"
] | permissive | durgeshkmr/minicoin | 69a834786413122eb2b85731b20f0fda931c7a72 | 4f082abe13cd34a759bf8ffb344a49244615960e | refs/heads/master | 2020-05-04T22:59:23.367524 | 2019-04-06T16:13:28 | 2019-04-06T16:13:28 | 179,529,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,371 | cpp | // Copyright (c) 2012-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util.h>
#include <support/allocators/secure.h>
#include <test/test_minicoin.h>
#include <memory>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(arena_tests)
{
// Fake memory base address for testing
// without actually using memory.
void *synth_base = reinterpret_cast<void*>(0x08000000);
const size_t synth_size = 1024*1024;
Arena b(synth_base, synth_size, 16);
void *chunk = b.alloc(1000);
#ifdef ARENA_DEBUG
b.walk();
#endif
BOOST_CHECK(chunk != nullptr);
BOOST_CHECK(b.stats().used == 1008); // Aligned to 16
BOOST_CHECK(b.stats().total == synth_size); // Nothing has disappeared?
b.free(chunk);
#ifdef ARENA_DEBUG
b.walk();
#endif
BOOST_CHECK(b.stats().used == 0);
BOOST_CHECK(b.stats().free == synth_size);
try { // Test exception on double-free
b.free(chunk);
BOOST_CHECK(0);
} catch(std::runtime_error &)
{
}
void *a0 = b.alloc(128);
void *a1 = b.alloc(256);
void *a2 = b.alloc(512);
BOOST_CHECK(b.stats().used == 896);
BOOST_CHECK(b.stats().total == synth_size);
#ifdef ARENA_DEBUG
b.walk();
#endif
b.free(a0);
#ifdef ARENA_DEBUG
b.walk();
#endif
BOOST_CHECK(b.stats().used == 768);
b.free(a1);
BOOST_CHECK(b.stats().used == 512);
void *a3 = b.alloc(128);
#ifdef ARENA_DEBUG
b.walk();
#endif
BOOST_CHECK(b.stats().used == 640);
b.free(a2);
BOOST_CHECK(b.stats().used == 128);
b.free(a3);
BOOST_CHECK(b.stats().used == 0);
BOOST_CHECK_EQUAL(b.stats().chunks_used, 0U);
BOOST_CHECK(b.stats().total == synth_size);
BOOST_CHECK(b.stats().free == synth_size);
BOOST_CHECK_EQUAL(b.stats().chunks_free, 1U);
std::vector<void*> addr;
BOOST_CHECK(b.alloc(0) == nullptr); // allocating 0 always returns nullptr
#ifdef ARENA_DEBUG
b.walk();
#endif
// Sweeping allocate all memory
for (int x=0; x<1024; ++x)
addr.push_back(b.alloc(1024));
BOOST_CHECK(b.stats().free == 0);
BOOST_CHECK(b.alloc(1024) == nullptr); // memory is full, this must return nullptr
BOOST_CHECK(b.alloc(0) == nullptr);
for (int x=0; x<1024; ++x)
b.free(addr[x]);
addr.clear();
BOOST_CHECK(b.stats().total == synth_size);
BOOST_CHECK(b.stats().free == synth_size);
// Now in the other direction...
for (int x=0; x<1024; ++x)
addr.push_back(b.alloc(1024));
for (int x=0; x<1024; ++x)
b.free(addr[1023-x]);
addr.clear();
// Now allocate in smaller unequal chunks, then deallocate haphazardly
// Not all the chunks will succeed allocating, but freeing nullptr is
// allowed so that is no problem.
for (int x=0; x<2048; ++x)
addr.push_back(b.alloc(x+1));
for (int x=0; x<2048; ++x)
b.free(addr[((x*23)%2048)^242]);
addr.clear();
// Go entirely wild: free and alloc interleaved,
// generate targets and sizes using pseudo-randomness.
for (int x=0; x<2048; ++x)
addr.push_back(0);
uint32_t s = 0x12345678;
for (int x=0; x<5000; ++x) {
int idx = s & (addr.size()-1);
if (s & 0x80000000) {
b.free(addr[idx]);
addr[idx] = 0;
} else if(!addr[idx]) {
addr[idx] = b.alloc((s >> 16) & 2047);
}
bool lsb = s & 1;
s >>= 1;
if (lsb)
s ^= 0xf00f00f0; // LFSR period 0xf7ffffe0
}
for (void *ptr: addr)
b.free(ptr);
addr.clear();
BOOST_CHECK(b.stats().total == synth_size);
BOOST_CHECK(b.stats().free == synth_size);
}
/** Mock LockedPageAllocator for testing */
class TestLockedPageAllocator: public LockedPageAllocator
{
public:
TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {}
void* AllocateLocked(size_t len, bool *lockingSuccess) override
{
*lockingSuccess = false;
if (count > 0) {
--count;
if (lockedcount > 0) {
--lockedcount;
*lockingSuccess = true;
}
return reinterpret_cast<void*>(0x08000000 + (count<<24)); // Fake address, do not actually use this memory
}
return 0;
}
void FreeLocked(void* addr, size_t len) override
{
}
size_t GetLimit() override
{
return std::numeric_limits<size_t>::max();
}
private:
int count;
int lockedcount;
};
BOOST_AUTO_TEST_CASE(lockedpool_tests_mock)
{
// Test over three virtual arenas, of which one will succeed being locked
std::unique_ptr<LockedPageAllocator> x(new TestLockedPageAllocator(3, 1));
LockedPool pool(std::move(x));
BOOST_CHECK(pool.stats().total == 0);
BOOST_CHECK(pool.stats().locked == 0);
// Ensure unreasonable requests are refused without allocating anything
void *invalid_toosmall = pool.alloc(0);
BOOST_CHECK(invalid_toosmall == nullptr);
BOOST_CHECK(pool.stats().used == 0);
BOOST_CHECK(pool.stats().free == 0);
void *invalid_toobig = pool.alloc(LockedPool::ARENA_SIZE+1);
BOOST_CHECK(invalid_toobig == nullptr);
BOOST_CHECK(pool.stats().used == 0);
BOOST_CHECK(pool.stats().free == 0);
void *a0 = pool.alloc(LockedPool::ARENA_SIZE / 2);
BOOST_CHECK(a0);
BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE);
void *a1 = pool.alloc(LockedPool::ARENA_SIZE / 2);
BOOST_CHECK(a1);
void *a2 = pool.alloc(LockedPool::ARENA_SIZE / 2);
BOOST_CHECK(a2);
void *a3 = pool.alloc(LockedPool::ARENA_SIZE / 2);
BOOST_CHECK(a3);
void *a4 = pool.alloc(LockedPool::ARENA_SIZE / 2);
BOOST_CHECK(a4);
void *a5 = pool.alloc(LockedPool::ARENA_SIZE / 2);
BOOST_CHECK(a5);
// We've passed a count of three arenas, so this allocation should fail
void *a6 = pool.alloc(16);
BOOST_CHECK(!a6);
pool.free(a0);
pool.free(a2);
pool.free(a4);
pool.free(a1);
pool.free(a3);
pool.free(a5);
BOOST_CHECK(pool.stats().total == 3*LockedPool::ARENA_SIZE);
BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE);
BOOST_CHECK(pool.stats().used == 0);
}
// These tests used the live LockedPoolManager object, this is also used
// by other tests so the conditions are somewhat less controllable and thus the
// tests are somewhat more error-prone.
BOOST_AUTO_TEST_CASE(lockedpool_tests_live)
{
LockedPoolManager &pool = LockedPoolManager::Instance();
LockedPool::Stats initial = pool.stats();
void *a0 = pool.alloc(16);
BOOST_CHECK(a0);
// Test reading and writing the allocated memory
*((uint32_t*)a0) = 0x1234;
BOOST_CHECK(*((uint32_t*)a0) == 0x1234);
pool.free(a0);
try { // Test exception on double-free
pool.free(a0);
BOOST_CHECK(0);
} catch(std::runtime_error &)
{
}
// If more than one new arena was allocated for the above tests, something is wrong
BOOST_CHECK(pool.stats().total <= (initial.total + LockedPool::ARENA_SIZE));
// Usage must be back to where it started
BOOST_CHECK(pool.stats().used == initial.used);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"durgeshkmr4u@gmail.com"
] | durgeshkmr4u@gmail.com |
c9bf4474a1cf1d7a9f3b22b30c070b525e4a7dc0 | 14ce01a6f9199d39e28d036e066d99cfb3e3f211 | /Cpp/SDK/GE_Evo_Shadow_Body_Lunge_ImpactVFX_T3_classes.h | beb51496e56bedd97ac097898cb274a397725bd8 | [] | no_license | zH4x-SDK/zManEater-SDK | 73f14dd8f758bb7eac649f0c66ce29f9974189b7 | d040c05a93c0935d8052dd3827c2ef91c128bce7 | refs/heads/main | 2023-07-19T04:54:51.672951 | 2021-08-27T13:47:27 | 2021-08-27T13:47:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | h | #pragma once
// Name: ManEater, Version: 1.0.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass GE_Evo_Shadow_Body_Lunge_ImpactVFX_T3.GE_Evo_Shadow_Body_Lunge_ImpactVFX_T3_C
// 0x0000 (FullSize[0x0870] - InheritedSize[0x0870])
class UGE_Evo_Shadow_Body_Lunge_ImpactVFX_T3_C : public UME_GameplayEffect
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass GE_Evo_Shadow_Body_Lunge_ImpactVFX_T3.GE_Evo_Shadow_Body_Lunge_ImpactVFX_T3_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
0c51d4681b49c11582b1281de6d6d7599420060d | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtbase/examples/network/blockingfortuneclient/fortunethread.h | fcd876a76171ec8c3869d205c3144be15548326b | [
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-commercial-license",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LGPL-3.0-only",
"LicenseRef-scancode-qt-company-exception-lgpl-2.1",
... | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 2,539 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef FORTUNETHREAD_H
#define FORTUNETHREAD_H
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
//! [0]
class FortuneThread : public QThread
{
Q_OBJECT
public:
FortuneThread(QObject *parent = 0);
~FortuneThread();
void requestNewFortune(const QString &hostName, quint16 port);
void run() Q_DECL_OVERRIDE;
signals:
void newFortune(const QString &fortune);
void error(int socketError, const QString &message);
private:
QString hostName;
quint16 port;
QMutex mutex;
QWaitCondition cond;
bool quit;
};
//! [0]
#endif
| [
"p_pavlov@wargaming.net"
] | p_pavlov@wargaming.net |
c1cfd9aabdb597e6c72f00fde5b447be4c12e3bc | 36385e4ae097d3b662512c32ebbd91fe168491c8 | /Project 1/project_1_milestone_2/radio.cpp | 52f2c4616d1884575d20f4229e4e45bd408119ba | [] | no_license | Gomer3261/CSC460 | 4b84691415fbca5616910b056d9539d0e907014f | 07e405b81b8c04bbf7663a09d4e2b0a8dc9d3df1 | refs/heads/master | 2021-01-25T12:14:42.720413 | 2015-04-07T04:44:05 | 2015-04-07T04:44:05 | 30,769,924 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 13,931 | cpp | /*
* radio.c
*
* Created on: 24-Jan-2009
* Author: Neil MacMillan
*/
#include "radio.h"
// debug
#define DEBUG_1_HIGH PORTH |= _BV(PH3)
#define DEBUG_1_LOW PORTH &= ~_BV(PH3)
#define DEBUG_2_HIGH PORTH |= _BV(PH4)
#define DEBUG_2_LOW PORTH &= ~_BV(PH4)
#define DEBUG_INIT DDRH |= _BV(PH3) | _BV(PH4)
//#define LED_TOGGLE PORTB ^= _BV(PB7)
// non-public constants and macros
#define CHANNEL 106
#define ADDRESS_LENGTH 5
// Pin definitions for chip select and chip enable on the radio module
#define CE_DDR DDRH
#define CSN_DDR DDRH
#define CE_PORT PORTH
#define CSN_PORT PORTH
#define CE_PIN PH5
#define CSN_PIN PH6
// Definitions for selecting and enabling the radio
#define CSN_HIGH() CSN_PORT |= _BV(CSN_PIN);
#define CSN_LOW() CSN_PORT &= ~_BV(CSN_PIN);
#define CE_HIGH() CE_PORT |= _BV(CE_PIN);
#define CE_LOW() CE_PORT &= ~_BV(CE_PIN);
// Flag which denotes that the radio is currently transmitting
static volatile uint8_t transmit_lock;
// tracks the payload widths of the Rx pipes
static volatile uint8_t rx_pipe_widths[6] = {32, 32, 0, 0, 0, 0};
// holds the transmit address (Rx pipe 0 is set to this address when transmitting with auto-ack enabled).
static volatile uint8_t tx_address[5] = { 0xe7, 0xe7, 0xe7, 0xe7, 0xe7 };
// holds the receiver address for Rx pipe 0 (the address is overwritten when transmitting with auto-ack enabled).
static volatile uint8_t rx_pipe0_address[5] = { 0xe7, 0xe7, 0xe7, 0xe7, 0xe7 };
// the driver keeps track of the success status for the last 16 transmissions
static volatile uint16_t tx_history = 0xFF;
static volatile RADIO_TX_STATUS tx_last_status = RADIO_TX_SUCCESS;
extern void radio_rxhandler(uint8_t pipenumber);
/**
* Retrieve the status register.
*/
static uint8_t get_status()
{
uint8_t status = 0;
CSN_LOW();
status = SPI_Write_Byte(NOP);
CSN_HIGH();
return status;
}
/**
* Set a register in the radio
* \param reg The register value defined in nRF24L01.h (e.g. CONFIG, EN_AA, &c.).
* \param value The value to write to the given register (the whole register is overwritten).
* \return The status register.
*/
static uint8_t set_register(radio_register_t reg, uint8_t* value, uint8_t len)
{
uint8_t status;
CSN_LOW();
status = SPI_Write_Byte(W_REGISTER | (REGISTER_MASK & reg));
SPI_Write_Block(value, len);
CSN_HIGH();
return status;
}
/**
* Retrieve a register value from the radio.
* \param reg The register value defined in nRF24L01.h (e.g. CONFIG, EN_AA, &c.).
* \param buffer A contiguous memory block into which the register contents will be copied. If the buffer is too long for the
* register contents, then the remaining bytes will be overwritten with 0xFF.
* \param len The length of the buffer.
*/
static uint8_t get_register(radio_register_t reg, uint8_t* buffer, uint8_t len)
{
uint8_t status, i;
for (i = 0; i < len; i++)
{
// If the buffer is too long for the register results, then the radio will interpret the extra bytes as instructions.
// To remove the risk, we set the buffer elements to NOP instructions.
buffer[i] = 0xFF;
}
CSN_LOW();
status = SPI_Write_Byte(R_REGISTER | (REGISTER_MASK & reg));
SPI_ReadWrite_Block(NULL, buffer, len);
CSN_HIGH();
return status;
}
/**
* Send an instruction to the nRF24L01.
* \param instruction The instruction to send (see the bottom of nRF24L01.h)
* \param data An array of argument data to the instruction. If len is 0, then this may be NULL.
* \param buffer An array for the instruction's return data. This can be NULL if the instruction has no output.
* \param len The length of the data and buffer arrays.
*/
static void send_instruction(uint8_t instruction, uint8_t* data, uint8_t* buffer, uint8_t len)
{
CSN_LOW();
// send the instruction
SPI_Write_Byte(instruction);
// pass in args
if (len > 0)
{
if (buffer == NULL) //
SPI_Write_Block(data, len);
else
SPI_ReadWrite_Block(data, buffer, len);
}
// resynch SPI
CSN_HIGH();
}
/**
* Switch the radio to receive mode. If the radio is already in receive mode, this does nothing.
*/
static void set_rx_mode()
{
uint8_t config;
get_register(CONFIG, &config, 1);
if ((config & _BV(PRIM_RX)) == 0)
{
config |= _BV(PRIM_RX);
set_register(CONFIG, &config, 1);
// the radio takes 130 us to power up the receiver.
_delay_us(65);
_delay_us(65);
}
}
/**
* Switch the radio to transmit mode. If the radio is already in transmit mode, this does nothing.
*/
static void set_tx_mode()
{
uint8_t config;
get_register(CONFIG, &config, 1);
if ((config & _BV(PRIM_RX)) != 0)
{
config &= ~_BV(PRIM_RX);
set_register(CONFIG, &config, 1);
// The radio takes 130 us to power up the transmitter
// You can delete this if you're sending large packets (I'm thinking > 25 bytes, but I'm not sure) because it
// sending the bytes over SPI can take this long.
_delay_us(65);
_delay_us(65);
}
}
/**
* Reset the pipe 0 address if pipe 0 is enabled. This is necessary when the radio is using Enhanced Shockburst, because
* the pipe 0 address is set to the transmit address while the radio is transmitting (this is how the radio receives
* auto-ack packets).
*/
static void reset_pipe0_address()
{
if (rx_pipe_widths[RADIO_PIPE_0] != 0)
{
// reset the pipe 0 address if pipe 0 is enabled.
set_register(RX_ADDR_P0, (uint8_t*)rx_pipe0_address, ADDRESS_LENGTH);
}
}
/**
* Configure radio defaults and turn on the radio in receive mode.
* This configures the radio to its max-power, max-packet-header-length settings. If you want to reduce power consumption
* or increase on-air payload bandwidth, you'll have to change the config.
*/
static void configure_registers(int channel)
{
uint8_t value;
SPI_Init();
// set address width to 5 bytes.
value = ADDRESS_LENGTH - 2; // 0b11 for 5 bytes, 0b10 for 4 bytes, 0b01 for 3 bytes
set_register(SETUP_AW, &value, 1);
// set Enhanced Shockburst retry to every 586 us, up to 5 times. If packet collisions are a problem even with AA enabled,
// then consider changing the retry delay to be different on the different stations so that they do not keep colliding on each retry.
value = 0x15;
//value = 0x10;
set_register(SETUP_RETR, &value, 1);
// Set to use 2.4 GHz channel 110.
value = channel;
set_register(RF_CH, &value, 1);
// Set radio to 2 Mbps and high power. Leave LNA_HCURR at its default.
value = _BV(RF_DR) | _BV(LNA_HCURR);
set_register(RF_SETUP, &value, 1);
// Enable 2-byte CRC and power up in receive mode.
value = _BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP) | _BV(PRIM_RX);
set_register(CONFIG, &value, 1);
// clear the interrupt flags in case the radio's still asserting an old unhandled interrupt
value = _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT);
set_register(STATUS, &value, 1);
// flush the FIFOs in case there are old data in them.
send_instruction(FLUSH_TX, NULL, NULL, 0);
send_instruction(FLUSH_RX, NULL, NULL, 0);
}
void Radio_Init(int channel)
{
transmit_lock = 0;
DEBUG_INIT;
DEBUG_2_LOW;
DEBUG_1_LOW;
// disable radio during config
CE_LOW();
// set as output AT90 pins connected to the radio's slave select and chip enable pins.
CE_DDR |= _BV(CE_PIN);
CSN_DDR |= _BV(CSN_PIN);
// Enable radio interrupt. This interrupt is triggered when data are received and when a transmission completes.
DDRE &= ~_BV(PE4);
EICRB |= _BV(ISC41);
EICRB &= ~_BV(ISC40);
EIMSK |= _BV(INT4);
EIFR |= _BV(INTF4);
//PORTE |= _BV(PE4);
// A 10.3 ms delay is required between power off and power on states (controlled by 3.3 V supply).
_delay_ms(11);
// Configure the radio registers that are not application-dependent.
configure_registers(channel);
// A 1.5 ms delay is required between power down and power up states (controlled by PWR_UP bit in CONFIG)
_delay_ms(2);
// enable radio as a receiver
CE_HIGH();
DEBUG_2_HIGH;
}
// default address for pipe 0 is 0xe7e7e7e7e7
// default address for pipe 1 is 0xc2c2c2c2c2
// default address for pipe 2 is 0xc2c2c2c2c3 (disabled)
// default address for pipe 3 is 0xc2c2c2c2c4 (disabled)
// default address for pipe 4 is 0xc2c2c2c2c5 (disabled)
// default address for pipe 5 is 0xc2c2c2c2c6 (disabled)
void Radio_Configure_Rx(RADIO_PIPE pipe, uint8_t* address, ON_OFF enable)
{
uint8_t value;
uint8_t use_aa = 1;
uint8_t payload_width = 32;
if (payload_width < 1 || payload_width > 32 || pipe < RADIO_PIPE_0 || pipe > RADIO_PIPE_5) return;
// store the pipe 0 address so that it can be overwritten when transmitting with auto-ack enabled.
if (pipe == RADIO_PIPE_0)
{
rx_pipe0_address[0] = address[0];
rx_pipe0_address[1] = address[1];
rx_pipe0_address[2] = address[2];
rx_pipe0_address[3] = address[3];
rx_pipe0_address[4] = address[4];
}
// Set the address. We set this stuff even if the pipe is being disabled, because for example the transmitter
// needs pipe 0 to have the same address as the Tx address for auto-ack to work, even if pipe 0 is disabled.
set_register(RX_ADDR_P0 + pipe, address, pipe > RADIO_PIPE_1 ? 1 : ADDRESS_LENGTH);
// Set auto-ack.
get_register(EN_AA, &value, 1);
if (use_aa)
value |= _BV(pipe);
else
value &= ~_BV(pipe);
set_register(EN_AA, &value, 1);
// Set the pipe's payload width. If the pipe is being disabled, then the payload width is set to 0.
value = enable ? payload_width : 0;
set_register(RX_PW_P0 + pipe, &value, 1);
rx_pipe_widths[pipe] = value;
// Enable or disable the pipe.
get_register(EN_RXADDR, &value, 1);
if (enable)
value |= _BV(pipe);
else
value &= ~_BV(pipe);
set_register(EN_RXADDR, &value, 1);
}
// default transmitter address is 0xe7e7e7e7e7.
void Radio_Set_Tx_Addr(uint8_t* address)
{
tx_address[0] = address[0];
tx_address[1] = address[1];
tx_address[2] = address[2];
tx_address[3] = address[3];
tx_address[4] = address[4];
set_register(TX_ADDR, address, ADDRESS_LENGTH);
}
void Radio_Configure(RADIO_DATA_RATE dr, RADIO_TX_POWER power)
{
uint8_t value;
if (power < RADIO_LOWEST_POWER || power > RADIO_HIGHEST_POWER || dr < RADIO_1MBPS || dr > RADIO_2MBPS) return;
// set the address
//Radio_Set_Tx_Addr(address);
// set the data rate and power bits in the RF_SETUP register
get_register(RF_SETUP, &value, 1);
value |= 3 << RF_PWR; // set the power bits so that the & will mask the power value in properly.
value &= power << RF_PWR; // mask the power value into the RF status byte.
if (dr)
value |= _BV(RF_DR);
else
value &= ~_BV(RF_DR);
set_register(RF_SETUP, &value, 1);
}
uint8_t Radio_Transmit(radiopacket_t* payload, RADIO_TX_WAIT wait)
{
//if (block && transmit_lock) while (transmit_lock);
//if (!block && transmit_lock) return 0;
uint8_t len = 32;
// indicate that the driver is transmitting.
transmit_lock = 1;
// disable the radio while writing to the Tx FIFO.
CE_LOW();
set_tx_mode();
// for auto-ack to work, the pipe0 address must be set to the Tx address while the radio is transmitting.
// The register will be set back to the original pipe 0 address when the TX_DS or MAX_RT interrupt is asserted.
set_register(RX_ADDR_P0, (uint8_t*)tx_address, ADDRESS_LENGTH);
// transfer the packet to the radio's Tx FIFO for transmission
DEBUG_1_HIGH;
send_instruction(W_TX_PAYLOAD, (uint8_t *)payload, NULL, len);
// start the transmission.
CE_HIGH();
if (wait == RADIO_WAIT_FOR_TX)
{
while (transmit_lock);
return tx_last_status;
}
return RADIO_TX_SUCCESS;
}
RADIO_RX_STATUS Radio_Receive(radiopacket_t* buffer)
{
uint8_t len = 32;
uint8_t status;
uint8_t pipe_number;
uint8_t doMove = 1;
RADIO_RX_STATUS result;
transmit_lock = 0;
CE_LOW();
status = get_status();
pipe_number = (status & 0xE) >> 1;
if (pipe_number == RADIO_PIPE_EMPTY)
{
result = RADIO_RX_FIFO_EMPTY;
doMove = 0;
}
if (rx_pipe_widths[pipe_number] > len)
{
// the buffer isn't big enough, so don't copy the data.
result = RADIO_RX_INVALID_ARGS;
doMove = 0;
}
if (doMove)
{
// Move the data payload into the local
send_instruction(R_RX_PAYLOAD, (uint8_t*)buffer, (uint8_t*)buffer, rx_pipe_widths[pipe_number]);
status = get_status();
pipe_number = (status & 0xE) >> 1;
if (pipe_number != RADIO_PIPE_EMPTY)
result = RADIO_RX_MORE_PACKETS;
else
result = RADIO_RX_SUCCESS;
}
CE_HIGH();
transmit_lock = 0;
//release_radio();
return result;
}
// This is only accurate if all the failed packets were sent using auto-ack.
uint8_t Radio_Success_Rate()
{
uint16_t wh = tx_history;
uint8_t weight = 0;
while (wh != 0)
{
if ((wh & 1) != 0) weight++;
wh >>= 1;
}
wh = (16 - weight) * 100;
wh /= 16;
return wh;
}
void Radio_Flush()
{
send_instruction(FLUSH_TX, NULL, NULL, 0);
send_instruction(FLUSH_RX, NULL, NULL, 0);
}
// Interrupt handler
ISR(INT4_vect)
{
uint8_t status;
uint8_t pipe_number;
DEBUG_2_LOW;
CE_LOW();
status = get_status();
if (status & _BV(RX_DR))
{
pipe_number = (status & 0xE) >> 1;
radio_rxhandler(pipe_number);
}
// We can get the TX_DS or the MAX_RT interrupt, but not both.
if (status & _BV(TX_DS))
{
// if there's nothing left to transmit, switch back to receive mode.
transmit_lock = 0;
reset_pipe0_address();
set_rx_mode();
// indicate in the history that a packet was transmitted successfully by appending a 1.
tx_history <<= 1;
tx_history |= 1;
tx_last_status = RADIO_TX_SUCCESS;
}
else if (status & _BV(MAX_RT))
{
send_instruction(FLUSH_TX, NULL, NULL, 0);
transmit_lock = 0;
reset_pipe0_address();
set_rx_mode();
// indicate in the history that a packet was dropped by appending a 0.
tx_history <<= 1;
tx_last_status = RADIO_TX_MAX_RT;
}
// clear the interrupt flags.
status = _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT);
set_register(STATUS, &status, 1);
DEBUG_2_HIGH;
CE_HIGH();
}
| [
"Geoff@Geoffreys-MacBook-Pro.local"
] | Geoff@Geoffreys-MacBook-Pro.local |
c66ab4fc7bdf4f2ee403cacbe4e7a34782d87c01 | cc13c060d7d3ed555d68073c770fc0aca3c67f82 | /codeforces/679-codeforces-round-356/B.cpp | 95ca0e71733e30e2378eff7733b4891fa6293966 | [] | no_license | Devang-25/acm-icpc | 8bd29cc90119a6269ccd61729d8e67a8b642b131 | a036bdbba60f8b363ee2d6cb9814e82e5536e02e | refs/heads/master | 2022-04-01T02:52:51.367994 | 2020-01-24T11:46:01 | 2020-01-24T11:46:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | cpp | #include <algorithm>
#include <iostream>
#include <map>
#include <utility>
#include <vector>
typedef long long Long;
std::vector<Long> volume;
std::vector<std::pair<int, Long>> memory;
std::pair<int, Long> solve(Long n)
{
std::pair<int, Long> tmp {-1, 0};
auto index = std::upper_bound(volume.begin(), volume.end(), n) - volume.begin();
auto& ref = n + 1 == volume.at(index) ? memory.at(index) : tmp;
if (~ref.first) {
return ref;
}
auto a = volume.at(index - 1);
auto c = n / a;
auto p = solve(n % a);
auto q = solve(a - 1);
auto result = std::max(std::make_pair(p.first + c, p.second + c * a), std::make_pair(q.first + c - 1, q.second + (c - 1) * a));
return ref = result;
}
int main()
{
Long n;
std::cin >> n;
for (Long a = 1; ; ++ a) {
Long c = a * a * a;
volume.push_back(c);
memory.push_back({-1, 0});
if (c > n) {
break;
}
}
memory[0] = {0, 0};
auto result = solve(n);
std::cout << result.first << " " << result.second << std::endl;
}
| [
"ftiasch0@gmail.com"
] | ftiasch0@gmail.com |
2ad5184284ed44772e954360b71daf6594e993ad | 3117b8eeb7f787a0713fb9bd62fd30d98c01e014 | /TheLittleGameEngine/Events/KeyEvent.h | 09ca9e044f6aa14587f515612d463fadbcc83ec9 | [] | no_license | EmilioLapointe/ProjectNotSummer | 1ecbcc8e19f997432dc6bab4372bf5bcbf050840 | 4db725d3021463920041394a0c057b5ccb6122e5 | refs/heads/master | 2020-04-09T21:22:25.781723 | 2019-04-04T01:32:22 | 2019-04-04T01:32:22 | 160,600,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,150 | h | #ifndef __TLGE__KEY_EVENT_H__
#define __TLGE__KEY_EVENT_H__
namespace TLGE
{
enum KeyState
{
KeyState_JustPressed,
KeyState_Unpressed,
NumKeyStates,
KeyState_Invalid
};
/**************************************************************************
* KeyEvent is passed when a key of some sort is pressed or released *
* *
* Important notes: *
* - visit https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
* for key codes *
***************************************************************************/
class KeyEvent : public Event
{
public:
//Event type is set on creation and cannot be changed
KeyEvent();
virtual ~KeyEvent();
//Getters
unsigned char GetKey() { return m_key; }
KeyState GetState() { return m_state; }
//Setters
void SetKey(unsigned char key) { m_key = key; }
void SetState(KeyState state) { m_state = state; }
private:
KeyState m_state;
unsigned char m_key;
};
}
#endif | [
"emirolap@hotmail.com"
] | emirolap@hotmail.com |
ef554eca6c8e29ff00b3fc9df9bdd3bc4b48945b | 98c7f1fa649e716d16658d367cdded9b5d98b7b3 | /cudaWraperL300/testCudaWrapperL300/kernel.cpp | bb77735d605f30cd9fa036add879a6befd1aabc1 | [] | no_license | laszlo-avotra-tips/cudaUnitTest | 394d64c365fdba5819d0b7c45f6a1f7a2a999dc9 | ba379d0ce839c3199d32a33c70a36bcd35a8f2b4 | refs/heads/master | 2020-12-10T17:03:07.102164 | 2020-01-24T15:10:19 | 2020-01-24T15:10:19 | 233,653,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | cpp | #include "../cudaWraperL300/cudaWrapperL300.h"
#include <stdio.h>
#include <vector>
int main()
{
const size_t arraySize = 5;
const int a[arraySize] { 1, 2, 3, 4, 7 };
const int b[arraySize] { 10, 20, 30, 40, 50 };
int c[arraySize] {};
// Add vectors in parallel.
if(!addTwoVectors(c, a, b, arraySize)){
fprintf(stderr, "addWithCuda failed!");
return 1;
}
printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
c[0], c[1], c[2], c[3], c[4]);
resetCuda();
return 0;
}
| [
"57722657+laszlo-avotra-tips@users.noreply.github.com"
] | 57722657+laszlo-avotra-tips@users.noreply.github.com |
1bb81f07ebcd57bcfaa80147fa08a6fd04d19c01 | 41d6b7e3b34b10cc02adb30c6dcf6078c82326a3 | /src/plugins/qrosp/scriptloaderinstance.h | dac2bf42491558b56611f5cf18e010031af8b740 | [
"BSL-1.0"
] | permissive | ForNeVeR/leechcraft | 1c84da3690303e539e70c1323e39d9f24268cb0b | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | refs/heads/master | 2020-04-04T19:08:48.065750 | 2016-11-27T02:08:30 | 2016-11-27T02:08:30 | 2,294,915 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,362 | h | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#pragma once
#include <QObject>
#include <QStringList>
#include <util/sys/resourceloader.h>
#include <interfaces/iscriptloader.h>
namespace LeechCraft
{
namespace Qrosp
{
class ScriptLoaderInstance : public QObject
, public IScriptLoaderInstance
{
Q_OBJECT
Q_INTERFACES (IScriptLoaderInstance)
mutable QHash<QString, QString> ID2Interpereter_;
Util::ResourceLoader Loader_;
public:
ScriptLoaderInstance (const QString&, QObject* = nullptr);
QObject* GetQObject ();
void AddGlobalPrefix ();
void AddLocalPrefix (QString prefix);
QStringList EnumerateScripts () const;
QVariantMap GetScriptInfo (const QString&);
IScript_ptr LoadScript (const QString&);
};
}
}
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
6815a0d7b820906b89e12538bb2079970e98f352 | 1cc4727469951710751e9c46d4e578cacc0ec141 | /jp2_pc/Source/Lib/Transform/GeomTest.cpp | 3cf7b17c50d6fa682f19a65d81b5d45e8a0204ee | [] | no_license | FabulaM24/JurassicParkTrespasserAIrip | 60036b6a0196f33b42bdc7f6e4c984ef39a813f4 | 081c826b723a5fef2b318009fdaf13a27af908a5 | refs/heads/master | 2023-07-15T20:49:47.505140 | 2020-05-13T12:57:52 | 2020-05-13T12:57:52 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 14,904 | cpp | /***********************************************************************************************
*
* Copyright © DreamWorks Interactive. 1996
*
* Geometry testing code. Not style-compliant. Leave me alone.
*
***********************************************************************************************
*
* $Log:: /JP2_PC/Source/Lib/Transform/GeomTest.cpp $
*
* 23 97/09/26 16:51 Speter
* Added timing code.
*
* 22 97-03-31 22:26 Speter
* Updated for changes in transforms.
*
* 21 96/12/09 16:07 Speter
* Removed CTimer calls.
*
* 20 96/11/11 14:44 Speter
*
* 19 96/10/28 15:00 Speter
* Changed CEventHandler to CAppShell.
*
* 18 96/09/27 11:31 Speter
* Oops. Changed <float> in geometry types to <>.
*
* 17 96/09/25 19:50 Speter
* The Big Change.
* In transforms, replaced TReal with TR, TDefReal with TReal.
* Replaced all references to transform templates that have <TObjReal> with <>.
* Replaced TObjReal with TReal, and "or" prefix with "r".
* Replaced CObjPoint, CObjNormal, and CObjPlacement with equivalent transform types, and
* prefixes likewise.
* Removed some unnecessary casts to TReal.
* Finally, replaced VER_GENERAL_DEBUG_ASSERTS with VER_DEBUG.
*
* 16 96/09/23 17:09 Speter
* Added some test code for transformations to texture surfaces.
*
* 15 96/09/16 12:26 Speter
* Added test for fixed point Fuzzy.
*
* 14 96/09/09 18:33 Speter
* Added more test code.
*
* 13 96/08/21 18:58 Speter
* Updated for new transform functions.
*
* 12 96/08/01 13:44 Speter
* Changes to test quat renorm.
*
* 11 96/07/31 15:53 Speter
* Added timing stats.
*
* 10 7/19/96 10:58a Pkeet
* Changed include files for shell files moved to 'Shell.'
*
* 9 96/07/08 12:40 Speter
* Changed name of CNormal3 to CDir3 (more general).
* Added specific functions to transform directions, which do not translate positions.
*
* 8 96/07/03 13:02 Speter
* Moved several files to new directories, and changed corresponding include statements.
*
* 7 96/06/27 11:05 Speter
* Fixed quaternion multiplication. It was backwards.
*
* 6 96/06/26 22:07 Speter
* Added a bunch of comments, prettied things up nicely.
*
* 5 96/06/26 15:05 Speter
* Changed CPosition3 to CPlacement3.
*
* 4 96/06/26 13:16 Speter
* Changed TGReal to TReal and prefix gr to r.
*
* 3 96/06/25 14:35 Speter
* Finalised design of transform classes, with Position3 and Transform3.
*
* 2 96/06/20 17:12 Speter
* Converted into templates and made necessary changes.
*
* 1 96/06/20 15:26 Speter
* First version of new optimised transform library.
*
**********************************************************************************************/
/* Renorm # Denorm Time
Avg Max Max Debug Release
Never renorm 1.6 us
Always check, renorm 14K .0001 10.3 us 1.7 us
Always renorm 2.3 us
Random (100), renorm 5K 300K .01 8.4 us 1.9 us
Check count, renorm 1.4K .00002 8.1 us 1.5 us
*/
#include "Common.hpp"
#include "Transform.hpp"
#include "Lib/Sys/Textout.hpp"
#include "Shell/AppShell.hpp"
#include <memory.h>
#define TIMIT 0
#define RENORM 0
#define iFACTOR 100
#if RENORM
class CAppShellGeom: public CAppShell
{
public:
TMSec msCycle;
int iCount;
CRotate3<> r3a, r3b, r3c;
CAppShellGeom()
: r3a(), r3b(), r3c('xyz', 0.01, 0.02, 0.03)
{
}
void Init()
{
iCount = msCycle = 0;
SetContinuous(1);
}
void Step()
{
CTimer tmr;
for (int i = 0; i < iFACTOR; i++)
{
r3b *= r3c;
r3a *= r3b;
}
msCycle += tmr.msElapsed();
iCount += iFACTOR;
conStd.SetCursorPosition(0, 0);
conStd.Print("Time = %f, Count = %d, Debug = %d \n",
(float) msCycle / iCount, iCount, VER_DEBUG);
#if VER_DEBUG
conStd.Print("Avg norm count = %d, Max denorm = %f, count = %d \n",
CRotate3<>::iAvgNormalisationCount,
CRotate3<>::tMaxDenormalisation,
CRotate3<>::iMaxDenormalisationCount);
#endif
conStd.Show();
}
};
#else
/*
Plans:
Current:
Basic transform types. They all combine.
Composite types: template, basic + vector.
Combining all is hairy.
Union:
Basic transform types. They all combine.
Transform = union of basics, + vector.
Combining anything with a translation results in a Transform.
Used only for intermediate calculations. Base transforms can be stored optimally.
Just matrix:
Basic transform types. They all combine.
Transform = matrix, + vector.
Combining anything with a translation results in a Transform.
Calculations needed: MT ?T *T
Camera:
Norm = Scale * Shear Xm = S * Hm Xm = S * Hm M = S * Hm
Camera = ~(RT) * Norm XmT = MT(~RT) * Xm XmT = MT(~RT) * Xm MT = MT(~RT) * M
Objects:
RT
or SRT
Camera.T * ~RT XmT = XmT * MT(~RT) XmT = XmT * MT(~RT) MT * MT(~RT)
or ~SRT XmT = XmT * MT(~SRT) XmT = XmT * MT(~SRT) MT * MT(~SRT)
Subobjects (skeletons):
RT = RT*RT RT = RT * RT XrT = RT * RT RT = RT * RT
or XrT = XrT * RT
Poly:
Poly = Object * Camera XmT = XmT(RT) * XmT XmT = MT(RT) * XmT MT = MT(RT) * MT
XmT = XmT(SRT) * XmT XmT = XmT(SRT) * XmT MT = MT(SRT) * MT
Vertex:
V * Poly V * XmT V * XmT V * MT
*/
CVector3<> v3_a(6, -5, 1.5), v3_b(1, 0, 0.4);
CDir3<> d3_a = v3_a, d3_b = v3_b;
CMatrix3<> mx3(1, 0, 3, 0, 3, 2, 7, 4, 0);
CRotate3<> r3(d3_a, d3_b);
CScale3<> s3(2, 0.5, -1);
CScaleI3<> si3(4);
CTranslate3<> tl3(-4, 0, 2);
CPlacement3<> p3(r3, v3_a);
CTransform3<> tf3(mx3, v3_b);
template<class T> inline bool operator ==(const T& t1, const T& t2)
{
return memcmp(&t1, &t2, sizeof(T)) == 0;
}
inline bool operator ==(const CVector3<>& v3_a, const CVector3<>& v3_b)
{
return bFurryEquals(v3_a.tX, v3_b.tX) &&
bFurryEquals(v3_a.tY, v3_b.tY) &&
bFurryEquals(v3_a.tZ, v3_b.tZ);
}
template<class T1, class T2> void GeomTest2(const T1& t1, const T2& t2)
{
CVector3<> v3(1, 10, 100);
CVector3<> v3_2, v3_3;
if (~(t1*t2) == ~t2*~t1)
;
else
{
v3_2 = v3 * ~(t1*t2);
v3_3 = v3 * ~t2*~t1;
Assert(v3_2 == v3_3);
}
v3_2 = v3 * t1 * t2;
v3 *= t1;
v3 *= t2;
Assert(v3_2 == v3);
}
template<class T3> void GeomTest(const T3& t3)
{
CVector3<> v3(1, 10, 100);
T3 t3_identity;
T3 t3_inv = ~t3;
t3_identity = t3_inv * t3;
CVector3<> v3_check = v3 * t3_identity;
Assert(v3 == v3_check);
CVector3<> v3_2 = v3 * t3;
v3 *= t3;
Assert(v3 == v3_2);
t3_inv = t3 * t3;
t3_identity = t3;
t3_identity *= t3;
Assert(t3_inv == t3_identity);
GeomTest2(t3, CMatrix3<>(2, -4, 1, 2, 0, 5, 0, 1, -1));
GeomTest2(t3, CRotate3<>
(
SFrame3<>(CDir3<>(1, 0, 3), d3YAxis),
SFrame3<>(d3XAxis, CDir3<>(0, 6, -1))
));
GeomTest2(t3, CScale3<>(1, 1.04, 0.02));
GeomTest2(t3, CScaleI3<>(-2.5));
GeomTest2(t3, CShear3<>(d3ZAxis, 0.1, -0.2));
GeomTest2(t3, CTranslate3<>(4, 2, -0.4));
GeomTest2(t3, CPlacement3<>
(
CRotate3<>(CDir3<>(1, 0.5, 0.3), CAngle(2.6)),
CVector3<>(5, 6, 7)
));
GeomTest2(t3, CTransform3<>(CMatrix3<>(2, 1, 0, 9, 0, 3, 7, 1, 0), CVector3<>(0.1, 0, -6)));
}
template<class T3> void GeomTestDir(const T3& t3)
{
CVector3<> v3(1, 10, 100);
CDir3<> d3 = v3;
CDir3<> d3_2 = d3 * t3;
d3 *= t3;
Assert(d3 == d3_2);
}
template<class T3> void GeomTestPlusDir(const T3& t3)
{
GeomTest(t3);
GeomTestDir(t3);
}
class CAppShellGeom: public CAppShell
{
public:
void Init()
{
#if TIMIT
SetContinuous(1);
}
void Step()
{
CTimer tmr;
#endif
for (int i = 0; i < iFACTOR; i++)
{
/*
Find the transformation which maps a 3-D triangle onto a 2-D texture.
!! This is not determinate !!
Given:
Polygon vertices v0, v1, v2;
Texture vertices t0, t1, t2; each with Z value arbitrary
Find:
Matrix M, such that
v * M = t
v:0:x,y,z,1 * M:x:x,y,0,0 = t:0:x,y,0,1
1:x,y,z,1 y:x,y,0,0 1:x,y,0,1
2:x,y,z,1 z:x,y,0,0 2:x,y,0,1
?:?,?,?,? t:x,y,0,1 ?:?,?,?,?
v:0:x,y,z,1 * M:x:x,y = t:0:x,y
1:x,y,z,1 y:x,y 1:x,y
2:x,y,z,1 z:x,y 2:x,y
t:x,y
3.4 * 4.2 = 3.2
Then:
M = ~v * t
4.3 * 3.2 = 4.2
3x4:
~(M+T) = (~M - T*~M)
*/
/*
CVector3<> poly[3] = {CVector3<>(2, 4, 7), CVector3<>(0, 0, 0), CVector3<>(9, 3, 2)};
CVector3<> tex[3] = {CVector3<>(4, 6, 0), CVector3<>(7, 3, 0), CVector3<>(1, 5, 0)};
CTransform3<> xform =
~CTransform3<>(CMatrix3<>(poly[0], poly[1], poly[2])) *
CTransform3<>(CMatrix3<>(tex[0], tex[1], tex[2]));
CVector3<> tex2[3] = {poly[0] * xform, poly[1] * xform, poly[2] * xform};
Assert(tex2[0] == tex[0]);
Assert(tex2[1] == tex[1]);
Assert(tex2[2] == tex[2]);
*/
fixed a = 3.00, b = 3.01;
if (Fuzzy(a) != b)
a = b;
GeomTestPlusDir(CMatrix3<>(1, 0, 3, 0, 3, 2, 7, 4, 0));
GeomTestPlusDir(CRotate3<>(d3XAxis, 0.2) * CRotate3<>(d3YAxis, 0.4) * CRotate3<>(d3ZAxis, 0.5));
GeomTest(CScale3<>(3, 0.5, -1));
GeomTest(CScaleI3<>(4));
GeomTest(CShear3<>('y', 0, -0.4));
GeomTest(CTranslate3<>(6, -5, 1.5));
GeomTest(CPlacement3<>(CRotate3<>(d3YAxis, -2.22), CVector3<>(0.5, 3.2, -6.7)));
GeomTest(CTransform3<>(CMatrix3<>(0, 9, 1, 8, 5, 0, 2, 0, 6), CVector3<>(-9.1, 6, 0)));
Assert(CRotate3<>(CDir3<>(1, 0, 0), CAngle(1)) == CRotate3<>(d3XAxis, 1));
Assert(CRotate3<>(CDir3<>(-1, 4, 3), 2) ==
CRotate3<>(d3XAxis, 1) * CRotate3<>(d3ZAxis, 2) * CRotate3<>(d3YAxis, 3));
Assert(CVector3<>(d3XAxis * r3) == CVector3<>(1, 0, 0) * r3);
Assert(CVector3<>(d3YAxis * r3) == CVector3<>(0, 1, 0) * r3);
Assert(CVector3<>(d3ZAxis * r3) == CVector3<>(0, 0, 1) * r3);
tf3 = p3;
tf3 = mx3 = r3;
tf3 = mx3;
tf3 = mx3 = s3;
tf3 = mx3 = si3;
// tf3 = tl3.v3T;
p3 = r3;
mx3 = r3;
mx3 = s3;
mx3 = si3;
s3 = si3;
}
#if TIMIT
msStep += tmr.msElapsed();
StatDB.iCount++;
conStd.SetCursorPosition(0, 0);
conStd.Print("Time = %f ", (float) msStep / StatDB.iCount, iFACTOR);
conStd.Show();
#else
TerminateShell();
#endif
}
void NewRaster()
{
}
void Resize()
{
}
void Paused(bool b_paused)
{
}
void Paint()
{
}
};
#endif
CAppShell* pappMain = new CAppShellGeom;
#include "Lib/Sys/Profile.hpp"
#include "Lib/Sys/DebugConsole.hpp"
//******************************************************************************************
//
class CGeomTimer
//
//**************************************
{
public:
CGeomTimer()
{
CProfileStatMain psMain;
psMain.Add(0, 1);
CProfileStat psVecMatrix("v3 * mx3", &psMain);
CProfileStat psVecTransform("v3 * tf3", &psMain);
CProfileStat psVecRotate("v3 * r3", &psMain);
CProfileStat psVecPlacement("v3 * p3", &psMain);
CProfileStat psVecPresence("v3 * pr3", &psMain);
CProfileStat psDirMatrix("d3 * mx3", &psMain);
CProfileStat psDirTransform("d3 * tf3", &psMain);
CProfileStat psDirRotate("d3 * r3", &psMain);
CProfileStat psDirPlacement("d3 * p3", &psMain);
CProfileStat psDirPresence("d3 * pr3", &psMain);
CProfileStat psMatrix("mx3 * mx3", &psMain);
CProfileStat psTransform("tf3 * tf3", &psMain);
CProfileStat psRotate("r3 * r3", &psMain);
CProfileStat psPlacement("p3 * p3", &psMain);
CProfileStat psPresence("pr3 * pr3", &psMain);
CProfileStat psMatrixRotate("mx3 = r3", &psMain);
CProfileStat psTransformPlacement("tf3 = p3", &psMain);
CProfileStat psTransformPresence("tf3 = pr3", &psMain);
CProfileStat psMatrixInv("~mx3", &psMain);
CProfileStat psTransformInv("~tf3", &psMain);
CProfileStat psRotateInv("~r3", &psMain);
CProfileStat psPlacementInv("~p3", &psMain);
CProfileStat psPresenceInv("~pr3", &psMain);
const int iREP = 100, iREP_TOTAL = 100;
CVector3<> av3[iREP];
CDir3<> ad3[iREP];
CPresence3<> apr3[iREP];
CPlacement3<> ap3[iREP];
CRotate3<> ar3[iREP];
CTransform3<> atf3[iREP];
CMatrix3<> amx3[iREP];
for (int i = 0; i < iREP; i++)
{
av3[i] = v3Random();
ad3[i] = av3[i];
apr3[i] = pr3Random();
ap3[i] = apr3[i];
ar3[i] = apr3[i].r3Rot;
atf3[i] = apr3[i];
amx3[i] = atf3[i].mx3Mat;
}
CVector3<> av3_t[iREP];
CDir3<> ad3_t[iREP];
CMatrix3<> amx3_t[iREP];
CTransform3<> atf3_t[iREP];
CRotate3<> ar3_t[iREP];
CPlacement3<> ap3_t[iREP];
CPresence3<> apr3_t[iREP];
for (int i_loop = 0; i_loop < iREP_TOTAL; i_loop++)
{
CCycleTimer ctmr;
int i;
// Vector.
for (i = 0; i < iREP; i++)
av3_t[i] = av3[i] * amx3[i];
psVecMatrix.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
av3_t[i] = av3[i] * atf3[i];
psVecTransform.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
av3_t[i] = av3[i] * ar3[i];
psVecRotate.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
av3_t[i] = av3[i] * ap3[i];
psVecPlacement.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
av3_t[i] = av3[i] * apr3[i];
psVecPresence.Add(ctmr(), iREP);
// Dir.
for (i = 0; i < iREP; i++)
ad3_t[i] = ad3[i] * amx3[i];
psDirMatrix.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ad3_t[i] = ad3[i] * atf3[i];
psDirTransform.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ad3_t[i] = ad3[i] * ar3[i];
psDirRotate.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ad3_t[i] = ad3[i] * ap3[i];
psDirPlacement.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ad3_t[i] = ad3[i] * apr3[i];
psDirPresence.Add(ctmr(), iREP);
// Self.
for (i = 0; i < iREP; i++)
amx3_t[i] = amx3[i] * amx3[i];
psMatrix.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
atf3_t[i] = atf3[i] * atf3[i];
psTransform.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ar3_t[i] = ar3[i] * ar3[i];
psRotate.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ap3_t[i] = ap3[i] * ap3[i];
psPlacement.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
apr3_t[i] = apr3[i] * apr3[i];
psPresence.Add(ctmr(), iREP);
// Convert.
for (i = 0; i < iREP; i++)
amx3_t[i] = ar3[i];
psMatrixRotate.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
atf3_t[i] = ap3[i];
psTransformPlacement.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
atf3_t[i] = apr3[i];
psTransformPresence.Add(ctmr(), iREP);
// Inverse.
for (i = 0; i < iREP; i++)
amx3_t[i] = ~amx3[i];
psMatrixInv.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
atf3_t[i] = ~atf3[i];
psTransformInv.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ar3_t[i] = ~ar3[i];
psRotateInv.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
ap3_t[i] = ~ap3[i];
psPlacementInv.Add(ctmr(), iREP);
for (i = 0; i < iREP; i++)
apr3_t[i] = ~apr3[i];
psPresenceInv.Add(ctmr(), iREP);
}
CStrBuffer strbuf(4000);
psMain.WriteToBuffer(strbuf);
dprint(strbuf);
}
};
static CGeomTimer GeomTimer;
| [
"crackedcomputerstudios@gmail.com"
] | crackedcomputerstudios@gmail.com |
a6df96f4f8d3a0b1e0c917c6d38747161c4160b8 | 09ab08f51d8a0ef6ae86aa5d3c2e3b3f01a775bd | /C_C++/examples/Hubbard/Examples/Ex1401.cpp | 52396e861ce97553db1d37606855fac600dad467 | [] | no_license | oconnellamethyst/csci1113 | 7beb093b7a619362de460f6a296afabf47bddc8d | 7f099756753b9b3bbd467d9327179b71b02ae673 | refs/heads/master | 2020-03-18T12:58:58.246400 | 2018-06-29T20:59:16 | 2018-06-29T20:59:16 | 134,754,110 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 596 | cpp | // Programming with C++ by John R. Hubbard
// Copyright McGraw-Hill, 1999
// Example 14.1 on page
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void load(vector<string>&);
void print(vector<string>);
const int SIZE=8;
int main()
{ vector<string> v(SIZE);
load(v);
print(v);
}
void load(vector<string>& v)
{ v[0] = "Japan";
v[1] = "Italy";
v[2] = "Spain";
v[3] = "Egypt";
v[4] = "Chile";
v[5] = "Zaire";
v[6] = "Nepal";
v[7] = "Kenya";
}
void print(vector<string> v)
{ for (int i=0; i<SIZE; i++)
cout << v[i] << endl;
cout << endl;
}
| [
"oconnellamethyst@gmail.com"
] | oconnellamethyst@gmail.com |
19a607ae0c682d38aab13708c880006680bff2a5 | f14b33109e39b7cbec8f2e92ac788aa9ca04eea5 | /Benchmark/main.cpp | fe97e58ca9b9bce93cc8575c120c43ce8268468f | [] | no_license | xSeditx/Benchmark | 9db81d1abfd741f515c6021d4fa5f0c6fadafece | 8f59ba2a0cf6472914c3ee0819bcd92ec1ad73e8 | refs/heads/master | 2020-08-12T22:39:38.652752 | 2019-10-23T09:47:11 | 2019-10-23T09:47:11 | 214,856,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | #include"Benchmark.h"
#include"Window.h"
#include<array>
#include<vector>
#include<list>
const int Samples = 1000;
#include<map>
#include<unordered_map>
using namespace std;
#define CAT(str, in) str##in
//http://index-of.co.uk/Game-Development/Programming/
int main()
{
Window Win(1400, 800, "Benchmark Tests");
std::map<std::string, int> A;
std::unordered_map<std::string, int> B;
// std::string C = std::string(CAT(Tag, 10));
for (int i{ 0 }; i < Samples; ++i)
{
std::string Num = std::to_string(i);
A.insert({ std::string("Tag") + Num , i });
B.insert({ std::string("Tag") + Num , i });
}
BENCH_MARK(BENCHA, Samples)
for (unsigned int H{ 0 }; H < i; ++H)
{
std::string Num = std::to_string(H);
B[std::string("Tag") + Num] = i;
}
END_BENCHMARK(BENCHA);
BENCH_MARK(BENCHB, Samples)
for (unsigned int H{ 0 }; H < i; ++H)
{
std::string Num = std::to_string(H);
A[std::string("Tag") + Num] = i;
}
END_BENCHMARK(BENCHB);
DISPLAY_BENCHMARKS
DISPLAY(BENCHA);
DISPLAY(BENCHB);
DISPLAY_END
}
//for (int a =1; a < 10000; ++a)
//{
// B[i] = B[i] / a;
//}
| [
"none"
] | none |
356afb839fde7508d1adad3a8d0e4385a184bbdc | b9323b66afe9a52c456bf4e20b459eb641cd059b | /src/localizer.cc | 020f1570538b3adc152a92d1d4f1e32f5d35e21e | [] | no_license | stack-of-tasks/sot-motion-planner | 896a1bef9d79d851ff9598de3416cb5c2c5fa863 | a5f1e8dcfefd31a0d24e0fca7a7636a637283719 | refs/heads/master | 2020-05-25T11:18:22.174623 | 2015-01-15T16:10:49 | 2015-01-15T16:10:49 | 1,294,709 | 1 | 1 | null | 2015-01-15T16:12:03 | 2011-01-26T09:31:52 | C++ | UTF-8 | C++ | false | false | 12,061 | cc | // Copyright 2011, Thomas Moulard, CNRS.
//
// This file is part of sot-motion-planner.
// sot-motion-planner 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.
//
// sot-motion-planner is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// sot-motion-planner. If not, see <http://www.gnu.org/licenses/>.
#include <algorithm>
#include <string>
#include <fstream>
#include <boost/assign/list_of.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <jrl/mal/boost.hh>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/null-ptr.hh>
#include <dynamic-graph/signal-time-dependent.h>
#include <dynamic-graph/signal-ptr.h>
#include <sot/core/matrix-homogeneous.hh>
#include <sot/core/matrix-rotation.hh>
#include <sot/core/vector-roll-pitch-yaw.hh>
#include <dynamic-graph/command.h>
#include "common.hh"
// Python:
//
// blobObserver = LandmarkObservation()
// blobObserver.setFeatureTrajectory((0, 0, 0, 0, ...))
//
//
// l = Localizer()
//
// l.addLandmarkObservation(name)
//
//
//
//
class Localizer;
namespace command
{
class AddLandmarkObservation;
} // end of namespace command.
struct LandmarkObservation
{
typedef dg::SignalPtr<sot::MatrixHomogeneous, int> signalInMatrixHomo_t;
typedef dg::SignalPtr<ml::Matrix, int> signalInMatrix_t;
typedef dg::SignalPtr<ml::Vector, int> signalInVector_t;
explicit LandmarkObservation (Localizer& localizer,
const std::string& signalNamePrefix);
/// \name Input signals
/// \{
/// \brief Variation of the sensor position w.r.t. the robot
/// configuration.
///
/// JsensorPosition_ = \frac{ds_i}{dq}
///
/// dq[0] dq[1] dq[2]
/// s_i(q)[0]
/// s_i(q)[1]
/// s_i(q)[2]
///
/// Here only (x,y, theta) columns are interesting.signalInVector_t
signalInMatrix_t JsensorPosition_;
/// \brief Expected current position of the feature.
///
/// Read from motion plan.
signalInVector_t featureReferencePosition_;
/// \brief Variation of the feature position w.r.t the sensor
/// position.
///
/// JfeatureReferencePosition_ = \frac{dP_{S_i,L_j}}{ds}(s_i(q0), l_j)
///
/// sensor_x sensor_y sensor_z
/// feature_x
/// feature_y
/// feature_z
signalInMatrix_t JfeatureReferencePosition_;
/// \brief Current real feature position as detected by the sensor.
signalInVector_t featureObservedPosition_;
/// \brief Current weight of this landmark observation.
/// This is a vector of N elements, where N is the dimension
/// of the feature space.
signalInVector_t weight_;
/// \brief Degrees of freedom that will be corrected by the
/// algorithm.
///
/// This vector is expressed as a list of boolean values, true
/// meaning that the DoF is considered, false that the configuration
/// value will be discarded.
///
/// For instance:
/// (true, true, false)
/// ...means that only the first two DoF will be taken into account.
///
/// Additionally, it means that the size of the offset output signal
/// of the localizer will be 2.
signalInVector_t correctedDofs_;
/// \}
};
namespace command
{
using ::dynamicgraph::command::Command;
using ::dynamicgraph::command::Value;
// Command SetFiles
struct AddLandmarkObservation : public Command
{
virtual ~AddLandmarkObservation ()
{}
explicit AddLandmarkObservation
(Localizer& entity, const std::string& docstring);
virtual Value doExecute ();
};
} // end of namespace command.
namespace ublas = boost::numeric::ublas;
class Localizer : public dg::Entity
{
DYNAMIC_GRAPH_ENTITY_DECL ();
public:
typedef dg::SignalTimeDependent<ml::Vector, int> signalOutVector_t;
explicit Localizer (const std::string& name);
size_t getFinalProblemSize (int t) const
{
size_t acc = 0;
BOOST_FOREACH (const boost::shared_ptr<LandmarkObservation> obs,
this->landmarkObservations_)
acc += obs->featureReferencePosition_ (t).size ();
return acc;
}
ublas::vector<double> computeFeatureOffset (int t)
{
using namespace boost::numeric::ublas;
size_t size = getFinalProblemSize (t);
vector<double> featureDelta (size);
// Compute im - im0.
unsigned i = 0;
BOOST_FOREACH (const boost::shared_ptr<LandmarkObservation> obs,
this->landmarkObservations_)
{
const vector<double>& featureObservedPos =
obs->featureObservedPosition_ (t).accessToMotherLib ();
const vector<double>& featureReferencePos =
obs->featureReferencePosition_ (t).accessToMotherLib ();
const vector<double>& weight =
obs->weight_ (t).accessToMotherLib ();
range r (i, i + featureReferencePos.size ());
vector_range<vector<double> > vr (featureDelta, r);
vr = featureObservedPos - featureReferencePos;
// Multiply by weight.
for (unsigned idx = 0; idx < weight.size (); ++idx)
vr[idx] *= weight[idx];
i += featureReferencePos.size ();
}
std::cout << "Feature delta:" << std::endl
<< featureDelta << std::endl;
return featureDelta;
}
size_t
nbConsideredDofs (const boost::shared_ptr<LandmarkObservation> obs, int t)
{
assert (obs);
const ml::Vector& correctedDofs = obs->correctedDofs_ (t);
size_t nbDofs = 0;
for (size_t i = 0; i < correctedDofs.size (); ++i)
if (correctedDofs (i) == 1.)
++nbDofs;
return nbDofs;
}
ublas::matrix<double>
extractConsideredDofs (const boost::shared_ptr<LandmarkObservation> obs,
const ublas::matrix<double>& M, int t)
{
typedef ublas::matrix_column<ublas::matrix<double> > column_t;
typedef ublas::matrix_column<const ublas::matrix<double> > constColumn_t;
const ml::Vector& correctedDofs = obs->correctedDofs_ (t);
size_t nbDofs = nbConsideredDofs (obs, t);
ublas::matrix<double> res (M.size1 (), nbDofs);
if (!nbDofs)
return res;
// Search for first considered DoF.
size_t j = 0u;
while (j < correctedDofs.size () && correctedDofs (j) != 1.)
++j;
for (size_t i = 0; i < nbDofs; ++i)
{
assert (correctedDofs (j));
// Fill the appropriate column.
column_t (res, i) = constColumn_t (M, j);
// Search for next considered DoF.
++j;
while (j < correctedDofs.size() && correctedDofs (j) != 1.)
++j;
}
std::cout << "Extract (before):" << std::endl
<< M << std::endl
<< "Extract (after):" << std::endl
<< res << std::endl;
return res;
}
ublas::matrix<double> computeW (int t)
{
using namespace boost::numeric::ublas;
matrix<double> W (getFinalProblemSize (t), 3);
unsigned i = 0;
BOOST_FOREACH (const boost::shared_ptr<LandmarkObservation> obs,
this->landmarkObservations_)
{
const matrix<double>& JfeatureReferencePosition =
obs->JfeatureReferencePosition_ (t).accessToMotherLib ();
const matrix<double>& JsensorPosition =
obs->JsensorPosition_ (t).accessToMotherLib ();
const vector<double>& weight =
obs->weight_ (t).accessToMotherLib ();
range rx (i, i + obs->featureReferencePosition_ (t).size ());
range ry (0, nbConsideredDofs (obs, t));
matrix_range<matrix<double> > mr (W, rx, ry);
mr = extractConsideredDofs
(obs, prod (JfeatureReferencePosition, JsensorPosition), t);
// Multiply by weight.
for (unsigned idx = 0; idx < weight.size (); ++idx)
matrix_row<matrix_range<matrix<double> > > (mr, idx)
*= weight[idx];
i += obs->featureReferencePosition_ (t).size ();
}
std::cout << "W:" << std::endl
<< W << std::endl;
return W;
}
ml::Vector& computeConfigurationOffset (ml::Vector& res, int t)
{
using namespace boost::numeric::ublas;
vector<double> featureDelta = computeFeatureOffset (t);
matrix<double> W = computeW (t);
matrix<double> Wp = W; //FIXME: pseudoinverse here.
ml::Matrix Wp_;
Wp_.initFromMotherLib (Wp);
Wp_ = Wp_.pseudoInverse (Wp_);
return res.initFromMotherLib
(prod (Wp_.accessToMotherLib (), featureDelta));
}
private:
friend class LandmarkObservation;
friend class command::AddLandmarkObservation;
/// Commands
/// - add_landmark_observation(name)
/// \name Output signals
/// \{
signalOutVector_t configurationOffset_;
/// \}
std::vector<boost::shared_ptr<LandmarkObservation> > landmarkObservations_;
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(Localizer, "Localizer");
LandmarkObservation::LandmarkObservation (Localizer& localizer,
const std::string& signalNamePrefix)
: JsensorPosition_
(dg::nullptr,
MAKE_SIGNAL_STRING
(localizer.getName (), true, "Matrix", signalNamePrefix + "_JsensorPosition")),
featureReferencePosition_
(dg::nullptr,
MAKE_SIGNAL_STRING
(localizer.getName (), true, "Vector", signalNamePrefix + "_featureReferencePosition")),
JfeatureReferencePosition_
(dg::nullptr,
MAKE_SIGNAL_STRING
(localizer.getName (), true, "Matrix", signalNamePrefix + "_JfeatureReferencePosition")),
featureObservedPosition_
(dg::nullptr,
MAKE_SIGNAL_STRING
(localizer.getName (), true, "Vector", signalNamePrefix + "_featureObservedPosition")),
weight_
(dg::nullptr,
MAKE_SIGNAL_STRING
(localizer.getName (), true, "Vector", signalNamePrefix + "_weight")),
correctedDofs_
(dg::nullptr,
MAKE_SIGNAL_STRING
(localizer.getName (), true, "Vector", signalNamePrefix + "_correctedDofs"))
{
localizer.configurationOffset_.addDependency(JsensorPosition_);
localizer.configurationOffset_.addDependency(featureReferencePosition_);
localizer.configurationOffset_.addDependency(JfeatureReferencePosition_);
localizer.configurationOffset_.addDependency(featureObservedPosition_);
localizer.configurationOffset_.addDependency(weight_);
localizer.configurationOffset_.addDependency(correctedDofs_);
localizer.signalRegistration (JsensorPosition_
<< featureReferencePosition_
<< JfeatureReferencePosition_
<< featureObservedPosition_
<< weight_
<< correctedDofs_);
}
Localizer::Localizer (const std::string& name)
: Entity(name),
configurationOffset_
(boost::bind (&Localizer::computeConfigurationOffset, this, _1, _2),
dg::sotNOSIGNAL,
MAKE_SIGNAL_STRING (name, false, "Vector", "configurationOffset")),
landmarkObservations_ ()
{
signalRegistration (configurationOffset_);
std::string docstring = " \n"
" Add a landmark observation to the localizer.\n"
" \n"
" In practice, calling this generates signals prefixed by\n"
" the name of the landmark observation.\n"
" \n"
" Generated signals are:"
" - FIXME"
" \n"
" Input:\n"
" - a string: landmark observation name,\n"
" Return:\n"
" - nothing\n";
addCommand
("add_landmark_observation",
new command::AddLandmarkObservation (*this, docstring));
}
namespace command
{
AddLandmarkObservation::AddLandmarkObservation
(Localizer& entity, const std::string& docstring)
: Command (entity, boost::assign::list_of (Value::STRING), docstring)
{}
Value AddLandmarkObservation::doExecute ()
{
Localizer& localizer = static_cast<Localizer&> (owner ());
const std::vector<Value>& values = getParameterValues();
const std::string& landmarkName = values[0].value();
LandmarkObservation* lmo =
new LandmarkObservation (localizer, landmarkName);
localizer.landmarkObservations_.push_back
(boost::shared_ptr<LandmarkObservation> (lmo));
return Value ();
}
} // end of namespace command.
| [
"thomas.moulard@gmail.com"
] | thomas.moulard@gmail.com |
4dcc0b29c7c7770c6803674c01d3de9b0b5c4850 | b2d41d85fa568d273fc0969d10b97549e27e47af | /src/AM_WiFiNINA.cpp | 5b78de55a899713e52c2785c943e8d692225f5b9 | [] | no_license | ArduinoManager/AM_WiFiNINA | e34749ef09a64ab241e507f8abb65e038c5cd0d0 | 7cfb4f01bee69839929616251f123e93e3fd33c0 | refs/heads/main | 2023-05-05T20:18:11.582476 | 2021-05-25T16:38:32 | 2021-05-25T16:38:32 | 365,158,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,538 | cpp | /*
*
* AMController libraries, example sketches (“The Software”) and the related documentation (“The Documentation”) are supplied to you
* by the Author in consideration of your agreement to the following terms, and your use or installation of The Software and the use of The Documentation
* constitutes acceptance of these terms.
* If you do not agree with these terms, please do not use or install The Software.
* The Author grants you a personal, non-exclusive license, under author's copyrights in this original software, to use The Software.
* Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by the Author, including but not limited to any
* patent rights that may be infringed by your derivative works or by other works in which The Software may be incorporated.
* The Software and the Documentation are provided by the Author on an "AS IS" basis. THE AUTHOR MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE SOFTWARE OR ITS USE AND OPERATION
* ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
* REPRODUCTION AND MODIFICATION OF THE SOFTWARE AND OR OF THE DOCUMENTATION, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
* STRICT LIABILITY OR OTHERWISE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Fabrizio Boco - fabboco@gmail.com
*
* All rights reserved
*
*/
#include <AM_WiFiNINA.h>
#ifdef DEBUG
#define LEAP_YEAR(Y) ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )
static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
#endif
char *dtostrf (double val, signed char width, unsigned char prec, char *sout);
#if defined(ALARMS_SUPPORT)
bool check(uint8_t *pRecord, void *pData) {
Alarm a;
memcpy(&a, pRecord, sizeof(a));
if (strcmp(a.id,(char *)pData)==0)
return true;
return false;
}
#endif
#if defined(ALARMS_SUPPORT)
AMController::AMController(WiFiServer *server,
void (*doWork)(void),
void (*doSync)(void),
void (*processIncomingMessages)(char *variable, char *value),
void (*processOutgoingMessages)(void),
#if defined(ALARMS_SUPPORT)
void (*processAlarms)(char *alarm),
#endif
void (*deviceConnected)(void),
void (*deviceDisconnected)(void)
) : AMController(server,doWork,doSync,processIncomingMessages,processOutgoingMessages,deviceConnected,deviceDisconnected) {
#ifdef ALARMS_SUPPORT
_alarmFile = "ALARMS.TXT";
//_timeServerAddress = IPAddress(64,90,182,55); // New York City, NY NTP Server nist1-ny.ustiming.org
_timeServerAddress = IPAddress(129,6,15,28); // time.nist.gov
_processAlarms = processAlarms;
_startTime = 0;
_sendNtpRequest=false;
_lastAlarmCheck = 0;
inizializeAlarms();
#endif
}
#endif
AMController::AMController(WiFiServer *server,
void (*doWork)(void),
void (*doSync)(void),
void (*processIncomingMessages)(char *variable, char *value),
void (*processOutgoingMessages)(void),
void (*deviceConnected)(void),
void (*deviceDisconnected)(void)
) {
_var = true;
_idx = 0;
_server = server;
_doWork = doWork;
_doSync = doSync;
_processIncomingMessages = processIncomingMessages;
_processOutgoingMessages = processOutgoingMessages;
_deviceConnected = deviceConnected;
_deviceDisconnected = deviceDisconnected;
_initialized = false;
_pClient = NULL;
_variable[0] = '\0';
_value[0] = '\0';
#ifdef ALARMS_SUPPORT
_processAlarms = NULL;
#endif
}
void AMController::loop() {
this->loop(20);
}
void AMController::loop(unsigned long _delay) {
if (!_initialized) {
_initialized = true;
_server->begin();
delay(1500);
}
#ifdef ALARMS_SUPPORT
if( (millis()/1000<20 && _startTime==0) || _sendNtpRequest) {
this->syncTime();
_startTime=100;
}
if ( _udp.parsePacket() ) {
this->readTime();
}
if (_processAlarms != NULL) {
unsigned long now = _startTime + millis()/1000;
if ( (now - _lastAlarmCheck) > ALARM_CHECK_INTERVAL) {
_lastAlarmCheck = now;
this->checkAndFireAlarms();
}
}
#endif
_doWork();
WiFiClient localClient = _server->available();
_pClient = &localClient;
if (localClient) {
#ifdef DEBUG
Serial.println("Client connected");
#endif
// Client connected
if (_deviceConnected != NULL) {
delay(250);
_deviceConnected();
delay(250);
}
while(_pClient->connected()) {
// Read incoming messages if any
this->readVariable();
if (strlen(_value)>0 && strcmp(_variable,"Sync") == 0) {
// Process sync messages for the variable _value
_doSync();
}
else {
#ifdef ALARMS_SUPPORT
// Manages Alarm creation and update requests
char id[8];
unsigned long time;
if (strlen(_value)>0 && strcmp(_variable,"$AlarmId$") == 0) {
strcpy(id,_value);
} else if (strlen(_value)>0 && strcmp(_variable,"$AlarmT$") == 0) {
time=atol(_value);
}
else if (strlen(_value)>0 && strcmp(_variable,"$AlarmR$") == 0) {
if (time == 0) {
#ifdef DEBUG
Serial.print("Deleting Alarm "); Serial.println(id);
#endif
this->removeAlarm(id);
}
else
this->createUpdateAlarm(id,time,atoi(_value));
#endif
}
#ifdef SD_SUPPORT
else if (strlen(_variable)>0 && strcmp(_variable,"SD") == 0) {
#ifdef DEBUG
Serial.println("List of Files");
#endif
File root = SD.open("/");
if (!root) {
#ifdef DEBUG
Serial.println("Failed to open /");
#endif
return;
}
root.rewindDirectory();
File entry = root.openNextFile();
if (!entry) {
#ifdef DEBUG
Serial.println("Failed to get first file");
#endif
return;
}
while(entry) {
if(!entry.isDirectory()) {
this->writeTxtMessage("SD",entry.name());
#ifdef DEBUG
Serial.println(entry.name());
#endif
}
entry.close();
entry = root.openNextFile();
}
root.close();
uint8_t buffer[10];
strcpy((char *)&buffer[0],"SD=$EFL$#");
_pClient->write(buffer,9*sizeof(uint8_t));
#ifdef DEBUG
Serial.println("File list sent");
#endif
}
else if (strlen(_variable)>0 && strcmp(_variable,"$SDDL$")==0) {
#ifdef DEBUG
Serial.print("File: "); Serial.println(_value);
#endif
File dataFile = SD.open(_value,FILE_READ);
if (dataFile) {
unsigned long n=0;
uint8_t buffer[64];
strcpy((char *)&buffer[0],"SD=$C$#");
_pClient->write(buffer,7*sizeof(uint8_t));
delay(3000); // OK
while(dataFile.available()) {
n = dataFile.read(buffer, sizeof(buffer));
_pClient->write(buffer, n*sizeof(uint8_t));
}
strcpy((char *)&buffer[0],"SD=$E$#");
_pClient->write(buffer,7*sizeof(uint8_t));
delay(150);
dataFile.close();
#ifdef DEBUG
Serial.print("Fine Sent");
#endif
}
_pClient->flush();
}
#endif
#ifdef SDLOGGEDATAGRAPH_SUPPORT
if (strlen(_variable)>0 && strcmp(_variable,"$SDLogData$") == 0) {
#ifdef DEBUG
Serial.print("Logged data request for: "); Serial.println(_value);
#endif
sdSendLogData(_value);
}
#endif
if (strlen(_variable)>0 && strlen(_value)>0) {
// Process incoming messages
_processIncomingMessages(_variable,_value);
}
}
#ifdef ALARMS_SUPPORT
// Check and Fire Alarms
if (_processAlarms != NULL) {
unsigned long now = _startTime + millis()/1000;
if ( (now - _lastAlarmCheck) > ALARM_CHECK_INTERVAL) {
_lastAlarmCheck = now;
this->checkAndFireAlarms();
}
}
#endif
#ifdef TWITTER_SUPPORT
if (_checkTwitter != NULL) {
unsigned long now = _startTime + millis()/1000;
if ( (now - _lastTwitterCheck) > TWITTER_CHECK_INTERVAL) {
_lastTwitterCheck = now;
checkTwitter();
}
}
#endif
// Write outgoing messages
_processOutgoingMessages();
#ifdef ALARMS_SUPPORT
// Sync local time with NTP Server
if(_sendNtpRequest) {
this->syncTime();
}
if ( _udp.parsePacket() ) {
this->readTime();
}
#endif
_doWork();
delay(_delay);
}
// Client disconnected
localClient.flush();
localClient.stop();
_pClient = NULL;
if (_deviceDisconnected != NULL)
_deviceDisconnected();
}
}
void AMController::readVariable(void) {
_variable[0]='\0';
_value[0]='\0';
_var = true;
_idx=0;
while (_pClient->available()) {
char c = _pClient->read();
if (isprint (c)) {
if (c == '=') {
_variable[_idx]='\0';
_var = false;
_idx = 0;
}
else {
if (c == '#') {
_value[_idx]='\0';
_var = true;
_idx = 0;
return;
}
else {
if (_var) {
if(_idx==VARIABLELEN)
_variable[_idx] = '\0';
else
_variable[_idx++] = c;
}
else {
if(_idx==VALUELEN)
_value[_idx] = '\0';
else
_value[_idx++] = c;
}
}
}
}
}
}
void AMController::writeMessage(const char *variable, int value){
char buffer[VARIABLELEN+VALUELEN+3];
if (_pClient == NULL)
return;
snprintf(buffer,VARIABLELEN+VALUELEN+3, "%s=%d#", variable, value);
_pClient->write((const uint8_t *)buffer, strlen(buffer)*sizeof(char));
}
void AMController::writeMessage(const char *variable, float value){
char buffer[VARIABLELEN+VALUELEN+3];
if (_pClient == NULL)
return;
snprintf(buffer,VARIABLELEN+VALUELEN+3, "%s=%.3f#", variable, value);
_pClient->write((const uint8_t *)buffer, strlen(buffer)*sizeof(char));
}
void AMController::writeTripleMessage(const char *variable, float vX, float vY, float vZ) {
char buffer[VARIABLELEN+VALUELEN+3];
char vbufferAx[VALUELEN];
char vbufferAy[VALUELEN];
char vbufferAz[VALUELEN];
dtostrf(vX, 0, 2, vbufferAx);
dtostrf(vY, 0, 2, vbufferAy);
dtostrf(vZ, 0, 2, vbufferAz);
snprintf(buffer,VARIABLELEN+VALUELEN+3, "%s=%s:%s:%s#", variable, vbufferAx,vbufferAy,vbufferAz);
_pClient->write((const uint8_t *)buffer, strlen(buffer)*sizeof(char));
}
void AMController::writeTxtMessage(const char *variable, const char *value) {
char buffer[128];
snprintf(buffer,128, "%s=%s#", variable, value);
_pClient->write((const uint8_t *)buffer, strlen(buffer)*sizeof(char));
}
void AMController::log(const char *msg) {
this->writeTxtMessage("$D$",msg);
}
void AMController::log(int msg) {
char buffer[11];
itoa(msg, buffer, 10);
this->writeTxtMessage("$D$",buffer);
}
void AMController::logLn(const char *msg) {
this->writeTxtMessage("$DLN$",msg);
}
void AMController::logLn(int msg) {
char buffer[11];
itoa(msg, buffer, 10);
this->writeTxtMessage("$DLN$",buffer);
}
void AMController::logLn(long msg) {
char buffer[11];
ltoa(msg, buffer, 10);
this->writeTxtMessage("$DLN$",buffer);
}
void AMController::logLn(unsigned long msg) {
char buffer[11];
ltoa(msg, buffer, 10);
this->writeTxtMessage("$DLN$",buffer);
}
void AMController::temporaryDigitalWrite(uint8_t pin, uint8_t value, unsigned long ms) {
#if defined(ARDUINO_SAMD_MKR1000)
PORT->Group[g_APinDescription[pin].ulPort].PINCFG[g_APinDescription[pin].ulPin].reg =(uint8_t)(PORT_PINCFG_INEN) ;
PORT->Group[g_APinDescription[pin].ulPort].DIRSET.reg = (uint32_t)(1<<g_APinDescription[pin].ulPin) ;
boolean previousValue = digitalRead(pin);
switch ( value )
{
case LOW:
PORT->Group[g_APinDescription[pin].ulPort].OUTCLR.reg = (1ul << g_APinDescription[pin].ulPin) ;
break ;
default:
PORT->Group[g_APinDescription[pin].ulPort].OUTSET.reg = (1ul << g_APinDescription[pin].ulPin) ;
break ;
}
delay(ms);
switch ( previousValue )
{
case LOW:
PORT->Group[g_APinDescription[pin].ulPort].OUTCLR.reg = (1ul << g_APinDescription[pin].ulPin) ;
break ;
default:
PORT->Group[g_APinDescription[pin].ulPort].OUTSET.reg = (1ul << g_APinDescription[pin].ulPin) ;
break ;
}
#else
boolean previousValue = digitalRead(pin);
digitalWrite(pin, value);
delay(ms);
digitalWrite(pin, previousValue);
#endif
}
// Time Management
#ifdef ALARMS_SUPPORT
void AMController::setNTPServerAddress(IPAddress address) {
_timeServerAddress = address;
}
void AMController::syncTime() {
// Send Request to NTP Server
_sendNtpRequest = false;
_udp.begin(2390); // Local Port to listen for UDP packets
this->sendNTPpacket(_timeServerAddress, _udp);
#ifdef DEBUG
Serial.print("NNP Request Sent to address ");
Serial.println(_timeServerAddress);
#endif
}
unsigned long AMController::now() {
unsigned long now = _startTime + millis()/1000;
return now;
}
void AMController::readTime() {
// Packet Received from NTP Server
_udp.read(_packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(_packetBuffer[40], _packetBuffer[41]);
unsigned long lowWord = word(_packetBuffer[42], _packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
// now convert NTP time into everyday time:
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years to get Unix time:
_startTime = secsSince1900 - seventyYears;
// subtract current millis to sync with time in Arduino
_startTime -= millis()/1000;
#ifdef DEBUG
Serial.println("NNP Respose");
this->printTime(_startTime);
Serial.println();
#endif
}
// send an NTP request to the time server at the given address
void AMController::sendNTPpacket(IPAddress& address, WiFiUDP udp) {
// set all bytes in the buffer to 0
memset(_packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
//Serial.println("2");
_packetBuffer[0] = 0b11100011; // LI, Version, Mode
_packetBuffer[1] = 0; // Stratum, or type of clock
_packetBuffer[2] = 6; // Polling Interval
_packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
_packetBuffer[12] = 49;
_packetBuffer[13] = 0x4E;
_packetBuffer[14] = 49;
_packetBuffer[15] = 52;
//Serial.println("3");
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
udp.beginPacket(address, 123); //NTP requests are to port 123
//Serial.println("4");
udp.write(_packetBuffer, NTP_PACKET_SIZE);
//Serial.println("5");
udp.endPacket();
}
#ifdef DEBUG
void AMController::breakTime(unsigned long time, int *seconds, int *minutes, int *hours, int *Wday, long *Year, int *Month, int *Day) {
// break the given time_t into time components
// this is a more compact version of the C library localtime function
// note that year is offset from 1970 !!!
unsigned long year;
uint8_t month, monthLength;
unsigned long days;
*seconds = time % 60;
time /= 60; // now it is minutes
*minutes = time % 60;
time /= 60; // now it is hours
*hours = time % 24;
time /= 24; // now it is days
*Wday = ((time + 4) % 7) + 1; // Sunday is day 1
year = 0;
days = 0;
while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
year++;
}
*Year = year+1970; // year is offset from 1970
days -= LEAP_YEAR(year) ? 366 : 365;
time -= days; // now it is days in this year, starting at 0
days=0;
month=0;
monthLength=0;
for (month=0; month<12; month++) {
if (month==1) { // february
if (LEAP_YEAR(year)) {
monthLength=29;
}
else {
monthLength=28;
}
}
else {
monthLength = monthDays[month];
}
if (time >= monthLength) {
time -= monthLength;
}
else {
break;
}
}
*Month = month + 1; // jan is month 1
*Day = time + 1; // day of month
}
void AMController::printTime(unsigned long time) {
int seconds;
int minutes;
int hours;
int Wday;
long Year;
int Month;
int Day;
this->breakTime(time, &seconds, &minutes, &hours, &Wday, &Year, &Month, &Day);
Serial.print(Day);
Serial.print("/");
Serial.print(Month);
Serial.print("/");
Serial.print(Year);
Serial.print(" ");
Serial.print(hours);
Serial.print(":");
Serial.print(minutes);
Serial.print(":");
Serial.print(seconds);
}
#endif
void AMController::inizializeAlarms() {
}
#ifdef ALARMS_SUPPORT
void AMController::createUpdateAlarm(char *id, unsigned long time, bool repeat) {
FileManager fileManager;
Alarm a;
int pos;
pos = fileManager.find(_alarmFile, (uint8_t*)&a, sizeof(a), &check, id);
if (pos > -1) {
a.time = time;
a.repeat = repeat;
fileManager.update(_alarmFile, pos, (uint8_t *)&a, sizeof(a));
#ifdef DEBUG
dumpAlarms();
#endif
return;
}
strcpy(a.id,id);
a.time = time;
a.repeat = repeat;
fileManager.append(_alarmFile, (uint8_t *)&a, sizeof(a));
#ifdef DEBUG
dumpAlarms();
#endif
}
void AMController::removeAlarm(char *id) {
FileManager fileManager;
Alarm a;
int pos;
pos = fileManager.find(_alarmFile, (uint8_t*)&a, sizeof(a), &check, id);
if (pos > -1) {
fileManager.remove(_alarmFile, pos, sizeof(a));
}
#ifdef DEBUG
dumpAlarms();
#endif
}
#ifdef DEBUG
void AMController::dumpAlarms() {
Serial.println("\t----Dump Alarms -----");
FileManager fileManager;
for(int i=0;i<MAX_ALARMS; i++) {
Alarm a;
if (!fileManager.read(_alarmFile, i, (uint8_t *)&a, sizeof(a)))
return;
Serial.print("\tId: "); Serial.print(a.id);
Serial.print(" time: "); printTime(a.time);
Serial.print(" Repeat: "); Serial.println(a.repeat);
}
}
#endif
void AMController::checkAndFireAlarms() {
FileManager fileManager;
unsigned long now = _startTime + millis()/1000;
#ifdef DEBUG
Serial.print("checkAndFireAlarms ");
this->printTime(now);
Serial.println();
this->dumpAlarms();
#endif
for(int i=0; i<MAX_ALARMS; i++) {
Alarm a;
if (!fileManager.read(_alarmFile, i, (uint8_t *)&a, sizeof(a)))
return;
if(a.time <= now) {
#ifdef DEBUG
Serial.print("Firing "); Serial.println(a.id);
#endif
// First character of id is A and has to be removed
_processAlarms(a.id);
if(a.repeat) {
a.time += 86400; // Scheduled again tomorrow
fileManager.update(_alarmFile, i, (uint8_t *)&a, sizeof(a));
#ifdef DEBUG
Serial.print("Alarm rescheduled at ");
this->printTime(a.time);
Serial.println();
#endif
}
else {
// Alarm removed
fileManager.remove(_alarmFile, i, sizeof(a));
#ifdef DEBUG
this->dumpAlarms();
#endif
}
}
}
}
#endif
#endif
#ifdef SDLOGGEDATAGRAPH_SUPPORT
void AMController::sdLogLabels(const char *variable, const char *label1) {
this->sdLogLabels(variable,label1,NULL,NULL,NULL,NULL);
}
void AMController::sdLogLabels(const char *variable, const char *label1, const char *label2) {
this->sdLogLabels(variable,label1,label2,NULL,NULL,NULL);
}
void AMController::sdLogLabels(const char *variable, const char *label1, const char *label2, const char *label3) {
this->sdLogLabels(variable,label1,label2,label3,NULL,NULL);
}
void AMController::sdLogLabels(const char *variable, const char *label1, const char *label2, const char *label3, const char *label4) {
this->sdLogLabels(variable,label1,label2,label3,label4,NULL);
}
void AMController::sdLogLabels(const char *variable, const char *label1, const char *label2, const char *label3, const char *label4, const char *label5) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile)
{
dataFile.print("-");
dataFile.print(";");
dataFile.print(label1);
dataFile.print(";");
if(label2 != NULL)
dataFile.print(label2);
else
dataFile.print("-");
dataFile.print(";");
if(label3 != NULL)
dataFile.print(label3);
else
dataFile.print("-");
dataFile.print(";");
if(label4 != NULL)
dataFile.print(label4);
else
dataFile.print("-");
dataFile.print(";");
if(label5 != NULL)
dataFile.println(label5);
else
dataFile.println("-");
dataFile.flush();
dataFile.close();
} else {
#ifdef DEBUG
Serial.print("Error opening"); Serial.println(variable);
#endif
}
}
void AMController::sdLog(const char *variable, unsigned long time, float v1) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile)
{
dataFile.print(time);
dataFile.print(";");
dataFile.print(v1);
dataFile.print(";-;-;-;-");
dataFile.println();
dataFile.flush();
dataFile.close();
}
else {
#ifdef DEBUG
Serial.print("Error opening"); Serial.println(variable);
#endif
}
}
void AMController::sdLog(const char *variable, unsigned long time, float v1, float v2) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile && time>0)
{
dataFile.print(time);
dataFile.print(";");
dataFile.print(v1);
dataFile.print(";");
dataFile.print(v2);
dataFile.print(";-;-;-");
dataFile.println();
dataFile.flush();
dataFile.close();
}
else {
#ifdef DEBUG
Serial.print("Error opening"); Serial.println(variable);
#endif
}
}
void AMController::sdLog(const char *variable, unsigned long time, float v1, float v2, float v3) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile && time>0)
{
dataFile.print(time);
dataFile.print(";");
dataFile.print(v1);
dataFile.print(";");
dataFile.print(v2);
dataFile.print(";");
dataFile.print(v3);
dataFile.print(";-;-");
dataFile.println();
dataFile.flush();
dataFile.close();
}
else {
#ifdef DEBUG
Serial.print("Error opening"); Serial.println(variable);
#endif
}
}
void AMController::sdLog(const char *variable, unsigned long time, float v1, float v2, float v3, float v4) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile && time>0)
{
dataFile.print(time);
dataFile.print(";");
dataFile.print(v1);
dataFile.print(";");
dataFile.print(v2);
dataFile.print(";");
dataFile.print(v3);
dataFile.print(";");
dataFile.print(v4);
dataFile.println(";-");
dataFile.println();
dataFile.flush();
dataFile.close();
}
else {
#ifdef DEBUG
Serial.print("Error opening"); Serial.println(variable);
#endif
}
}
void AMController::sdLog(const char *variable, unsigned long time, float v1, float v2, float v3, float v4, float v5) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile && time>0)
{
dataFile.print(time);
dataFile.print(";");
dataFile.print(v1);
dataFile.print(";");
dataFile.print(v2);
dataFile.print(";");
dataFile.print(v3);
dataFile.print(";");
dataFile.print(v4);
dataFile.print(";");
dataFile.println(v5);
dataFile.println();
dataFile.flush();
dataFile.close();
}
else {
#ifdef DEBUG
Serial.print("Error opening"); Serial.println(variable);
#endif
}
}
void AMController::sdSendLogData(const char *variable) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile) {
char c;
char buffer[128];
int i = 0;
dataFile.seek(0);
while( dataFile.available() ) {
c = dataFile.read();
if (c == '\n') {
buffer[i++] = '\0';
#ifdef DEBUG
Serial.println(buffer);
#endif
this->writeTxtMessage(variable,buffer);
i=0;
}
else
buffer[i++] = c;
}
#ifdef DEBUG
Serial.println("All data sent");
#endif
dataFile.close();
}
else {
#ifdef DEBUG
Serial.print("Error opening "); Serial.println(variable);
#endif
}
this->writeTxtMessage(variable,"");
}
// Size in bytes
uint16_t AMController::sdFileSize(const char *variable) {
File dataFile = SD.open(variable, FILE_WRITE);
if (dataFile) {
return dataFile.size();
}
return -1;
}
void AMController::sdPurgeLogData(const char *variable) {
noInterrupts();
SD.remove(variable);
interrupts();
}
#endif
| [
"fabrizio.boco@gmail.com"
] | fabrizio.boco@gmail.com |
2ac44fa114c9934cf8e12427ab40390ce1a3c1d1 | 8149612d43061ef428685cd4453044fb2bb476e3 | /LCARS_Slider/lcars_slider.cpp | 5df41e643adaf59421e4e7b5108f9d4218bf2eaf | [] | no_license | sequency/qt-lcars_widgets | fe2cda8f1e82e6b1a1972fa2ce232aab948e5641 | cd85956749675b027de99495ed795a0d6d3734e3 | refs/heads/master | 2021-05-09T09:40:16.376028 | 2018-01-29T23:03:16 | 2018-01-29T23:03:16 | 119,453,004 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 55,593 | cpp | #include "lcars_slider.h"
#include <QSlider>
#include <QMouseEvent>
#include <QPainter>
#include <QEvent>
#include <QDebug>
LCARS_Slider::LCARS_Slider(QWidget *parent) :
QSlider(parent)
{
//pieHeight=this->property("customRoundingValue").toInt;
temp = QPoint(0,0);
}
void LCARS_Slider::showEvent(QShowEvent *event) {
//LCARS_Slider::showEvent(event);
//QTimer::singleShot(120, this, SLOT(window_shown()));
switch (this->orientation()) {
case Qt::Horizontal:
if (temp.x()==0) {
resultValue=this->value();
//qDebug() << "ok";
}
break;
case Qt::Vertical:
if (this->invertedControls()==false) {
if (temp.y()==0) {
resultValue=this->value();
//qDebug() << "ok2";
}
} else if (this->invertedControls()==true) {
if (temp.y()==0) {
this->setValue(this->maximum()-resultValue);
}
}
break;
default:
break;
}
return;
}
void LCARS_Slider::paintEvent(QPaintEvent*) {
//resultValue=this->value();
//p.setX(0);
//qDebug() << p.x() << p.y();
//qDebug() << temp;
qDebug() << this->value();
switch (this->orientation()) {
case Qt::Horizontal:
if (temp.x()==0) {
resultValue=this->value();
//qDebug() << "ok";
}
break;
case Qt::Vertical:
if (this->invertedControls()==false) {
if (temp.y()==0) {
resultValue=this->value();
//qDebug() << "ok2";
}
} else if (this->invertedControls()==true) {
if (temp.y()==0) {
this->setValue(this->maximum()-resultValue);
qDebug() << this->value();
qDebug() << "ok3";
this->update();
}
}
break;
default:
break;
}
QPainter painter(this);
sliderMode=this->property("sliderMode").toInt(); //0;
widthDash = this->property("widthDash").toInt(); //5;
distanceDash = this->property("distanceDash").toInt() + widthDash; //20+widthDash;
if (handleBackground=="") {
handleBackground = QColor(this->property("handleBackground").toString()); //QColor("#cc6666");
}
/*handleBackground = QColor(this->property("handleBackground").toString()); //QColor("#cc6666");
handleBackgroundPressed = QColor(this->property("handleBackgroundPressed").toString()); //QColor("#ffffff");*/
handleBorderColor = QColor(this->property("handleBorderColor").toString()); //;
barBackgroundTop = QColor(this->property("barBackgroundTop").toString()); //;
barBackgroundBottom = QColor(this->property("barBackgroundBottom").toString()); //
bgGradient_Start=QColor(this->property("bgGradient_Start").toString()); //;
bgGradient_End=QColor(this->property("bgGradient_End").toString()); //;
frontGradient_Start=QColor(this->property("frontGradient_Start").toString()); //;
frontGradient_End=QColor(this->property("frontGradient_End").toString()); //;
dividerColor=QColor(this->property("dividerColor").toString()); //;
handleSize=QSize(this->property("handleSize").toSize()); //;
handleBorderSize=QSize(this->property("handleBorderSize").toSize()); //;
barTopLine=QSize(this->property("barTopLineSize").toSize()); //;
barBottomLine=QSize(this->property("barBottomLineSize").toSize()); //;
customRounding=this->property("customRounding").toBool();
roundBorder=this->property("roundBorder").toBool();
roundHandle_Bar_width=this->property("roundHandle_Bar_width").toInt();
border_roundedHandleWidth=this->property("border_roundedHandleWidth").toInt();
size_roundedHandleTop = QSize(this->property("size_roundedHandleTop").toSize());
size_roundedHandleBottom = QSize(this->property("size_roundedHandleBottom").toSize());;
size_roundedHandle = QSize(this->property("size_roundedHandle").toSize());;
bar_roundedHandleColor=QColor(this->property("bar_roundedHandleColor").toString());
onlyOne=this->property("onlyOneRounding").toBool(); //false
topBottom=this->property("TopOrBottomRounding").toInt(); // 0
switch (sliderMode) {
case 0:
{
paintBar(&painter);
paintHandle(&painter);
}
break;
case 1:
{
switch (this->orientation()) {
case Qt::Horizontal:
{
QLinearGradient gradient1(rect().topLeft(), rect().bottomRight());
gradient1.setColorAt(0, bgGradient_Start); // QColor("#363496")
gradient1.setColorAt(1, bgGradient_End); //QColor("#131128")
QBrush rush1 = QBrush(gradient1);
painter.setBackgroundMode(Qt::OpaqueMode);
painter.setBackground(rush1);
painter.fillRect(0,0,this->width(),this->height(),rush1);
paintBar(&painter);
paintHandle(&painter);
int distanceBorder = distanceDash - widthDash;
for (int i=distanceBorder;i<=this->width()/*-distanceBorder*/;i++) {
painter.fillRect(i,0,widthDash,this->height(),dividerColor);
i=i+distanceDash;
}
}
break;
case Qt::Vertical:
{
if (roundBorder == true) {
if (onlyOne == false) {
painter.setBackgroundMode(Qt::OpaqueMode);
if (customRounding == false) {
pieHeight=(this->width()/2)*2;
} else if (customRounding == true) {
pieHeight = this->property("customRoundingValue").toInt()*2;
}
else
{
pieHeight=(this->width()/2)*2;
}
QLinearGradient gradientBackground(0,this->height()-pieHeight,0,pieHeight/2);
gradientBackground.setColorAt(0,bgGradient_Start);
gradientBackground.setColorAt(1,bgGradient_End);
QBrush rush2 = QBrush(gradientBackground);
painter.setRenderHint(QPainter::Antialiasing,true);
painter.setBrush(QBrush(bgGradient_End));
painter.setPen(QPen(bgGradient_End,-1));
painter.drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter.fillRect(0,pieHeight/2,this->width(),this->height()-pieHeight,rush2);
painter.setBrush(QBrush(bgGradient_Start));
painter.setPen(QPen(bgGradient_Start,-1));
painter.drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
paintBar(&painter);
paintHandle(&painter);
int distanceBorder = distanceDash - widthDash;
for (int i=this->height()-pieHeight;i>=distanceBorder+pieHeight/*-distanceBorder*/;i--) {
painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
i=i-distanceDash;
painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
}
} else if (onlyOne==true) {
switch (topBottom) {
case 0:
{
painter.setBackgroundMode(Qt::OpaqueMode);
if (customRounding == false) {
pieHeight=(this->width()/2)*2;
} else if (customRounding == true) {
pieHeight = this->property("customRoundingValue").toInt()*2;
}
else
{
pieHeight=(this->width()/2)*2;
}
//pieHeight=pieHeight/2;
QLinearGradient gradientBackground(0,this->height()-pieHeight,0,pieHeight/2);
gradientBackground.setColorAt(0,bgGradient_Start);
gradientBackground.setColorAt(1,bgGradient_End);
QBrush rush2 = QBrush(gradientBackground);
painter.setRenderHint(QPainter::Antialiasing,true);
painter.setBrush(QBrush(bgGradient_End));
painter.setPen(QPen(bgGradient_End,-1));
painter.drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter.fillRect(0,pieHeight/2,this->width(),this->height(),rush2);
paintBar(&painter);
paintHandle(&painter);
int distanceBorder = distanceDash - widthDash;
for (int i=this->height();i>=distanceBorder+pieHeight-distanceBorder;i--) {
painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
i=i-distanceDash;
//painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
}
}
break;
case 1:
{
if (this->invertedAppearance()==false) {
painter.setBackgroundMode(Qt::OpaqueMode);
if (customRounding == false) {
pieHeight=(this->width()/2)*2;
} else if (customRounding == true) {
pieHeight = this->property("customRoundingValue").toInt()*2;
}
else
{
pieHeight=(this->width()/2)*2;
}
//pieHeight=pieHeight/2;
QLinearGradient gradientBackground(0,this->height()-pieHeight,0,pieHeight/2);
gradientBackground.setColorAt(0,bgGradient_Start);
gradientBackground.setColorAt(1,bgGradient_End);
QBrush rush2 = QBrush(gradientBackground);
painter.setRenderHint(QPainter::Antialiasing,true);
painter.setBrush(rush2);
painter.setPen(QPen(rush2,-1));
painter.drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter.fillRect(0,0,this->width(),this->height()-pieHeight/2,rush2);
paintBar(&painter);
paintHandle(&painter);
int distanceBorder = distanceDash - widthDash;
for (int i=this->height()-pieHeight;i>=0;i--) {
painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
i=i-distanceDash;
//painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
}
} else if (this->invertedAppearance()==true) {
painter.setBackgroundMode(Qt::OpaqueMode);
if (customRounding == false) {
pieHeight=(this->width()/2)*2;
} else if (customRounding == true) {
pieHeight = this->property("customRoundingValue").toInt()*2;
}
else
{
pieHeight=(this->width()/2)*2;
}
//pieHeight=pieHeight/2;
QLinearGradient gradientBackground(0,this->height()-pieHeight,0,pieHeight/2);
gradientBackground.setColorAt(1,bgGradient_Start);
gradientBackground.setColorAt(0,bgGradient_End);
QBrush rush2 = QBrush(gradientBackground);
painter.setRenderHint(QPainter::Antialiasing,true);
painter.setBrush(rush2);
painter.setPen(QPen(rush2,-1));
painter.drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter.fillRect(0,0,this->width(),this->height()-pieHeight/2,rush2);
paintBar(&painter);
paintHandle(&painter);
int distanceBorder = distanceDash - widthDash;
for (int i=this->height()-pieHeight;i>=0;i--) {
painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
i=i-distanceDash;
}
}
}
break;
default:
break;
}
}
} else {
QLinearGradient gradient1(rect().bottomLeft(), rect().topRight());
gradient1.setColorAt(0, bgGradient_Start);//QColor("#363496")
gradient1.setColorAt(1, bgGradient_End); //QColor("#131128")
QBrush rush1 = QBrush(gradient1);
painter.setBackgroundMode(Qt::OpaqueMode);
painter.setBackground(rush1);
painter.setRenderHint(QPainter::Antialiasing,true);
painter.fillRect(0,0,this->width(),this->height(),rush1);
paintBar(&painter);
paintHandle(&painter);
int distanceBorder = distanceDash - widthDash;
for (int i=this->height();i>=distanceBorder/*-distanceBorder*/;i--) {
painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
i=i-distanceDash;
painter.fillRect(0,i,this->width(),widthDash,dividerColor); //#000000
}
}
}
break;
default:
break;
}
}
break;
case 2:
{
paintBar(&painter);
paintHandle(&painter);
}
break;
default:
break;
}
}
void LCARS_Slider::mouseMoveEvent(QMouseEvent *e)
{
switch (this->orientation()) {
case Qt::Horizontal:
{
if(e->buttons() == Qt::LeftButton)
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
resultValue = (int)((((double)p.x()/(double)this->width())*100)*(double)maxVal/100);
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
this->setValue(resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
temp.setX(p.x());
}
}
}
break;
case Qt::Vertical: {
if(e->buttons() == Qt::LeftButton) {
if (this->invertedControls()==false) {
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
//if (p.y()>=pieHeight+widthDash && p.y()<=this->height()-pieHeight+widthDash) {
resultValue = (int)((((double)(this->height()-p.y())/(double)this->height())*100)*(double)maxVal/100);
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
this->setValue(resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
temp.setY(p.y());
}
}
} else if(this->invertedControls()==true) {
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
//if (p.y()>=pieHeight+widthDash && p.y()<=this->height()-pieHeight+widthDash) {
resultValue = (int)((((double)(this->height()-p.y())/(double)this->height())*100)*(double)maxVal/100);
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
//qDebug() << "thisvalue" << this->maximum()-resultValue;
this->setValue(this->maximum()-resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
temp.setY(p.y());
}
}
}
}
}
default:
break;
}
this->repaint();
}
void LCARS_Slider::mousePressEvent ( QMouseEvent * e ) {
/*if(event->buttons() == Qt::LeftButton) {
qDebug() << "Only right button";
}*/
switch (this->orientation()) {
case Qt::Horizontal:
{
if(e->buttons() == Qt::LeftButton)
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
resultValue = (int)((((double)p.x()/(double)this->width())*100)*(double)maxVal/100);
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
this->setValue(resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
temp.setX(p.x());
}
}
}
break;
case Qt::Vertical: {
if(e->buttons() == Qt::LeftButton) {
if (this->invertedControls()==false) {
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
//if (p.y()>=pieHeight+widthDash && p.y()<=this->height()-pieHeight+widthDash) {
resultValue = (int)((((double)(this->height()-p.y())/(double)this->height())*100)*(double)maxVal/100);
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
this->setValue(resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
temp.setY(p.y());
}
}
} else if(this->invertedControls()==true) {
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
//if (p.y()>=pieHeight+widthDash && p.y()<=this->height()-pieHeight+widthDash) {
resultValue = (int)((((double)(this->height()-p.y())/(double)this->height())*100)*(double)maxVal/100);
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
//qDebug() << "thisvalue" << this->maximum()-resultValue;
this->setValue(this->maximum()-resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
temp.setY(p.y());
}
}
}
}
}
default:
break;
}
handleBackground = QColor(this->property("handleBackgroundPressed").toString());
this->repaint();
}
void LCARS_Slider::mouseReleaseEvent ( QMouseEvent * e ) {
switch (this->orientation()) {
case Qt::Horizontal:
{
if(e->buttons() == Qt::LeftButton)
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
resultValue = (int)((((double)p.x()/(double)this->width())*100)*(double)maxVal/100);
temp.setX(p.x());
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
this->setValue(resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
}
}
}
break;
case Qt::Vertical: {
if(e->buttons() == Qt::LeftButton) {
if (this->invertedControls()==false) {
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
//if (p.y()>=pieHeight+widthDash && p.y()<=this->height()-pieHeight+widthDash) {
resultValue = (int)((((double)(this->height()-p.y())/(double)this->height())*100)*(double)maxVal/100);
temp.setY(p.y());
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
this->setValue(resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
}
}
} else if(this->invertedControls()==true) {
p = this->mapFromGlobal(QCursor::pos());
int maxVal = this->maximum();
//! ((LOWER NUMBER)/(BIGGER NUMBER)*100)*(MAXIMUM/100)
//if (p.y()>=pieHeight+widthDash && p.y()<=this->height()-pieHeight+widthDash) {
resultValue = (int)((((double)(this->height()-p.y())/(double)this->height())*100)*(double)maxVal/100);
temp.setY(p.y());
if (this->hasTracking() == true) {
if (resultValue >= this->minimum() && resultValue <=this->maximum()) {
//qDebug() << "thisvalue" << this->maximum()-resultValue;
this->setValue(this->maximum()-resultValue);
emit valueChanged(resultValue);
emit sliderMoved(resultValue);
}
}
}
}
}
default:
break;
}
handleBackground = QColor(this->property("handleBackground").toString());
emit sliderReleased();
this->repaint();
/*p.setX(0);
p.setY(0);*/
temp.setX(0);
temp.setY(0);
}
void LCARS_Slider::paintHandle(QPainter *painter) {
switch (sliderMode) {
case 0:
{
int handleWidth = handleSize.width();//20;
int handleBorder = handleBorderSize.width(); //5;
//int handleX=this->value()+handleBorder;
int handleY=0;
int handleX = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->width()/100);
if (handleX+handleWidth>=this->width()) {
handleX=this->width()-(handleWidth);
} else if (p.x()<0) {
/*qDebug() << p.x() << this->width();
qDebug() << "lol" << handleX;
*/
handleX=0;
}
/*if (p.x()-(handleWidth)+handleBorder>=0) {
handleX=p.x()-(handleWidth)/2+handleBorder/2;
}*/
/*if (p.x()+(handleWidth/2+handleBorder)>=this->width()) {
handleX=this->width()-(handleWidth+handleBorder);
}*/
painter->fillRect(handleX,handleY,handleWidth,this->height(),handleBackground);
painter->fillRect(handleX-handleBorder,handleY,handleBorder,this->height(),handleBorderColor);
painter->fillRect(handleX+handleWidth,handleY,handleBorder,this->height(),handleBorderColor);
}
break;
case 1:
{
switch (this->orientation()) {
case Qt::Horizontal:
{
int handleY=0;
int handleX = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->width()/100);
QLinearGradient gradient1(rect().topLeft(), rect().bottomRight());
gradient1.setColorAt(0, frontGradient_Start); //QColor("#e66e1e")
gradient1.setColorAt(1, frontGradient_End); //QColor("#ba001e")
QBrush rush1 = QBrush(gradient1);
int distanceBorder = distanceDash - widthDash;
if (p.x()<handleX) {
for (int i=distanceBorder;i<=handleX;i++) {
painter->fillRect(0,handleY,i,this->height(),rush1);
i=i+distanceDash;
painter->fillRect(0,handleY,i,this->height(),rush1);
}
} else if(p.x()==handleX) {
for (int i=distanceBorder;i<=p.x();i++) {
painter->fillRect(0,handleY,i,this->height(),rush1);
i=i+distanceDash;
painter->fillRect(0,handleY,i,this->height(),rush1);
}
} else if(p.x() > handleX) {
for (int i=distanceBorder;i<=p.x();i++) {
painter->fillRect(0,handleY,i,this->height(),rush1);
i=i+distanceDash;
painter->fillRect(0,handleY,i,this->height(),rush1);
}
} else if (p.x()-widthDash<handleX) {
for (int i=distanceBorder;i<=p.x();i++) {
painter->fillRect(0,handleY,i,this->height(),rush1);
i=i+distanceDash;
}
}
}
break;
case Qt::Vertical:
{
//! [ ---- ROUND BORDER TRUE ---- ]
if (roundBorder == false) {
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
QLinearGradient gradient1(rect().bottomLeft(), rect().topRight());
gradient1.setColorAt(0, frontGradient_Start); //QColor("#e66e1e")
gradient1.setColorAt(1, frontGradient_End); //QColor("#ba001e")
QBrush rush1 = QBrush(gradient1);
int distanceBorder = distanceDash - widthDash;
if (p.y()<handleY) {
for (int i=distanceBorder;i<=handleY;i++) {
painter->fillRect(0,this->height(),this->width(),i*-1,rush1);
i=i+distanceDash;
painter->fillRect(0,this->height(),this->width(),i*-1,rush1);
}
}
else if (p.y()<=widthDash+distanceDash) {
for (int i=distanceBorder;i<=p.y();i++) {
painter->fillRect(0,i,this->width(),handleY*-1,rush1);
i=i+distanceDash;
}
}
else if(p.y()==handleY) {
for (int i=distanceBorder;i<=p.y();i++) {
painter->fillRect(0,this->height(),this->width(),i*-1,rush1);
i=i+distanceDash;
painter->fillRect(0,this->height(),this->width(),i*-1,rush1);
}
} else if(p.y() > handleY) {
for (int i=distanceBorder;i<=handleY;i++) {
painter->fillRect(0,this->height(),this->width(),i*-1,rush1);
i=i+distanceDash;
painter->fillRect(0,this->height(),this->width(),i*-1,rush1);
}
} else if (p.y()-widthDash<this->height()) {
for (int i=distanceBorder;i<=p.y();i++) {
painter->fillRect(0,this->height(),this->width(),i*-1,rush1);
i=i+distanceDash;
}
}
}
//! [ ---- ROUND BORDER TRUE ---- ]
else if(roundBorder == true) {
if (onlyOne == false) {
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
QLinearGradient gradient1(rect().bottomLeft(), rect().topRight());
gradient1.setColorAt(0, frontGradient_Start); //QColor("#e66e1e")
gradient1.setColorAt(1, frontGradient_End); //QColor("#ba001e")
QBrush rush1 = QBrush(gradient1);
int distanceBorder = distanceDash - widthDash;
if (p.y()>pieHeight && p.y() < this->height()-pieHeight) {
for (int i=pieHeight;i<this->height()-pieHeight;i++) {
i=i+distanceBorder;
}
}
if (p.y()<=pieHeight && p.y()!=0) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight*2,rush1);
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else if(p.y()==0 && handleY==this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight*2,rush1);
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else if (p.y()>=this->height()-pieHeight && p.y()<this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else if ((p.y()>pieHeight && p.y() < this->height()-pieHeight) || p.y()<handleY-pieHeight /*p.y()==0*/) {
for (int i=0;i<handleY-pieHeight;i++) {
painter->fillRect(0,this->height()-pieHeight,this->width(),-i-distanceDash,rush1);
i=i+distanceDash;
}
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
}
//! ONLY ONE
else if (onlyOne==true) {
switch (topBottom) {
case 0:
{
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
QLinearGradient gradient1(rect().bottomLeft(), rect().topRight());
gradient1.setColorAt(0, frontGradient_Start); //QColor("#e66e1e")
gradient1.setColorAt(1, frontGradient_End); //QColor("#ba001e")
QBrush rush1 = QBrush(gradient1);
int distanceBorder = distanceDash - widthDash;
if (p.y()>pieHeight && p.y() < this->height()-pieHeight) {
for (int i=pieHeight;i<this->height()-pieHeight;i++) {
i=i+distanceBorder;
}
}
if(handleY+pieHeight>this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight,rush1);
}
else if (p.y()<=pieHeight && p.y()!=0) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight,rush1);
}
else if ((p.y()>pieHeight && p.y() < this->height()-pieHeight/2+distanceBorder) || p.y()<handleY-pieHeight ) {
for (int i=0;i<handleY-pieHeight/2+distanceBorder;i++) {
painter->fillRect(0,this->height(),this->width(),-i-distanceDash,rush1);
i=i+distanceDash;
}
}
qDebug() << "py" << this->height()-p.y() << "handle y" << handleY << "pieheight" << pieHeight << "this" << this->height();
} //! ERSTE ENDE
break;
case 1:
{
if (this->invertedAppearance()==false) {
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
QLinearGradient gradient1(rect().bottomLeft(), rect().topRight());
gradient1.setColorAt(0, frontGradient_Start); //QColor("#e66e1e")
gradient1.setColorAt(1, frontGradient_End); //QColor("#ba001e")
QBrush rush1 = QBrush(gradient1);
int distanceBorder = distanceDash - widthDash;
if (p.y()>pieHeight && p.y() < this->height()-pieHeight) {
for (int i=pieHeight;i<this->height()-pieHeight;i++) {
i=i+distanceBorder;
}
}
/*if (p.y()<=pieHeight && p.y()!=0) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight*2,rush1);
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else*/ /*if(p.y()==0 && handleY==this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight*2,rush1);
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else*/ if (p.y()>=this->height()-pieHeight && p.y()<this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else if ((p.y()>pieHeight && p.y() < this->height()-pieHeight) || p.y()<handleY-pieHeight /*p.y()==0*/) {
for (int i=0;i<handleY-pieHeight;i++) {
painter->fillRect(0,this->height()-pieHeight,this->width(),-i-distanceDash,rush1);
i=i+distanceDash;
}
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
}else if(this->invertedAppearance()==true) {
if (this->invertedControls()==false) {
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
QLinearGradient gradient1(rect().bottomLeft(), rect().topRight());
gradient1.setColorAt(1, frontGradient_Start); //QColor("#e66e1e")
gradient1.setColorAt(0, frontGradient_End); //QColor("#ba001e")
QBrush rush1 = QBrush(gradient1);
int distanceBorder = distanceDash - widthDash;
if (p.y()>pieHeight && p.y() < this->height()-pieHeight) {
for (int i=pieHeight;i<this->height()-pieHeight;i++) {
i=i+distanceBorder;
}
}
if (p.y()>=this->height()-pieHeight && p.y()<this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else if ((p.y()>pieHeight && p.y() < this->height()-pieHeight) || p.y()<handleY-pieHeight /*p.y()==0*/) {
for (int i=0;i<handleY-pieHeight;i++) {
painter->fillRect(0,this->height()-pieHeight,this->width(),-i-distanceDash,rush1);
i=i+distanceDash;
}
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
}else if (this->invertedControls() == true) {
qDebug() << "changed";
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
QLinearGradient gradient1(rect().bottomLeft(), rect().topRight());
gradient1.setColorAt(1, frontGradient_Start); //QColor("#e66e1e")
gradient1.setColorAt(0, frontGradient_End); //QColor("#ba001e")
QBrush rush1 = QBrush(gradient1);
int distanceBorder = distanceDash - widthDash;
/* if (p.y()>pieHeight && p.y() < this->height()-pieHeight) {
for (int i=pieHeight;i<this->height()-pieHeight;i++) {
i=i+distanceBorder;
}
}*/
/*if (p.y()<=pieHeight && p.y()!=0) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight*2,rush1);
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else*/ /*if(p.y()==0 && handleY==this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,0,this->width(),pieHeight,360*16,360*8);
painter->fillRect(0,pieHeight/2,this->width(),pieHeight/2,rush1);
painter->fillRect(0,pieHeight,this->width(),this->height()-pieHeight*2,rush1);
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,this->height()-pieHeight,this->width(),pieHeight/2,rush1);
}
else*/
/* if (p.y()>0 && p.y() < this->height()-pieHeight) {
for (int i=pieHeight;i<this->height()-pieHeight;i++) {
painter->fillRect(0,0,this->width(),i,rush1);
i=i+distanceBorder;
qDebug() << "irgendwo hier" ;
}
}*/
if ((p.y()>=this->height()-pieHeight && p.y()<=this->height() )|| p.y()>=this->height()) {
painter->setBrush(rush1);
painter->setPen(QPen(rush1,-1));
painter->drawPie(0,this->height()-pieHeight,this->width(),pieHeight,360*8,360*8);
painter->fillRect(0,0,this->width(),this->height()-pieHeight/2,rush1);
}
//else if ((p.y()>pieHeight && p.y() < this->height()-pieHeight) || p.y()<handleY-pieHeight /*p.y()==0*/) {
else if (p.y()<this->height()-pieHeight ) {
for (int i=this->height()-handleY;i>0;i++) {
//qDebug() << this->height()-handleY;
painter->fillRect(0,0,this->width(),i,rush1);
i=i-distanceDash;
}
}
}
} //! INVERTED APPEAREANCE
}
break;
default:
break;
} //! SWITCH ENDE
}
}
}
break;
default:
break;
}
}
break;
case 2:
{
switch (orientation()) {
case Qt::Horizontal:
{
}
break;
case Qt::Vertical:
{
switch (this->layoutDirection()) {
case Qt::LeftToRight:
{
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
/*int border_roundedHandleWidth=5;
QSize size_roundedHandleTop(30,30);
QSize size_roundedHandleBottom(30,30);
QSize size_roundedHandle(15,35);*/
QPoint point_roundedHandle(this->width(),handleY);
if (p.y()<=0 || p.y()<=size_roundedHandle.height()/2) {
point_roundedHandle.setY(0);
} else if (p.y()>=this->height()|| p.y()>=this->height()-size_roundedHandle.height()/2) {
point_roundedHandle.setY(this->height()-size_roundedHandle.height());
}
else {
//point_roundedHandle=QPoint(this->width(),p.y()-size_roundedHandle.height()/2);
point_roundedHandle.setY(this->height()-handleY-size_roundedHandle.height()/2);
}
QRect rect_roundedHandle(point_roundedHandle,size_roundedHandle);
QPoint point_roundedHandlePieTop(rect_roundedHandle.x()-rect_roundedHandle.width()-size_roundedHandleTop.width()/2,
rect_roundedHandle.y());
QPoint point_roundedHandlePieBottom(rect_roundedHandle.x()-rect_roundedHandle.width()-size_roundedHandleTop.width()/2,
rect_roundedHandle.y()+rect_roundedHandle.height()-size_roundedHandleBottom.height());
QRect rect_roundedHandleTop(point_roundedHandlePieTop,
size_roundedHandleTop);
QRect rect_roundedHandleBottom(point_roundedHandlePieBottom,
size_roundedHandleBottom);
QRect rect_roundedHandleFillerRect(rect_roundedHandle.x()-rect_roundedHandle.width(),
point_roundedHandlePieTop.y()+size_roundedHandleTop.height()/2,
-1*(size_roundedHandleTop.width()/2),
rect_roundedHandle.height()-size_roundedHandleBottom.height()/2-size_roundedHandleTop.height()/2);
painter->setRenderHint(QPainter::Antialiasing,true);
painter->setBrush(handleBorderColor);
painter->setPen(QPen(handleBorderColor,border_roundedHandleWidth*2));
painter->drawRect(rect_roundedHandle.x(),rect_roundedHandle.y(),-1*(rect_roundedHandle).width(),rect_roundedHandle.height());
painter->drawPie(rect_roundedHandleTop,360*4,360*4);
painter->drawPie(rect_roundedHandleBottom,360*8,360*4);
painter->drawRect(rect_roundedHandleFillerRect);
painter->setBrush(handleBackground);
painter->setPen(QPen(handleBackground,-1));
painter->fillRect(rect_roundedHandle.x(),rect_roundedHandle.y(),-1*(rect_roundedHandle).width(),rect_roundedHandle.height(),handleBackground);
painter->drawPie(rect_roundedHandleTop,360*4,360*4);
painter->drawPie(rect_roundedHandleBottom,360*8,360*4);
painter->fillRect(rect_roundedHandleFillerRect,handleBackground);
}
break;
case Qt::RightToLeft:
{
int handleY = ((int)((double)resultValue/(double)this->maximum()*100)*(double)this->height()/100);
/*int border_roundedHandleWidth=5;
QSize size_roundedHandleTop(30,30);
QSize size_roundedHandleBottom(30,30);
QSize size_roundedHandle(15,35);*/
QPoint point_roundedHandle(0,handleY);
/*if (p.y()<=0 || p.y()<=size_roundedHandle.height()/2) {
point_roundedHandle.y()=0;
} else if (p.y()>=this->height()|| p.y()>=this->height()-size_roundedHandle.height()/2) {
point_roundedHandle= QPoint(0,this->height()-size_roundedHandle.height());
}
else {
point_roundedHandle=QPoint(0,p.y()-size_roundedHandle.height()/2);
}*/
if (p.y()<=0 || p.y()<=size_roundedHandle.height()/2) {
point_roundedHandle.setY(0);
} else if (p.y()>=this->height()|| p.y()>=this->height()-size_roundedHandle.height()/2) {
point_roundedHandle.setY(this->height()-size_roundedHandle.height());
}
else {
//point_roundedHandle=QPoint(this->width(),p.y()-size_roundedHandle.height()/2);
point_roundedHandle.setY(this->height()-handleY-size_roundedHandle.height()/2);
}
QRect rect_roundedHandle(point_roundedHandle,size_roundedHandle);
QPoint point_roundedHandlePieTop(rect_roundedHandle.x()+rect_roundedHandle.width()-size_roundedHandleTop.width()/2,
rect_roundedHandle.y());
QPoint point_roundedHandlePieBottom(rect_roundedHandle.x()+rect_roundedHandle.width()-size_roundedHandleTop.width()/2,
rect_roundedHandle.y()+rect_roundedHandle.height()-size_roundedHandleBottom.height());
QRect rect_roundedHandleTop(point_roundedHandlePieTop,
size_roundedHandleTop);
QRect rect_roundedHandleBottom(point_roundedHandlePieBottom,
size_roundedHandleBottom);
QRect rect_roundedHandleFillerRect(rect_roundedHandle.x()+rect_roundedHandle.width(),
point_roundedHandlePieTop.y()+size_roundedHandleTop.height()/2,
size_roundedHandleTop.width()/2,
/*rect_roundedHandle.height()-size_roundedHandleTop.height()/2-size_roundedHandleBottom.height()/2*/
/*rect_roundedHandle.y()+rect_roundedHandle.height()-size_roundedHandleBottom.height()*/
rect_roundedHandle.height()-size_roundedHandleBottom.height()/2-size_roundedHandleTop.height()/2);
painter->setRenderHint(QPainter::Antialiasing,true);
painter->setBrush(handleBorderColor);
painter->setPen(QPen(handleBorderColor,border_roundedHandleWidth*2));
painter->drawRect(rect_roundedHandle.x(),rect_roundedHandle.y(),rect_roundedHandle.width(),rect_roundedHandle.height());
painter->drawPie(rect_roundedHandleTop,360*16,360*4);
painter->drawPie(rect_roundedHandleBottom,360*12,360*4);
painter->drawRect(rect_roundedHandleFillerRect);
painter->setBrush(handleBackground);
painter->setPen(QPen(handleBackground,-1));
painter->fillRect(rect_roundedHandle.x(),rect_roundedHandle.y(),rect_roundedHandle.width(),rect_roundedHandle.height(),handleBackground);
painter->drawPie(rect_roundedHandleTop,360*16,360*4);
painter->drawPie(rect_roundedHandleBottom,360*12,360*4);
painter->fillRect(rect_roundedHandleFillerRect,handleBackground);
}
break;
default:
//painter->fillRect(0,0,this->width()/2,this->height(),barBackgroundTop);
break;
}
}
default:
break;
}
}
default:
break;
}
}
void LCARS_Slider::paintBar(QPainter *painter) {
switch (sliderMode) {
case 0:{
int height1 = barTopLine.height();
int height2 = barBottomLine.height();
int y1 = (this->height()/2-height1)/2;
int y2 = ((this->height()/2-height1)/2)+this->height()/2;
painter->fillRect(0,y1+1,this->width(),height1,barBackgroundTop); //QColor("#ff9900")
painter->fillRect(0,y2+1,this->width(),height2,barBackgroundBottom);
}
case 1: {
}
break;
case 2:
{
switch (orientation()) {
case Qt::Horizontal:
{
}
break;
case Qt::Vertical:
{
switch (this->layoutDirection()) {
case Qt::LeftToRight:
{
painter->fillRect(this->width(),0,-1*(roundHandle_Bar_width),this->height(),bar_roundedHandleColor);
}
break;
case Qt::RightToLeft:
{
painter->fillRect(0,0,roundHandle_Bar_width,this->height(),bar_roundedHandleColor);
}
break;
default:
break;
}
}
default:
break;
}
}
default:
break;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
2008727d1d83d1081e6aec63d743f4e0ef52c39f | fea665e9515cf1f7618da4d728bf4b9cdc7302dc | /5. Challanges --Bits Manuplation/2. Unique Numbers.cpp | f009e8f8e904ebf101401f942d7646e53cb0d8c7 | [] | no_license | Harshal0506/GYM-FOR-MY-CP-JOURNEY | c8d94997bc790e9997421e53f1807b2e8a7ecfc5 | 3a44b82fbb3b2cd457d4db1dbc9e42fcf6150507 | refs/heads/main | 2023-04-25T13:07:42.320659 | 2021-05-16T16:29:39 | 2021-05-16T16:29:39 | 359,478,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | cpp | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
#define ff first
#define ss second
#define int long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define mii map<int,int>
#define pqb priority_queue<int>
#define pqs priority_queue<int,vi,greater<int> >
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define inf 1e18
#define ps(x,y) fixed<<setprecision(y)<<x
#define mk(arr,n,type) type *arr=new type[n];
#define w(x) int x; cin>>x; while(x--)
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
void c_p_c()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int32_t main()
{
c_p_c();
int n;
cin>>n;
int x;
int Exor=0;
for(int i=0;i<n;i++){
cin>>x;
Exor^=x;
}
cout<<"The unique element is "<<Exor<<endl;
return 0;
} | [
"Harshaljain0055@gmail.com"
] | Harshaljain0055@gmail.com |
f259749378ecb8d050c90421b5a907e21125e9a3 | 3d14bd13a8c113e754d149b2507dfe9ffbbb290e | /Source/ZNTestGame/UserInterface/ViewHumanFirstPerson.cpp | 4867fbac9f15c11d8dd3b4578c2d180addde327c | [] | no_license | tzemanovic/gp2cw | 34ed711a66a4bec521fcf084d5406b7a4b32488e | f92b9bf9ea86012d2e43100b96431bd9845af863 | refs/heads/master | 2021-05-26T19:54:50.818248 | 2012-12-06T15:53:13 | 2012-12-06T15:53:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,582 | cpp | ////////////////////////////////////////////////////
// human first person view
////////////////////////////////////////////////////
#include "ZNTestGameStd.h"
#include "ViewHumanFirstPerson.h"
namespace zn
{
ViewHumanFirstPerson::ViewHumanFirstPerson() : ViewHuman(), m_pHumanChar( NULL ),
m_isFreeCameraController( false ), m_pFirstPersonController( NULL )
{
}
ViewHumanFirstPerson::~ViewHumanFirstPerson()
{
ZN_SAFE_DELETE( m_pFirstPersonController );
}
void ViewHumanFirstPerson::VInit()
{
ViewHuman::VInit();
if( m_pRenderer )
{
m_pFirstPersonController = ZN_NEW FirstPersonController( 0 );
m_pKeyboardHandler = m_pFirstPersonController;
m_pMouseHandler = m_pFirstPersonController;
g_pGame->GetWindow()->CaptureMouse();
}
}
void ViewHumanFirstPerson::VUpdate( const float deltaMs )
{
if( !m_isFreeCameraController && m_pFirstPersonController )
{
m_pFirstPersonController->Update( deltaMs );
}
ViewHuman::VUpdate( deltaMs );
}
const bool ViewHumanFirstPerson::VProcessMessage( const Message& message )
{
if( message == Message::KeyUp )
{
if( message.key.type == Key::F2 )
{
if( m_isFreeCameraController )
{
m_pCamera->SetTarget( m_pHumanChar );
m_pKeyboardHandler = m_pFirstPersonController;
m_pMouseHandler = m_pFirstPersonController;
m_isFreeCameraController = false;
}
else
{
m_pCamera->ClearTarget();
m_pKeyboardHandler = m_pFreeCameraController;
m_pMouseHandler = m_pFreeCameraController;
m_isFreeCameraController = true;
}
}
}
return ViewHuman::VProcessMessage( message );
}
void ViewHumanFirstPerson::VSetOwner( GameObjectId id )
{
ViewHuman::VSetOwner( id );
m_pHumanChar = m_pScene->FindGameObject( id );
m_pCamera->SetTarget( m_pHumanChar );
}
void ViewHumanFirstPerson::SetControlledObject( shared_ptr< FirstPersonCharacterComponent > pFirstPersonComp )
{
if( m_pFirstPersonController )
{
m_pFirstPersonController->SetControlledObject( pFirstPersonComp );
}
}
} | [
"tzemanovic@gmail.com"
] | tzemanovic@gmail.com |
8bb1a9a9dbd0fad82cbdc06513ceac04e54e0530 | 314e32208d36c2df9bb444b72c55d88226198f41 | /gauss.h | 1147043079f187d9db3543fa393e9e02640c678b | [] | no_license | IVarha/nefclass | 00080dfc2f97f322344822f3d009755ccba9827a | 6cef9003fa3850f6f8d95f00619086f8445893b1 | refs/heads/master | 2021-07-11T07:32:54.160273 | 2017-10-17T09:33:23 | 2017-10-17T09:33:23 | 107,248,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | h | #ifndef GAUSS_H
#define GAUSS_H
class Gauss
// public FuzzyWeight
{
public:
Gauss(double a, double b);
Gauss();
~Gauss();
bool operator==(const Gauss & other);
Gauss operator=(const Gauss & other);
// Inherited via FuzzyWeight
double evaluate(double x);
void setRuleClass(int cl);
double getA();
double getB();
private:
double a;
double b;
int ruleClass;
// Inherited via FuzzyWeight
};
#endif
| [
"igorvarga@MacBook-Pro-Igor.local"
] | igorvarga@MacBook-Pro-Igor.local |
a51e040fb2a5e22a8b80fd9c964691ef102e957f | 386556e9b9083aa72d6c04e9fd1b29a11e3abaec | /30_Days_Challenge/Day18(Stacks_Queues).cpp | cb95be9f45bd0186b1503080b5a651b10e7922c7 | [] | no_license | Thayjes/HackerRank | 5704aece07968f41082347e72b7f9f05cea201a9 | 973a6fca83818174a589e0d1f3d64b7ae8f0d3b7 | refs/heads/master | 2021-07-17T19:59:09.216958 | 2017-10-26T03:12:11 | 2017-10-26T03:12:11 | 103,687,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,214 | cpp | /*Input Format
You do not need to read anything from stdin. The locked stub code in your editor reads a single line containing string . It then calls the methods specified above to pass each character to your instance variables.
Constraints
is composed of lowercase English letters.
Output Format
You are not responsible for printing any output to stdout.
If your code is correctly written and is a palindrome, the locked stub code will print ; otherwise, it will print
Sample Input
racecar
Sample Output
The word, racecar, is a palindrome. */
#include <iostream>
#include<stack>
#include<queue>
using namespace std;
class Solution {
//Write your code here
public:
queue<char> myqueue;
stack<char> mystack;
void pushCharacter(char ch){
mystack.push(ch);
}
void enqueueCharacter(char ch){
myqueue.push(ch);
}
char popCharacter(){
char temp = mystack.top();
mystack.pop();
return temp;
}
char dequeueCharacter(){
char temp = myqueue.front();
myqueue.pop();
return temp;
}
}; | [
"thayjes.srivas@gmail.com"
] | thayjes.srivas@gmail.com |
70c2b5768c65d0b0f92725b87c8524e78fcdc03c | 5fcacbc63db76625cc60ffc9d6ed58a91f134ea4 | /vxl/vxl-1.13.0/contrib/brl/bseg/boxm/opt/tests/test_driver.cxx | 739217a5cfc12f04ba7a15b2bc4d124522af808f | [] | no_license | EasonZhu/rcc | c809956eb13fb732d1b2c8035db177991e3530aa | d230b542fa97da22271b200e3be7441b56786091 | refs/heads/master | 2021-01-15T20:28:26.541784 | 2013-05-14T07:18:12 | 2013-05-14T07:18:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 156 | cxx | #include <testlib/testlib_register.h>
DECLARE( test_bayesian_optimizer );
void register_tests()
{
REGISTER( test_bayesian_optimizer );
}
DEFINE_MAIN;
| [
"hieuza@gmail.com"
] | hieuza@gmail.com |
c41a10938dfe5ff0e2c192ea82f023fdd3ed49fb | cdc4b28a1f04aa31b07373a9cad47574c2b986e2 | /t5_23.cpp | da6a2cd93010a27a2d44d132821885fda565b196 | [] | no_license | pw-ethan/CPP-Primer | fe2fbe900c1cf01f5dfd93550a0d581d062dfe7c | fde28b2de88372a94eead514b99131014fbccac2 | refs/heads/master | 2021-01-25T06:06:41.332946 | 2017-06-06T13:51:31 | 2017-06-06T13:51:31 | 93,523,811 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | #include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
int a, b;
while(cin >> a >> b){
try{
if(b == 0){
throw runtime_error("/ by 0");
}
cout << a << " / " << b << " = " << a / b << endl;
}catch(runtime_error err){
cout << err.what() << endl;
cout << "Try Again? Enter y or n" << endl;
char c;
cin >> c;
if(!cin || c == 'n'){
break;
}
}
}
return 0;
}
| [
"pw-ethan@localhost.localdomain"
] | pw-ethan@localhost.localdomain |
7527a62351b066d2544bd03615e01b5d7238b87b | 83a15e04a196e51e4593791cc10f83687c55a884 | /handlers/Filter/FilterableValue.h | df185d40bdbb58488cca95b0a9c5b79d232621c1 | [] | no_license | solisqq/HawkRC | 8defb1a887df5bc28ffc6b38670ef42ce6e12d0e | 602ccc761f37befb8b8f0e77dc7358ef60e9553e | refs/heads/master | 2023-03-12T16:00:00.195535 | 2021-02-25T21:56:10 | 2021-02-25T21:56:10 | 172,204,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,351 | h | #pragma once
#ifndef FILTERABLEVALUE_H
#define FILTERABLEVALUE_H
#include "C:/Users/kamil/Documents/Programming/HawkRC/handlers/Filter/Filter.h"
#include "C:/Users/kamil/Documents/Programming/HawkRC/structures/List.h"
#include "C:/Users/kamil/Documents/Programming/HawkRC/handlers/Output/AllowPrint.h"
template <class Type>
class FilterableValue: public AllowPrint {
public:
Type value;
FilterableValue(){}
List<Filter<Type>*> filters;
~FilterableValue(){
for(typename List<Filter<Type>*>::Node *it = filters.front; it!=nullptr; it=it->next)
delete it->val;
}
void update(Type val) {
if(filters.count()==0) {
value = val;
return;
}
typename List<Filter<Type>*>::Node *current = filters.front;
if(current!=nullptr) {
filters.front->val->update(val);
current = current->next;
while(current!=nullptr) {
current->val->update(current->prev->val->filtered);
current = current->next;
}
value = filters.back->val->filtered;
}
}
void reset() {
typename List<Filter<Type>*>::Node *current = filters.front;
if(current!=nullptr) {
filters.front->val->reset();
current = current->next;
}
}
void addFilter(Filter<Type>* filter) {
filters.pushBack(filter);
}
void addFilter(List<Filter<Type>*> filter) {
filters.Union(filter);
}
String toString() {
return String(value);
}
};
#endif | [
"solisqq"
] | solisqq |
a4048e52bc5c7850324ea2f8e01be7f73069235f | fff2127659e2432ef268f39cf152eb96e15c5b34 | /StdAfx.h | ea613eb340ebca41b31640633fd4da583eaf9922 | [
"MIT"
] | permissive | 1m30s/EasySRT | 92a21db9f77891f1c4e8e74e18ae03df447d69d3 | 2a4cb580d787f4446c42882c36c74c0c801bb88a | refs/heads/master | 2023-02-04T01:52:56.579224 | 2013-08-18T12:23:42 | 2013-08-18T12:23:42 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,340 | h | // stdafx.h : 標準のシステム インクルード ファイル、
// または参照回数が多く、かつあまり変更されない
// プロジェクト専用のインクルード ファイルを記述します。
//
#if !defined(AFX_STDAFX_H__CE1C2ED7_2E1A_417B_B7E6_AEE047B148C4__INCLUDED_)
#define AFX_STDAFX_H__CE1C2ED7_2E1A_417B_B7E6_AEE047B148C4__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define VC_EXTRALEAN // Windows ヘッダーから殆ど使用されないスタッフを除外します。
#include <afxwin.h> // MFC のコアおよび標準コンポーネント
#include <afxext.h> // MFC の拡張部分
#include <afxdisp.h> // MFC のオートメーション クラス
#include <afxdtctl.h> // MFC の Internet Explorer 4 コモン コントロール サポート
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC の Windows コモン コントロール サポート
#endif // _AFX_NO_AFXCMN_SUPPORT
#include "wmpids.h"
#include "wmp.h"
#include <string.h>
#include <vector>
using namespace std;
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ は前行の直前に追加の宣言を挿入します。
#endif // !defined(AFX_STDAFX_H__CE1C2ED7_2E1A_417B_B7E6_AEE047B148C4__INCLUDED_)
| [
"rev_c1815@yahoo.co.jp"
] | rev_c1815@yahoo.co.jp |
cd34b9fbfd9c42a91516407be9ddfcba3a8cc144 | a2e04e4eac1cf93bb4c1d429e266197152536a87 | /Cpp/SDK/BP_tls_tankard_ice_01_a_ItemInfo_classes.h | 107ae8ba52f4ca51144a8705d7766cddfc022a7a | [] | no_license | zH4x-SDK/zSoT-SDK | 83a4b9fcdf628637613197cf644b7f4d101bb0cb | 61af221bee23701a5df5f60091f96f2cf929846e | refs/heads/main | 2023-07-16T18:23:41.914014 | 2021-08-27T15:44:23 | 2021-08-27T15:44:23 | 400,555,804 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_tls_tankard_ice_01_a_ItemInfo.BP_tls_tankard_ice_01_a_ItemInfo_C
// 0x0008 (FullSize[0x0518] - InheritedSize[0x0510])
class ABP_tls_tankard_ice_01_a_ItemInfo_C : public AItemInfo
{
public:
class USceneComponent* DefaultSceneRoot; // 0x0510(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_tls_tankard_ice_01_a_ItemInfo.BP_tls_tankard_ice_01_a_ItemInfo_C");
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
266fddb54246a67665cf403e4735807ddcffcbfe | 4ef9ec047c984a1ce5668128ea11c711d80144f4 | /is_prime.cpp | aaa7298d1eb84913374833c5fab8245ead569621 | [] | no_license | abhaykagalkar/routine_codes | b6391299ff270661f0294ea5e9bc5c6c18bc5590 | 318813156f30404ea54b6aeb3d6ed125dc6a9f93 | refs/heads/master | 2020-05-07T22:30:46.885821 | 2019-04-02T08:50:20 | 2019-04-02T08:50:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
bool is_prime(int n) {
// Assumes that n is a positive natural number
// We know 1 is not a prime number
if (n == 1) {
return false;
}
int i = 2;
// This will loop from 2 to int(sqrt(x))
while (i*i <= n) {
// Check if i divides x without leaving a remainder
if (n % i == 0) {
// This means that n has a factor in between 2 and sqrt(n)
// So it is not a prime number
return false;
}
i += 1;
}
// If we did not find any factor in the above loop,
// then n is a prime number
return true;
}
int main()
{
int n, k =3,num;
cin>>n;
for(int i=0;i<n;i++){
cin>>num;
is_prime(num) ? cout << "Prime"<<endl :
cout << "Not prime"<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
b11efe2dee04d1841d66ff02fe4c21c861982b24 | 2ba94892764a44d9c07f0f549f79f9f9dc272151 | /Engine/Source/Editor/Sequencer/Private/SSequencerTrackOutliner.h | 2627998cfa7ee09e8084f40af0d8145f7269ff47 | [
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] | permissive | PopCap/GameIdea | 934769eeb91f9637f5bf205d88b13ff1fc9ae8fd | 201e1df50b2bc99afc079ce326aa0a44b178a391 | refs/heads/master | 2021-01-25T00:11:38.709772 | 2018-09-11T03:38:56 | 2018-09-11T03:38:56 | 37,818,708 | 0 | 0 | BSD-2-Clause | 2018-09-11T03:39:05 | 2015-06-21T17:36:44 | null | UTF-8 | C++ | false | false | 253 | h | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
/**
* The area where outliner nodes for each track is stored
*/
class SSequencerTrackOutliner : public SVerticalBox
{
public:
void Construct( const FArguments& InArgs );
};
| [
"dkroell@acm.org"
] | dkroell@acm.org |
6aea1336c007be248f85375aa9fb0ce5dc3b5983 | 518bd84e3e659e514d44cc3a49bd1750447bffc0 | /srs/src/app/srs_app_caster_flv.hpp | 11a6ea493f9f9596d04381591f7a4a72d7390c2a | [] | no_license | lxq00/srs-win-linux | 1b225f107bc7349ab2da5c29f60bcd5246e43ab8 | 3562f05bfdec64f0f809090ad2c7a83cb4a27151 | refs/heads/master | 2020-03-26T16:45:00.640726 | 2018-08-19T08:45:07 | 2018-08-19T08:45:07 | 145,121,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,827 | hpp | /**
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Winlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_APP_CASTER_FLV_HPP
#define SRS_APP_CASTER_FLV_HPP
#include <srs_core.hpp>
#include <string>
#include <vector>
#ifdef SRS_AUTO_STREAM_CASTER
class SrsConfDirective;
class SrsHttpServeMux;
class SrsRtmpClient;
class SrsStSocket;
class SrsRequest;
class SrsPithyPrint;
class ISrsHttpResponseReader;
class SrsFlvDecoder;
class SrsTcpClient;
class SrsSimpleRtmpClient;
#include <srs_app_thread.hpp>
#include <srs_app_listener.hpp>
#include <srs_app_conn.hpp>
#include <srs_app_http_conn.hpp>
#include <srs_kernel_file.hpp>
/**
* the stream caster for flv stream over HTTP POST.
*/
class SrsAppCasterFlv : virtual public ISrsTcpHandler
, virtual public IConnectionManager, virtual public ISrsHttpHandler
{
private:
std::string output;
SrsHttpServeMux* http_mux;
std::vector<SrsHttpConn*> conns;
SrsCoroutineManager* manager;
public:
SrsAppCasterFlv(SrsConfDirective* c);
virtual ~SrsAppCasterFlv();
public:
virtual srs_error_t initialize();
// ISrsTcpHandler
public:
virtual srs_error_t on_tcp_client(srs_netfd_t stfd);
// IConnectionManager
public:
virtual void remove(ISrsConnection* c);
// ISrsHttpHandler
public:
virtual srs_error_t serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r);
};
/**
* the dynamic http connection, never drop the body.
*/
class SrsDynamicHttpConn : public SrsHttpConn
{
private:
std::string output;
SrsPithyPrint* pprint;
SrsSimpleRtmpClient* sdk;
public:
SrsDynamicHttpConn(IConnectionManager* cm, srs_netfd_t fd, SrsHttpServeMux* m, std::string cip);
virtual ~SrsDynamicHttpConn();
public:
virtual srs_error_t on_got_http_message(ISrsHttpMessage* msg);
public:
virtual srs_error_t proxy(ISrsHttpResponseWriter* w, ISrsHttpMessage* r, std::string o);
private:
virtual srs_error_t do_proxy(ISrsHttpResponseReader* rr, SrsFlvDecoder* dec);
};
/**
* the http wrapper for file reader,
* to read http post stream like a file.
*/
class SrsHttpFileReader : public SrsFileReader
{
private:
ISrsHttpResponseReader* http;
public:
SrsHttpFileReader(ISrsHttpResponseReader* h);
virtual ~SrsHttpFileReader();
public:
/**
* open file reader, can open then close then open...
*/
virtual srs_error_t open(std::string file);
virtual void close();
public:
// TODO: FIXME: extract interface.
virtual bool is_open();
virtual int64_t tellg();
virtual void skip(int64_t size);
virtual int64_t seek2(int64_t offset);
virtual int64_t filesize();
public:
virtual srs_error_t read(void* buf, size_t count, size_t* pnread);
virtual srs_error_t lseek(off_t offset, int whence, off_t* seeked);
};
#endif
#endif
| [
"lxq00@foxmail.com"
] | lxq00@foxmail.com |
c14c8f8544c4aa6df0c20981fada3776cadc7115 | 1e395205d1c315c269a44c2e465831f862b2a491 | /src/nimbro_robotcontrol/contrib/rbdl/source/include/rbdl/Model.h | 6631c82c7a293baecd3e6e1992bb6979ecff9054 | [
"Zlib"
] | permissive | anh0001/EROS | 01c46f88cc91ef0677b482124b2974790143e723 | a5fae8bf9612cd13fbbcfc0838685430a6fe8fa4 | refs/heads/master | 2021-08-28T00:07:13.261399 | 2021-08-20T08:56:12 | 2021-08-20T08:56:12 | 195,176,022 | 0 | 2 | MIT | 2021-08-20T08:52:12 | 2019-07-04T05:44:14 | null | UTF-8 | C++ | false | false | 14,691 | h | /*
* RBDL - Rigid Body Dynamics Library
* Copyright (c) 2011-2012 Martin Felis <martin.felis@iwr.uni-heidelberg.de>
*
* Licensed under the zlib license. See LICENSE for more details.
*/
#ifndef _MODEL_H
#define _MODEL_H
#include <rbdl/rbdl_math.h>
#include <map>
#include <list>
#include <assert.h>
#include <iostream>
#include <limits>
#include <cstring>
#include "rbdl/Logging.h"
#include "rbdl/Joint.h"
#include "rbdl/Body.h"
// std::vectors containing any objectst that have Eigen matrices or vectors
// as members need to have a special allocater. This can be achieved with
// the following macro.
#ifdef EIGEN_CORE_H
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(RigidBodyDynamics::Joint);
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(RigidBodyDynamics::Body);
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(RigidBodyDynamics::FixedBody);
#endif
/** \brief Namespace for all structures of the RigidBodyDynamics library
*/
namespace RigidBodyDynamics {
/** \defgroup model_group Modelling
* @{
*
* There are two ways of creating models for RBDL:
*
* \li Using \ref luamodel_introduction that uses Lua files or
* \li using the C++ interface.
*
* The first approach requires the addon \ref luamodel_introduction to be
* activated which is done by enabling BUILD_ADDON_LUAMODEL in CMake and is
* recommended when one is not interested in the details of RBDL and simply
* wants to create a model.
*
* \section modeling_lua Modeling using Lua
*
* For this see the documentation of \ref luamodel_introduction.
*
* \section modeling_cpp Modeling using C++
*
* Using the C++ interface is more advanced but gives some overview about the
* internals of RBDL.
*
* \subsection modeling_overview Overview
*
* All model related values are stored in the model structure \link
* RigidBodyDynamics::Model\endlink. The functions
* \link RigidBodyDynamics::Model::AddBody Model::AddBody(...)\endlink,
* \link RigidBodyDynamics::Model::AppendBody Model::AppendBody(...)\endlink, and
* \link RigidBodyDynamics::Model::GetBodyId Model::GetBodyId(...)\endlink,
* are used to construct the \ref model_structure.
*
* \section model_construction Model Construction
*
* The construction of \link RigidBodyDynamics::Model Models \endlink makes
* use of carefully designed constructors of the classes \link
* RigidBodyDynamics::Body Body \endlink and \link RigidBodyDynamics::Joint
* Joint \endlink to ease the process of articulated models. Adding bodies to
* the model is done by specifying the parent body by its id, the
* transformation from the parent origin to the joint origin, the joint
* specification as an object, and the body itself. These parameters are
* then fed to the function RigidBodyDynamics::Model::AddBody().
*
* To create a model with a floating base (a.k.a a model with a free-flyer
* joint) it is recommended to use \link
* RigidBodyDynamics::Model::SetFloatingBaseBody
* Model::SetFloatingBaseBody(...)\endlink.
*
* Once this is done, the model structure can be used with the functions of \ref
* kinematics_group, \ref dynamics_group, \ref contacts_group, to perform
* computations.
*
* A simple example can be found \ref SimpleExample "here".
*
* \subsection model_structure Model Structure
*
* The model structure contains all the parameters of the rigid multi-body
* model such as joint informations, mass and inertial parameters of the
* rigid bodies, etc. It also contains storage for the transformations and
* current state, such as velocity and acceleration of each body.
*
* \subsection joint_models Joint Modeling
*
* The Rigid Body Dynamics Library supports models with multiple degrees of
* freedom. When a joint with more than one degrees of freedom is used,
* additional virtual bodies with zero mass that are connected by 1 degree
* of freedom joints to simulate the multiple degrees of freedom joint. Even
* though this adds some overhead in terms of memory usage, it allows to
* exploit fast computations on fixed size elements of the underlying math
* library Eigen3.
*
* Joints are defined by their motion subspace. For each degree of freedom
* a one dimensional motion subspace is specified as a Math::SpatialVector.
* This vector follows the following convention:
* \f[ (r_x, r_y, r_z, t_x, t_y, t_z) \f]
*
* To specify a planar joint with three degrees of freedom for which the
* first two are translations in \f$x\f$ and \f$y\f$ direction and the last
* is a rotation around \f$z\f$, the following joint definition can be used:
*
* \code
* Joint planar_joint = Joint (
* Math::SpatialVector (0., 0., 0., 1., 0., 0.),
* Math::SpatialVector (0., 0., 0., 0., 1., 0.),
* Math::SpatialVector (0., 0., 1., 0., 0., 0.)
* );
* \endcode
*
* \subsubsection joint_models_fixed Fixed Joints
*
* Fixed joints do not add an additional degree of freedom to the model.
* When adding a body that via a fixed joint (i.e. when the type is
* JointTypeFixed) then the dynamical parameters mass and inertia are
* merged onto its moving parent. By doing so fixed bodies do not add
* computational costs when performing dynamics computations.
* To ensure a consistent API for the Kinematics such fixed bodies have a
* different range of ids. Where as the ids start at 1 get incremented for
* each added body, fixed bodies start at Model::fixed_body_discriminator
* which has a default value of std::numeric_limits<unsigned int>::max() /
* 2. This means theoretical a maximum of each 2147483646 movable and fixed
* bodies are possible.
* To check whether a body is connected by a fixed joint you can use the
* function Model::IsFixedBodyId().
*
* See also: \link RigidBodyDynamics::Joint Joint\endlink.
*
* \note Please note that in the Rigid %Body Dynamics Library all angles
* are specified in radians.
*/
/** \brief Contains all information about the rigid body model
*
* This class contains all information required to perform the forward
* dynamics calculation. The variables in this class are also used for
* storage of temporary values. It is designed for use of the Articulated
* Rigid Body Algorithm (which is implemented in ForwardDynamics()) and
* follows the numbering as described in Featherstones book.
*
* An important note is that body 0 is the root body and the moving bodies
* start at index 1. Additionally the vectors for the states q, qdot, etc.
* have \#Model::mBodies + 1 entries where always the first entry (e.g.
* q[0]) contains the value for the base (or "root" body). Thus the
* numbering might be confusing as q[1] holds the position variable of the
* first added joint. This numbering scheme is very beneficial in terms of
* readability of the code as the resulting code is very similar to the
* pseudo-code in the RBDA book.
*
* \note To query the number of degrees of freedom use Model::dof_count.
*/
struct Model {
Model();
// Structural information
/// \brief The id of the parents body
std::vector<unsigned int> lambda;
/// \brief Contains the ids of all the children of a given body
std::vector<std::vector<unsigned int> >mu;
/** \brief number of degrees of freedoms of the model
*
* This value contains the number of entries in the generalized state (q)
* velocity (qdot), acceleration (qddot), and force (tau) vector.
*/
unsigned int dof_count;
/// \brief Id of the previously added body, required for Model::AppendBody()
unsigned int previously_added_body_id;
/// \brief the cartesian vector of the gravity
Math::Vector3d gravity;
// State information
/// \brief The spatial velocity of the bodies
std::vector<Math::SpatialVector> v;
/// \brief The spatial acceleration of the bodies
std::vector<Math::SpatialVector> a;
////////////////////////////////////
// Joints
/// \brief All joints
std::vector<Joint> mJoints;
/// \brief The joint axis for joint i
std::vector<Math::SpatialVector> S;
/// \brief Transformations from the parent body to the frame of the joint
std::vector<Math::SpatialTransform> X_T;
/// \brief The number of fixed joints that have been declared before each joint.
std::vector<unsigned int> mFixedJointCount;
////////////////////////////////////
// Dynamics variables
/// \brief The velocity dependent spatial acceleration
std::vector<Math::SpatialVector> c;
/// \brief The spatial inertia of the bodies
std::vector<Math::SpatialMatrix> IA;
/// \brief The spatial bias force
std::vector<Math::SpatialVector> pA;
/// \brief Temporary variable U_i (RBDA p. 130)
std::vector<Math::SpatialVector> U;
/// \brief Temporary variable D_i (RBDA p. 130)
Math::VectorNd d;
/// \brief Temporary variable u (RBDA p. 130)
Math::VectorNd u;
/// \brief Internal forces on the body (used only InverseDynamics())
std::vector<Math::SpatialVector> f;
/// \brief The spatial inertia of body i (used only in CompositeRigidBodyAlgorithm())
std::vector<Math::SpatialRigidBodyInertia> Ic;
////////////////////////////////////
// Bodies
/// \brief Transformation from the parent body to the current body
std::vector<Math::SpatialTransform> X_lambda;
/// \brief Transformation from the base to bodies reference frame
std::vector<Math::SpatialTransform> X_base;
/// \brief All bodies that are attached to a body via a fixed joint.
std::vector<FixedBody> mFixedBodies;
/** \brief Value that is used to discriminate between fixed and movable
* bodies.
*
* Bodies with id 1 .. (fixed_body_discriminator - 1) are moving bodies
* while bodies with id fixed_body_discriminator .. max (unsigned int)
* are fixed to a moving body. The value of max(unsigned int) is
* determined via std::numeric_limits<unsigned int>::max() and the
* default value of fixed_body_discriminator is max (unsigned int) / 2.
*
* On normal systems max (unsigned int) is 4294967294 which means there
* could be a total of 2147483646 movable and / or fixed bodies.
*/
unsigned int fixed_body_discriminator;
/** \brief All bodies 0 ... N_B, including the base
*
* mBodies[0] - base body <br>
* mBodies[1] - 1st moveable body <br>
* ... <br>
* mBodies[N_B] - N_Bth moveable body <br>
*/
std::vector<Body> mBodies;
/// \brief Human readable names for the bodies
std::map<std::string, unsigned int> mBodyNameMap;
/** \brief Connects a given body to the model
*
* When adding a body there are basically informations required:
* - what kind of body will be added?
* - where is the new body to be added?
* - by what kind of joint should the body be added?
*
* The first information "what kind of body will be added" is contained
* in the Body class that is given as a parameter.
*
* The question "where is the new body to be added?" is split up in two
* parts: first the parent (or successor) body to which it is added and
* second the transformation to the origin of the joint that connects the
* two bodies. With these two informations one specifies the relative
* positions of the bodies when the joint is in neutral position.gk
*
* The last question "by what kind of joint should the body be added?" is
* again simply contained in the Joint class.
*
* \param parent_id id of the parent body
* \param joint_frame the transformation from the parent frame to the origin
* of the joint frame (represents X_T in RBDA)
* \param joint specification for the joint that describes the connection
* \param body specification of the body itself
* \param body_name human readable name for the body (can be used to retrieve its id
* with GetBodyId())
*
* \returns id of the added body
*/
unsigned int AddBody (
const unsigned int parent_id,
const Math::SpatialTransform &joint_frame,
const Joint &joint,
const Body &body,
std::string body_name = ""
);
/** \brief Adds a Body to the model such that the previously added Body is the Parent.
*
* This function is basically the same as Model::AddBody() however the
* most recently added body (or body 0) is taken as parent.
*/
unsigned int AppendBody (
const Math::SpatialTransform &joint_frame,
const Joint &joint,
const Body &body,
std::string body_name = ""
);
/** \brief Specifies the dynamical parameters of the first body and
* \brief assigns it a 6 DoF joint.
*
* The 6 DoF joint is simulated by adding 5 massless bodies at the base
* which are connected with joints. The body that is specified as a
* parameter of this function is then added by a 6th joint to the model.
*
* The floating base has the following order of degrees of freedom:
*
* \li translation X
* \li translation Y
* \li translation Z
* \li rotation Z
* \li rotation Y
* \li rotation X
*
* To specify a different ordering, it is recommended to create a 6 DoF
* joint. See \link RigidBodyDynamics::Joint Joint\endlink for more
* information.
*
* \param body Properties of the floating base body.
*
* \returns id of the body with 6 DoF
*/
unsigned int SetFloatingBaseBody (
const Body &body
);
/** \brief Returns the id of a body that was passed to AddBody()
*
* Bodies can be given a human readable name. This function allows to
* resolve its name to the numeric id.
*
* \note Instead of querying this function repeatedly, it might be
* advisable to query it once and reuse the returned id.
*
* \returns the id of the body or \c std::numeric_limits<unsigned int>::max() if the id was not found.
*/
unsigned int GetBodyId (const char *body_name) const {
if (mBodyNameMap.count(body_name) == 0) {
return std::numeric_limits<unsigned int>::max();
}
return mBodyNameMap.find(body_name)->second;
}
/** \brief Returns the name of a body for a given body id */
std::string GetBodyName (unsigned int body_id) const {
std::map<std::string, unsigned int>::const_iterator iter = mBodyNameMap.begin();
while (iter != mBodyNameMap.end()) {
if (iter->second == body_id)
return iter->first;
iter++;
}
return "";
}
/** \brief Checks whether the body is rigidly attached to another body.
*/
bool IsFixedBodyId (unsigned int body_id) {
if (body_id >= fixed_body_discriminator
&& body_id < std::numeric_limits<unsigned int>::max()
&& body_id - fixed_body_discriminator < mFixedBodies.size()) {
return true;
}
return false;
}
bool IsBodyId (unsigned int id) {
if (id > 0 && id < mBodies.size())
return true;
if (id >= fixed_body_discriminator && id < std::numeric_limits<unsigned int>::max()) {
if (id - fixed_body_discriminator < mFixedBodies.size())
return true;
}
return false;
}
};
/** @} */
}
#endif /* _MODEL_H */
| [
"anhrisn@gmail.com"
] | anhrisn@gmail.com |
cd430b4ef63d047ae17519bdaf2da350895227ea | 78d9dbbdd09559cfc5f011fbfeb098a603908612 | /functions.cpp | 7be2a71b8eedd162ffd58c3b18c869fe08319c29 | [] | no_license | martin-bn/MyProject | 917a71f1e021ae5361814297289a6f209f07a5a9 | 3d2e1583ef88003cd0d23be1036d275cbe8b2984 | refs/heads/master | 2022-11-29T09:38:51.629346 | 2020-07-29T12:25:45 | 2020-07-29T12:25:45 | 283,441,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | cpp | #include <iostream>
using namespace std;
void sayHi(string name, int age){
cout << "Hello, " << name << " you are " << age;
}
int main()
{
cout << "Top \n";
sayHi("Mike", 64);
cout << "\n Bottom";
sayHi("Aria", 45);
return 0;
}
| [
"mbnesse@gmail.com"
] | mbnesse@gmail.com |
247b3324b7df65953b7f0d988dc65f3d52baa4a9 | a0dfadd795c65d6b944e36c11462a08ed53b78ae | /foo/tests/src/test_main.cpp | 90109911d413b510261d681cf801876d8d7d54ce | [
"MIT"
] | permissive | FerranGarcia/CMakeTemplate | cca9d6b621891cd63cc937b2e66966c8198275d4 | aa7ff44775b4d61b730933199df1f4d57b4d7679 | refs/heads/master | 2020-06-20T15:07:48.199083 | 2019-07-16T15:27:08 | 2019-07-16T15:27:08 | 196,224,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 119 | cpp | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <foo/foo.h>
TEST_CASE( "run" ) {
REQUIRE( 2 == 2 );
} | [
"ferran.garcia@softbankrobotics.com"
] | ferran.garcia@softbankrobotics.com |
62b4690819e678b999a0b0f05021187c1f370628 | cffc460605febc80e8bb7c417266bde1bd1988eb | /before2020/ZeroJudge/ZJ b082.cpp | 5ee2c65e0de070bfa6914366e785324f01b2f757 | [] | no_license | m80126colin/Judge | f79b2077f2bf67a3b176d073fcdf68a8583d5a2c | 56258ea977733e992b11f9e0cb74d630799ba274 | refs/heads/master | 2021-06-11T04:25:27.786735 | 2020-05-21T08:55:03 | 2020-05-21T08:55:03 | 19,424,030 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 518 | cpp | #include <iostream>
#include <string>
using namespace std;
struct bone{
int a;
char ch;
int b;
};
int main() {
string s,ss;
int n,m,i,t;
bone x[302];
for (cin>>n;n;n--) {
for (cin>>m,i=1;i<=m;i++) cin>>x[i].a>>x[i].ch>>x[i].b;
s="";
for (t=i=1,s+=x[t].ch;i<=m;i++) {
if (x[t].b==x[i].a) {
s+=x[i].ch;
t=i;
i=1;
}
}
for (t=i=1;i<=m;i++) {
if (x[t].a==x[i].b) {
ss=x[i].ch;
s.insert(0,ss);
t=i;
i=1;
}
}
cout<<s<<endl;
}
} | [
"m80126colin@gmail.com"
] | m80126colin@gmail.com |
2086888d292070d2cc23f4a3a3fc3ec9e8ba2868 | ba0677235d7688a8594da68c1fb784e8862ebaf6 | /UVa/DP/UVa-108.cpp | 35aceabebdedf32f85bcc679ccb6c9e2bb08ecfc | [] | no_license | sauravchandra1/Competitive-Programming | 1a7a5de9b976f6abe3f162d7765d8882322efeb0 | 4f10ea68abff1280c64a7b77edf95b2b389c9f00 | refs/heads/master | 2021-04-26T23:03:28.436706 | 2020-03-25T20:05:07 | 2020-03-25T20:05:07 | 123,922,852 | 1 | 12 | null | 2019-10-26T11:19:42 | 2018-03-05T13:23:21 | C++ | UTF-8 | C++ | false | false | 1,028 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll mod = int(1e9) + 7;
const int siz = 110;
#define eb emplace_back
#define mp make_pair
#define OPEN 0
int N, matrix[siz][siz], sum[siz][siz], max_sum, ans;
int main() {
if(int(OPEN))
freopen("input.txt", "r", stdin);
scanf("%d", &N);
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
scanf("%d", &matrix[i][j]);
for(int i = 0; i < N; i++)
for(int j = 1; j <= N; j++)
sum[i][j] = sum[i][j - 1] + matrix[i][j - 1];
ans = matrix[0][0];
for(int mat_siz = 1; mat_siz <= N; mat_siz++) {
for(int j = mat_siz; j <= N; j++) {
max_sum = sum[0][j] - sum[0][j - mat_siz];
for(int i = 1; i < N; i++) {
max_sum = max(sum[i][j] - sum[i][j - mat_siz], max_sum + sum[i][j] - sum[i][j - mat_siz]);
ans = max(ans, max_sum);
}
}
}
printf("%d\n", ans);
return 0;
}
| [
"sauravchandra125@gmail.com"
] | sauravchandra125@gmail.com |
24d4c54bcc943377f8f0d9e38282ef6a35cad347 | 61750b7a7bfc2c480764fad2ca419268d65c7e54 | /Engine/Game/GameObjectManager.h | 95140d4ba89f5e5df04429fbe4f0021f76c7d321 | [] | no_license | Dokest/LorwenEngine_Old | 0db818fd459cabdaf6d8d4c19f73a4940ed9fa40 | 113dddc895d8ddb3eeb3c6c82b772f7307046315 | refs/heads/master | 2021-09-27T16:04:23.410067 | 2018-11-09T11:36:45 | 2018-11-09T11:36:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,100 | h | #pragma once
#include <string>
#include <functional>
#include <vector>
#include <map>
#include <array>
#include <typeinfo>
#include "Object.h"
#include "GameObject.h"
#include "MemoryManager.h"
#include "BaseLevel.h"
#include "Graphics/LRenderableComponent.h"
#define MAX_GAME_OBJECTS 1000
template<typename T>
struct ObjectRegistration
{
unsigned int ClassID;
std::vector<T> m_InstancedObjects;
};
template<typename T>
struct SGameObjectHandle
{
unsigned int HandleID;
std::vector<T> ArrayInstance;
SGameObjectHandle() {}
};
class GameObjectManager
{
private:
public:
static GameObjectManager* Singleton_ObjectManager;
unsigned int m_ObjectCounter;
public:
GameObjectManager()
{
Singleton_ObjectManager = this;
}
void Remove(unsigned int objectID);
template<class T>
static std::vector<T> m_Objects;
template<class T>
static T* RegisterGameObjectTest()
{
if (m_Objects<T>.size() == 0)
{
/* m_Objects<T> = std::map<unsigned int, T>();*/
m_Objects<T>.push_back(T());
return &m_Objects<T>[0];
}
m_Objects<T>.push_back(T());
T* newObject = &m_Objects<T>[m_Objects<T>.size() - 1];
newObject->_Create();
return newObject;
}
std::vector<class Object*> m_ObjectManager;
std::vector<class GameObject*> m_GameObjectManager;
template<typename T>
static T* RegisterGameObject(const char* Name)
{
T* newObject = new T();
Singleton_ObjectManager->m_ObjectManager.push_back(newObject);
GameObject* temp = (GameObject*)newObject;
temp->_Create();
Singleton_ObjectManager->m_GameObjectManager.push_back(temp);
return newObject;
}
template<typename T>
static T* RegisterComponent(class GameObject* owner)
{
T* newComponent = new T();
newComponent->Owner = owner;
Singleton_ObjectManager->m_ObjectManager.push_back(newComponent);
GameObject* temp = (GameObject*)newComponent;
temp->_Create();
if (LRenderableComponent* rendComp = dynamic_cast<LRenderableComponent*>(newComponent))
{
BaseLevel::CurrentLevel->SubmitNextFrame(rendComp);
}
return newComponent;
}
void Update(float deltaTime);
};
| [
"35165785+SosoVG@users.noreply.github.com"
] | 35165785+SosoVG@users.noreply.github.com |
8159e8d06198ffa93718a58e6d6f2f05dc574b49 | 5b9a1720d88be1ba9b18a0adb2d0ac2bd76c5e42 | /Tugas Online/Tugas Online 5/Coba G.cpp | 787c9b38313006e67dea2138ba864f5af128f7f8 | [] | no_license | asianjack19/Cpp | 7affaa765c5e5b246e21e4b9df239334362ca470 | acc2cac32921fff56c8d76a43d18ba740a9ed26f | refs/heads/master | 2023-08-14T15:33:29.487550 | 2021-09-18T10:58:27 | 2021-09-18T10:58:27 | 378,959,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 311 | cpp | #include <stdio.h>
int main()
{
int T;
scanf("%d", &T);
int a;
scanf("%d", &a);
char x1[100];
char x2[100];
scanf("%s %s", &x1, &x2);
int t;
scanf("%d", &t);
char y1[100];
char y2[100];
scanf("%s %s", &y1, &y2);
printf("Case #1: YES\nCase #2: NO\n");
}
| [
"michaeladriel080801@gmail.com"
] | michaeladriel080801@gmail.com |
411e5ca93f091545dc06b954b4193d9bf7b41c2f | 2ead209b23a5b4d12779fd65013bd371dccbe95e | /aveditor/src/main/cpp/video/IEGL.h | b70cf3848b6cba7d55c5badcde8f411e7982398c | [] | no_license | songfang/AVEditor | c81262d0ba7a2b07cb04351b77d03f80a5eac220 | 74a7c85e25389ad20dfac9f53c7dfd13a645e314 | refs/heads/master | 2023-06-15T12:47:15.923244 | 2020-10-12T10:18:57 | 2020-10-12T10:18:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | h | //
// Created by 阳坤 on 2020-05-23.
//
#ifndef IAVEDIT_IEGL_H
#define IAVEDIT_IEGL_H
class IEGL {
public:
virtual bool init(void *win) = 0;
virtual void close() = 0;
virtual void draw() = 0;
protected:
IEGL() {}
};
#endif //IAVEDIT_IEGL_H
| [
"yang1001yk@gmail.com"
] | yang1001yk@gmail.com |
5f015ef5cc5a99cdb636baf1ffa4e505f9dd6a33 | a394c2cf4dcdccf632cd35bd739712988cb406d6 | /src/TotobotFace.cpp | 63a2669cfdbc50d2fd7095aee7945a7073a6df51 | [] | no_license | vitkud/Totobot | 7afd5338296ebc04e3e9f5e7241f2769ec237563 | 282da3ba7fc420ca8a4f885c208e8c39015d819f | refs/heads/master | 2020-04-25T06:57:37.544995 | 2019-07-14T07:11:26 | 2019-07-14T07:11:26 | 172,598,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,498 | cpp | /*
Used effects from https://github.com/AlexGyver/GyverMatrixBT/
*/
#include "TotobotFace.h"
#include "Totobot.h"
#include "TotobotTinyFont.h"
#include "FastLED.h"
CRGB leds[EYE_TOTAL_LEDS];
volatile bool eyeLoadingFlag[2];
volatile short eyeEffects[2];
#define _WIDTH EYE_WIDTH
#define THIS_X x
#define THIS_Y (EYE_HEIGHT - y - 1)
//#define THIS_X (EYE_WIDTH - x - 1)
//#define THIS_Y y
void TotobotFace::init() {
FastLED.addLeds<WS2812, EYE_PIN, GRB>(leds, EYE_TOTAL_LEDS);
FastLED.setBrightness(EYE_BRIGHTNESS);
if (EYE_CURRENT_LIMIT > 0) FastLED.setMaxPowerInVoltsAndMilliamps(5, EYE_CURRENT_LIMIT);
FastLED.clear();
FastLED.show();
}
void TotobotFace::loop() {
bool needRefresh = false;
for (int i = 0; i < EYE_COUNT; ++i) {
needRefresh = needRefresh || eyeEffects[i] != 0 || eyeLoadingFlag[i];
updateEffect(i, eyeEffects[i], eyeLoadingFlag[i]);
eyeLoadingFlag[i] = false;
}
if (needRefresh)
FastLED.show();
}
void TotobotFace::setEyeEffect(byte eye, short effect) {
eye = eye % EYE_COUNT;
eyeEffects[eye] = effect;
eyeLoadingFlag[eye] = true;
}
uint16_t getPixelNumber(byte eye, int8_t x, int8_t y) {
if (THIS_Y % 2 == 0) {
return (THIS_Y * _WIDTH + THIS_X) + EYE_LEDS * eye;
} else {
return (THIS_Y * _WIDTH + _WIDTH - THIS_X - 1) + EYE_LEDS * eye;
}
}
void drawPixelXY(byte eye, int8_t x, int8_t y, CRGB color) {
if (x < 0 || x >= EYE_WIDTH || y < 0 || y >= EYE_HEIGHT)
return;
leds[getPixelNumber(eye, x, y)] = color;
}
uint32_t getPixColor(int pixelNumber) {
if (pixelNumber < 0 || pixelNumber >= EYE_TOTAL_LEDS)
return 0;
return (((uint32_t)leds[pixelNumber].r << 16) |
((long)leds[pixelNumber].g << 8) |
(long)leds[pixelNumber].b); // XXX uint32_t, long, long
}
uint32_t getPixColorXY(byte eye, int8_t x, int8_t y) {
return getPixColor(getPixelNumber(eye, x, y));
}
void noneRoutine(byte eye, boolean loadingFlag) {
if (loadingFlag) {
for (int i = eye; i < EYE_LEDS; ++i)
leds[i + EYE_LEDS * eye] = 0;
}
}
void snowRoutine(byte eye, boolean loadingFlag) {
for (byte x = 0; x < EYE_WIDTH; x++) {
for (byte y = 0; y < EYE_HEIGHT - 1; y++) {
drawPixelXY(eye, x, y, getPixColorXY(eye, x, y + 1));
}
}
for (byte x = 0; x < EYE_WIDTH; x++) {
if (getPixColorXY(eye, x, EYE_HEIGHT - 2) == 0 && (random(0, EYE_SNOW_DENSE) == 0))
drawPixelXY(eye, x, EYE_HEIGHT - 1, 0xE0FFFF - 0x101010 * random(0, 4));
else
drawPixelXY(eye, x, EYE_HEIGHT - 1, 0x000000);
}
}
void testRoutine(byte eye, boolean loadingFlag) {
static int x = 0;
static int y = 0;
drawPixelXY(eye, x, y, 0x000000);
if (++x == EYE_WIDTH) {
x = 0;
if (++y == EYE_HEIGHT)
y = 0;
}
drawPixelXY(eye, x, y, 0x00FF00);
}
void matrixRoutine(byte eye, boolean loadingFlag) {
if (loadingFlag)
noneRoutine(eye, loadingFlag);
for (byte x = 0; x < EYE_WIDTH; x++) {
uint32_t thisColor = getPixColorXY(eye, x, EYE_HEIGHT - 1);
if (thisColor == 0)
drawPixelXY(eye, x, EYE_HEIGHT - 1, 0x00FF00 * (random(0, 10) == 0));
else if (thisColor < 0x002000)
drawPixelXY(eye, x, EYE_HEIGHT - 1, 0);
else
drawPixelXY(eye, x, EYE_HEIGHT - 1, thisColor - 0x002000);
}
for (byte x = 0; x < EYE_WIDTH; x++) {
for (byte y = 0; y < EYE_HEIGHT - 1; y++) {
drawPixelXY(eye, x, y, getPixColorXY(eye, x, y + 1));
}
}
}
void TotobotFace::updateEffect(byte eye, short effect, boolean loadingFlag) {
switch (effect) {
case 0: noneRoutine(eye, loadingFlag); break;
case 2: snowRoutine(eye, loadingFlag); break;
case 7: matrixRoutine(eye, loadingFlag); break;
default: testRoutine(eye, loadingFlag); break;
}
}
void TotobotFace::showImage(byte *bytes, byte size, byte x, byte y) {
//drawPixelXY(0, 2, 2, )
for (int i = 0; i < size / 2; ++i) {
for (int j = 0; j < 4; ++j) {
int d = bytes[i * 2] >> j * 2 & 1;
int r = bytes[i * 2] >> j * 2 + 1 & 1;
int g = bytes[i * 2 + 1] >> j * 2 + 1 & 1;
int b = bytes[i * 2 + 1] >> j * 2 & 1;
drawPixelXY((x + i) / 4, (x + i) % 4, y + j, (d + r + g + b) * 40);
// drawPixelXY((x + i) / 4, (x + i) % 4, y + j, (r * 0x7f0000 + g * 0x007f00 + b * 0x00007f) * (d + 1));
}
}
FastLED.show();
}
const int separatorWidth = 1;
const int displayWidth = EYE_WIDTH + separatorWidth + EYE_WIDTH;
const int displayHeight = EYE_HEIGHT;
// const int fontWidth = 4;
// const int fontHeight = 4;
const int charWidth = 5;
void setPixel(byte x, byte y, CRGB color) {
if (x < EYE_WIDTH) {
drawPixelXY(0, x, 3 - y, color);
} else if (x >= EYE_WIDTH + separatorWidth) {
drawPixelXY(1, x - (EYE_WIDTH + separatorWidth), 3 - y, color);
}
}
bool getBit(byte byteData, byte bitNumber) {
return (byteData >> bitNumber) & 1;
}
void TotobotFace::showString(const char *str, int8_t x, int8_t y) {
int strLen = strlen(str);
int curChar = -1;
byte charData[4];
for (int cx = 0; cx < displayWidth; ++cx) {
if (cx < x || cx >= x + strLen * charWidth) {
curChar = -1;
} else {
byte c = str[(cx - x) / charWidth];
if (c != curChar) {
for (int i = 0; i < sizeof charData / sizeof *charData; ++i) {
charData[i] = pgm_read_byte(&font4x4[(c / 2) * 4 + i]) >> (c % 2 == 0 ? 4 : 0);
}
curChar = c;
}
}
for (int cy = 0; cy < displayHeight; ++cy) {
if (curChar == -1 || cy < y || cy >= y + 4) {
setPixel(cx, cy, 0x000000);
} else {
byte bit = (cx - x) % charWidth;
if (bit > 3)
setPixel(cx, cy, 0x000000);
else
setPixel(cx, cy, getBit(charData[cy - y], 3 - bit) ? 0x00ff00 : 0x000000);
}
}
}
FastLED.show();
}
| [
"vitkud@gmail.com"
] | vitkud@gmail.com |
d67febe6e110cb085ce87506054c6975ac800b38 | 5b7f5229df3e1f61eb264df8aa9c67fbcccb6ba0 | /cocos2d/cocos/3d/CCAnimation3D.cpp | c873aeb227c0afbdc0246ad314698ef47dc6e62e | [
"MIT"
] | permissive | IoriKobayashi/BluetoothChecker | cac73371b264522210b181b13e6a9ea555e9f4e8 | fb0127d756a2794be89e5a98b031109cdabfc977 | refs/heads/main | 2023-03-29T21:16:08.104908 | 2021-04-06T13:19:22 | 2021-04-06T13:19:22 | 354,246,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,647 | cpp | /****************************************************************************
Copyright (c) 2014-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
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 "3d/CCAnimation3D.h"
#include "3d/CCBundle3D.h"
#include "platform/CCFileUtils.h"
NS_CC_BEGIN
Animation3D* Animation3D::create(const std::string& fileName, const std::string& animationName)
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName);
std::string key = fullPath + "#" + animationName;
auto animation = Animation3DCache::getInstance()->getAnimation(key);
if (animation != nullptr)
return animation;
animation = new (std::nothrow) Animation3D();
if(animation->initWithFile(fileName, animationName))
{
animation->autorelease();
}
else
{
CC_SAFE_DELETE(animation);
}
return animation;
}
bool Animation3D::initWithFile(const std::string& filename, const std::string& animationName)
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
//load animation here
auto bundle = Bundle3D::createBundle();
Animation3DData animationdata;
if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata))
{
std::string key = fullPath + "#" + animationName;
Animation3DCache::getInstance()->addAnimation(key, this);
Bundle3D::destroyBundle(bundle);
return true;
}
Bundle3D::destroyBundle(bundle);
return false;
}
Animation3D::Curve* Animation3D::getBoneCurveByName(const std::string& name) const
{
auto it = _boneCurves.find(name);
if (it != _boneCurves.end())
return it->second;
return nullptr;
}
Animation3D::Animation3D()
: _duration(0)
{
}
Animation3D::~Animation3D()
{
for (const auto& itor : _boneCurves) {
Curve* curve = itor.second;
CC_SAFE_DELETE(curve);
}
}
Animation3D::Curve::Curve()
: translateCurve(nullptr)
, rotCurve(nullptr)
, scaleCurve(nullptr)
{
}
Animation3D::Curve::~Curve()
{
CC_SAFE_RELEASE_NULL(translateCurve);
CC_SAFE_RELEASE_NULL(rotCurve);
CC_SAFE_RELEASE_NULL(scaleCurve);
}
bool Animation3D::init(const Animation3DData &data)
{
_duration = data._totalTime;
for(const auto& iter : data._translationKeys)
{
Curve* curve = _boneCurves[iter.first];
if( curve == nullptr)
{
curve = new (std::nothrow) Curve();
_boneCurves[iter.first] = curve;
}
if(iter.second.size() == 0) continue;
std::vector<float> keys;
std::vector<float> values;
for(const auto& keyIter : iter.second)
{
keys.push_back(keyIter._time);
values.push_back(keyIter._key.x);
values.push_back(keyIter._key.y);
values.push_back(keyIter._key.z);
}
curve->translateCurve = Curve::AnimationCurveVec3::create(&keys[0], &values[0], (int)keys.size());
if(curve->translateCurve) curve->translateCurve->retain();
}
for(const auto& iter : data._rotationKeys)
{
Curve* curve = _boneCurves[iter.first];
if( curve == nullptr)
{
curve = new (std::nothrow) Curve();
_boneCurves[iter.first] = curve;
}
if(iter.second.size() == 0) continue;
std::vector<float> keys;
std::vector<float> values;
for(const auto& keyIter : iter.second)
{
keys.push_back(keyIter._time);
values.push_back(keyIter._key.x);
values.push_back(keyIter._key.y);
values.push_back(keyIter._key.z);
values.push_back(keyIter._key.w);
}
curve->rotCurve = Curve::AnimationCurveQuat::create(&keys[0], &values[0], (int)keys.size());
if(curve->rotCurve) curve->rotCurve->retain();
}
for(const auto& iter : data._scaleKeys)
{
Curve* curve = _boneCurves[iter.first];
if( curve == nullptr)
{
curve = new (std::nothrow) Curve();
_boneCurves[iter.first] = curve;
}
if(iter.second.size() == 0) continue;
std::vector<float> keys;
std::vector<float> values;
for(const auto& keyIter : iter.second)
{
keys.push_back(keyIter._time);
values.push_back(keyIter._key.x);
values.push_back(keyIter._key.y);
values.push_back(keyIter._key.z);
}
curve->scaleCurve = Curve::AnimationCurveVec3::create(&keys[0], &values[0], (int)keys.size());
if(curve->scaleCurve) curve->scaleCurve->retain();
}
return true;
}
////////////////////////////////////////////////////////////////
Animation3DCache* Animation3DCache::_cacheInstance = nullptr;
Animation3DCache* Animation3DCache::getInstance()
{
if (_cacheInstance == nullptr)
_cacheInstance = new (std::nothrow) Animation3DCache();
return _cacheInstance;
}
void Animation3DCache::destroyInstance()
{
CC_SAFE_DELETE(_cacheInstance);
}
Animation3D* Animation3DCache::getAnimation(const std::string& key)
{
auto it = _animations.find(key);
if (it != _animations.end())
return it->second;
return nullptr;
}
void Animation3DCache::addAnimation(const std::string& key, Animation3D* animation)
{
const auto& it = _animations.find(key);
if (it != _animations.end())
{
return; // already have this key
}
_animations[key] = animation;
animation->retain();
}
void Animation3DCache::removeAllAnimations()
{
for (auto itor : _animations) {
CC_SAFE_RELEASE(itor.second);
}
_animations.clear();
}
void Animation3DCache::removeUnusedAnimation()
{
for (auto itor = _animations.begin(); itor != _animations.end(); ) {
if (itor->second->getReferenceCount() == 1)
{
itor->second->release();
itor = _animations.erase(itor);
}
else
++itor;
}
}
Animation3DCache::Animation3DCache()
{
}
Animation3DCache::~Animation3DCache()
{
removeAllAnimations();
}
NS_CC_END
| [
"iori.kobayashi.mail@gmail.com"
] | iori.kobayashi.mail@gmail.com |
28987ad11ee66bb5bce1085e6513161398f13ddf | 38c10c01007624cd2056884f25e0d6ab85442194 | /chrome/browser/supervised_user/supervised_user_settings_service_unittest.cc | b67f7fa7c3efedc146e88e453006095377edee3f | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 11,278 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/callback.h"
#include "base/json/json_reader.h"
#include "base/prefs/testing_pref_store.h"
#include "base/strings/string_util.h"
#include "chrome/browser/supervised_user/supervised_user_settings_service.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "sync/api/fake_sync_change_processor.h"
#include "sync/api/sync_change.h"
#include "sync/api/sync_change_processor_wrapper_for_test.h"
#include "sync/api/sync_error_factory_mock.h"
#include "sync/protocol/sync.pb.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class MockSyncErrorFactory : public syncer::SyncErrorFactory {
public:
explicit MockSyncErrorFactory(syncer::ModelType type);
~MockSyncErrorFactory() override;
// SyncErrorFactory implementation:
syncer::SyncError CreateAndUploadError(
const tracked_objects::Location& location,
const std::string& message) override;
private:
syncer::ModelType type_;
DISALLOW_COPY_AND_ASSIGN(MockSyncErrorFactory);
};
MockSyncErrorFactory::MockSyncErrorFactory(syncer::ModelType type)
: type_(type) {}
MockSyncErrorFactory::~MockSyncErrorFactory() {}
syncer::SyncError MockSyncErrorFactory::CreateAndUploadError(
const tracked_objects::Location& location,
const std::string& message) {
return syncer::SyncError(location,
syncer::SyncError::DATATYPE_ERROR,
message,
type_);
}
} // namespace
const char kAtomicItemName[] = "X-Wombat";
const char kSettingsName[] = "TestingSetting";
const char kSettingsValue[] = "SettingsValue";
const char kSplitItemName[] = "X-SuperMoosePowers";
class SupervisedUserSettingsServiceTest : public ::testing::Test {
protected:
SupervisedUserSettingsServiceTest() : settings_service_(nullptr) {}
~SupervisedUserSettingsServiceTest() override {}
scoped_ptr<syncer::SyncChangeProcessor> CreateSyncProcessor() {
sync_processor_.reset(new syncer::FakeSyncChangeProcessor);
return scoped_ptr<syncer::SyncChangeProcessor>(
new syncer::SyncChangeProcessorWrapperForTest(sync_processor_.get()));
}
void StartSyncing(const syncer::SyncDataList& initial_sync_data) {
scoped_ptr<syncer::SyncErrorFactory> error_handler(
new MockSyncErrorFactory(syncer::SUPERVISED_USER_SETTINGS));
syncer::SyncMergeResult result = settings_service_.MergeDataAndStartSyncing(
syncer::SUPERVISED_USER_SETTINGS,
initial_sync_data,
CreateSyncProcessor(),
error_handler.Pass());
EXPECT_FALSE(result.error().IsSet());
}
void UploadSplitItem(const std::string& key, const std::string& value) {
split_items_.SetStringWithoutPathExpansion(key, value);
settings_service_.UploadItem(
SupervisedUserSettingsService::MakeSplitSettingKey(kSplitItemName,
key),
scoped_ptr<base::Value>(new base::StringValue(value)));
}
void UploadAtomicItem(const std::string& value) {
atomic_setting_value_.reset(new base::StringValue(value));
settings_service_.UploadItem(
kAtomicItemName,
scoped_ptr<base::Value>(new base::StringValue(value)));
}
void VerifySyncDataItem(syncer::SyncData sync_data) {
const sync_pb::ManagedUserSettingSpecifics& supervised_user_setting =
sync_data.GetSpecifics().managed_user_setting();
base::Value* expected_value = NULL;
if (supervised_user_setting.name() == kAtomicItemName) {
expected_value = atomic_setting_value_.get();
} else {
EXPECT_TRUE(base::StartsWith(supervised_user_setting.name(),
std::string(kSplitItemName) + ':',
base::CompareCase::SENSITIVE));
std::string key =
supervised_user_setting.name().substr(strlen(kSplitItemName) + 1);
EXPECT_TRUE(split_items_.GetWithoutPathExpansion(key, &expected_value));
}
scoped_ptr<base::Value> value =
base::JSONReader::Read(supervised_user_setting.value());
EXPECT_TRUE(expected_value->Equals(value.get()));
}
void OnNewSettingsAvailable(const base::DictionaryValue* settings) {
if (!settings)
settings_.reset();
else
settings_.reset(settings->DeepCopy());
}
// testing::Test overrides:
void SetUp() override {
TestingPrefStore* pref_store = new TestingPrefStore;
settings_service_.Init(pref_store);
user_settings_subscription_ = settings_service_.Subscribe(
base::Bind(&SupervisedUserSettingsServiceTest::OnNewSettingsAvailable,
base::Unretained(this)));
pref_store->SetInitializationCompleted();
ASSERT_FALSE(settings_);
settings_service_.SetActive(true);
ASSERT_TRUE(settings_);
}
void TearDown() override { settings_service_.Shutdown(); }
content::TestBrowserThreadBundle thread_bundle_;
base::DictionaryValue split_items_;
scoped_ptr<base::Value> atomic_setting_value_;
SupervisedUserSettingsService settings_service_;
scoped_ptr<base::DictionaryValue> settings_;
scoped_ptr<base::CallbackList<void(
const base::DictionaryValue*)>::Subscription> user_settings_subscription_;
scoped_ptr<syncer::FakeSyncChangeProcessor> sync_processor_;
};
TEST_F(SupervisedUserSettingsServiceTest, ProcessAtomicSetting) {
StartSyncing(syncer::SyncDataList());
ASSERT_TRUE(settings_);
const base::Value* value = NULL;
EXPECT_FALSE(settings_->GetWithoutPathExpansion(kSettingsName, &value));
settings_.reset();
syncer::SyncData data =
SupervisedUserSettingsService::CreateSyncDataForSetting(
kSettingsName, base::StringValue(kSettingsValue));
syncer::SyncChangeList change_list;
change_list.push_back(
syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_ADD, data));
syncer::SyncError error =
settings_service_.ProcessSyncChanges(FROM_HERE, change_list);
EXPECT_FALSE(error.IsSet()) << error.ToString();
ASSERT_TRUE(settings_);
ASSERT_TRUE(settings_->GetWithoutPathExpansion(kSettingsName, &value));
std::string string_value;
EXPECT_TRUE(value->GetAsString(&string_value));
EXPECT_EQ(kSettingsValue, string_value);
}
TEST_F(SupervisedUserSettingsServiceTest, ProcessSplitSetting) {
StartSyncing(syncer::SyncDataList());
ASSERT_TRUE(settings_);
const base::Value* value = NULL;
EXPECT_FALSE(settings_->GetWithoutPathExpansion(kSettingsName, &value));
base::DictionaryValue dict;
dict.SetString("foo", "bar");
dict.SetBoolean("awesomesauce", true);
dict.SetInteger("eaudecologne", 4711);
settings_.reset();
syncer::SyncChangeList change_list;
for (base::DictionaryValue::Iterator it(dict); !it.IsAtEnd(); it.Advance()) {
syncer::SyncData data =
SupervisedUserSettingsService::CreateSyncDataForSetting(
SupervisedUserSettingsService::MakeSplitSettingKey(kSettingsName,
it.key()),
it.value());
change_list.push_back(
syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_ADD, data));
}
syncer::SyncError error =
settings_service_.ProcessSyncChanges(FROM_HERE, change_list);
EXPECT_FALSE(error.IsSet()) << error.ToString();
ASSERT_TRUE(settings_);
ASSERT_TRUE(settings_->GetWithoutPathExpansion(kSettingsName, &value));
const base::DictionaryValue* dict_value = NULL;
ASSERT_TRUE(value->GetAsDictionary(&dict_value));
EXPECT_TRUE(dict_value->Equals(&dict));
}
TEST_F(SupervisedUserSettingsServiceTest, SetLocalSetting) {
const base::Value* value = NULL;
EXPECT_FALSE(settings_->GetWithoutPathExpansion(kSettingsName, &value));
settings_.reset();
settings_service_.SetLocalSetting(
kSettingsName,
scoped_ptr<base::Value>(new base::StringValue(kSettingsValue)));
ASSERT_TRUE(settings_);
ASSERT_TRUE(settings_->GetWithoutPathExpansion(kSettingsName, &value));
std::string string_value;
EXPECT_TRUE(value->GetAsString(&string_value));
EXPECT_EQ(kSettingsValue, string_value);
}
TEST_F(SupervisedUserSettingsServiceTest, UploadItem) {
UploadSplitItem("foo", "bar");
UploadSplitItem("blurp", "baz");
UploadAtomicItem("hurdle");
// Uploading should produce changes when we start syncing.
StartSyncing(syncer::SyncDataList());
ASSERT_EQ(3u, sync_processor_->changes().size());
for (const syncer::SyncChange& sync_change : sync_processor_->changes()) {
ASSERT_TRUE(sync_change.IsValid());
EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_change.change_type());
VerifySyncDataItem(sync_change.sync_data());
}
// It should also show up in local Sync data.
syncer::SyncDataList sync_data =
settings_service_.GetAllSyncData(syncer::SUPERVISED_USER_SETTINGS);
EXPECT_EQ(3u, sync_data.size());
for (const syncer::SyncData& sync_data_item : sync_data)
VerifySyncDataItem(sync_data_item);
// Uploading after we have started syncing should work too.
sync_processor_->changes().clear();
UploadSplitItem("froodle", "narf");
ASSERT_EQ(1u, sync_processor_->changes().size());
syncer::SyncChange change = sync_processor_->changes()[0];
ASSERT_TRUE(change.IsValid());
EXPECT_EQ(syncer::SyncChange::ACTION_ADD, change.change_type());
VerifySyncDataItem(change.sync_data());
sync_data = settings_service_.GetAllSyncData(
syncer::SUPERVISED_USER_SETTINGS);
EXPECT_EQ(4u, sync_data.size());
for (const syncer::SyncData& sync_data_item : sync_data)
VerifySyncDataItem(sync_data_item);
// Uploading an item with a previously seen key should create an UPDATE
// action.
sync_processor_->changes().clear();
UploadSplitItem("blurp", "snarl");
ASSERT_EQ(1u, sync_processor_->changes().size());
change = sync_processor_->changes()[0];
ASSERT_TRUE(change.IsValid());
EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type());
VerifySyncDataItem(change.sync_data());
sync_data = settings_service_.GetAllSyncData(
syncer::SUPERVISED_USER_SETTINGS);
EXPECT_EQ(4u, sync_data.size());
for (const syncer::SyncData& sync_data_item : sync_data)
VerifySyncDataItem(sync_data_item);
sync_processor_->changes().clear();
UploadAtomicItem("fjord");
ASSERT_EQ(1u, sync_processor_->changes().size());
change = sync_processor_->changes()[0];
ASSERT_TRUE(change.IsValid());
EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type());
VerifySyncDataItem(change.sync_data());
sync_data = settings_service_.GetAllSyncData(
syncer::SUPERVISED_USER_SETTINGS);
EXPECT_EQ(4u, sync_data.size());
for (const syncer::SyncData& sync_data_item : sync_data)
VerifySyncDataItem(sync_data_item);
// The uploaded items should not show up as settings.
const base::Value* value = NULL;
EXPECT_FALSE(settings_->GetWithoutPathExpansion(kAtomicItemName, &value));
EXPECT_FALSE(settings_->GetWithoutPathExpansion(kSplitItemName, &value));
// Restarting sync should not create any new changes.
settings_service_.StopSyncing(syncer::SUPERVISED_USER_SETTINGS);
StartSyncing(sync_data);
ASSERT_EQ(0u, sync_processor_->changes().size());
}
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
712205197f084e8d7ef2cd4d77163fff8ba5b26f | b922ee4ecd0a539bd1e04812c58b1547671d5eb5 | /ifc/include/ifc/gui/simulation_gui.h | 280fa07a162b5f266ce0eb1a67a32d29f8833022 | [] | no_license | Jakub-Ciecierski/InfinityCAM | 5723945ed56b8c2b34f353deb0f19c9f03335873 | 4c9240c0af37bc97cb59fa61dc8fd0a873c695e2 | refs/heads/master | 2021-01-12T17:42:59.611772 | 2017-01-07T17:38:04 | 2017-01-07T17:38:04 | 71,628,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,432 | h | #ifndef PROJECT_SIMULATION_GUI_H
#define PROJECT_SIMULATION_GUI_H
#include <ifc/material/material_box.h>
#include <ifc/cutter/cutter_simulation.h>
#include <memory>
class RenderObject;
namespace ifx{
class Scene;
}
namespace ifc {
class SimulationGUI {
public:
SimulationGUI(std::shared_ptr<ifx::Scene> scene,
std::shared_ptr<ifx::RenderObject> plane,
std::shared_ptr<CutterSimulation> simulation);
~SimulationGUI();
void Render();
private:
void SetDefaultParameters();
void RenderMainWindow();
void RenderDebugWindow();
void RenderMenuBar();
void RenderSimulationInfoSection();
void RenderSimulationRequirements();
void RenderSimulationControl();
void RenderSimulationError();
void RenderCutterSection();
void RenderLoadCutter();
void RenderShowTrajectoryCutter();
void RenderMaterialBoxSection();
void RenderMaterialBoxDimensions();
void RenderMaterialBoxPrecision();
void ResetSimulation();
void RenderDebugSection();
void RenderPlane();
void RenderExample();
void RenderCameraInfo();
void RenderPolygonMode();
void RenderErrorWindow();
std::shared_ptr<ifx::Scene> scene_;
MaterialBoxCreateParams material_box_create_params_;
std::shared_ptr<ifx::RenderObject> plane_;
std::shared_ptr<CutterSimulation> simulation_;
};
}
#endif //PROJECT_SIMULATION_GUI_H
| [
"jakub.ciecier@gmail.com"
] | jakub.ciecier@gmail.com |
502da332c7f18c10863f22cea3ed58ddf67360ca | 413c00fbe8a3ca4857498ed2086d66bdebe7cce7 | /cpp/benchmarks/t/pipelines/registration/Registration.cpp | 461fda8da5e4f437293ad0b33bc46de2a6aa6e1d | [
"MIT"
] | permissive | sinead-li/Open3D | 299dc5bc245acad403ff66ee2441a6766c19167c | 76c2baf9debd460900f056a9b51e9a80de9c0e64 | refs/heads/master | 2023-07-03T04:30:30.918533 | 2021-08-01T09:40:23 | 2021-08-01T09:40:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,929 | cpp | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018-2021 www.open3d.org
//
// 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 "open3d/t/pipelines/registration/Registration.h"
#include <benchmark/benchmark.h>
#include "open3d/core/CUDAUtils.h"
#include "open3d/core/nns/NearestNeighborSearch.h"
#include "open3d/t/io/PointCloudIO.h"
#include "open3d/t/pipelines/registration/TransformationEstimation.h"
// Testing parameters:
// Filename for pointcloud registration data.
static const std::string source_pointcloud_filename =
std::string(TEST_DATA_DIR) + "/ICP/cloud_bin_0.pcd";
static const std::string target_pointcloud_filename =
std::string(TEST_DATA_DIR) + "/ICP/cloud_bin_1.pcd";
static const double voxel_downsampling_factor = 0.02;
// ICP ConvergenceCriteria.
static const double relative_fitness = 1e-6;
static const double relative_rmse = 1e-6;
static const int max_iterations = 30;
// NNS parameter.
static const double max_correspondence_distance = 0.05;
// Initial transformation guess for registation.
static const std::vector<float> initial_transform_flat{
0.862, 0.011, -0.507, 0.5, -0.139, 0.967, -0.215, 0.7,
0.487, 0.255, 0.835, -1.4, 0.0, 0.0, 0.0, 1.0};
namespace open3d {
namespace t {
namespace pipelines {
namespace registration {
static std::tuple<geometry::PointCloud, geometry::PointCloud>
LoadTensorPointCloudFromFile(const std::string& source_pointcloud_filename,
const std::string& target_pointcloud_filename,
const double voxel_downsample_factor,
const core::Dtype& dtype,
const core::Device& device) {
geometry::PointCloud source, target;
io::ReadPointCloud(source_pointcloud_filename, source,
{"auto", false, false, true});
io::ReadPointCloud(target_pointcloud_filename, target,
{"auto", false, false, true});
// Eliminates the case of impractical values (including negative).
if (voxel_downsample_factor > 0.001) {
// TODO: Use geometry::PointCloud::VoxelDownSample.
open3d::geometry::PointCloud legacy_s = source.ToLegacyPointCloud();
open3d::geometry::PointCloud legacy_t = target.ToLegacyPointCloud();
legacy_s = *legacy_s.VoxelDownSample(voxel_downsample_factor);
legacy_t = *legacy_t.VoxelDownSample(voxel_downsample_factor);
source = geometry::PointCloud::FromLegacyPointCloud(legacy_s);
target = geometry::PointCloud::FromLegacyPointCloud(legacy_t);
} else {
utility::LogWarning(
" VoxelDownsample: Impractical voxel size [< 0.001], skiping "
"downsampling.");
}
geometry::PointCloud source_device(device), target_device(device);
core::Tensor source_points = source.GetPoints().To(device, dtype);
source_device.SetPoints(source_points);
core::Tensor target_points = target.GetPoints().To(device, dtype);
core::Tensor target_normals = target.GetPointNormals().To(device, dtype);
target_device.SetPoints(target_points);
target_device.SetPointNormals(target_normals);
return std::make_tuple(source_device, target_device);
}
static void BenchmarkRegistrationICP(benchmark::State& state,
const core::Device& device,
const core::Dtype& dtype,
const TransformationEstimationType& type) {
geometry::PointCloud source(device), target(device);
std::tie(source, target) = LoadTensorPointCloudFromFile(
source_pointcloud_filename, target_pointcloud_filename,
voxel_downsampling_factor, dtype, device);
std::shared_ptr<TransformationEstimation> estimation;
if (type == TransformationEstimationType::PointToPlane) {
estimation = std::make_shared<TransformationEstimationPointToPlane>();
} else if (type == TransformationEstimationType::PointToPoint) {
estimation = std::make_shared<TransformationEstimationPointToPoint>();
}
core::Tensor init_trans =
core::Tensor(initial_transform_flat, {4, 4}, core::Float32, device)
.To(dtype);
RegistrationResult reg_result(init_trans);
// Warm up.
reg_result = RegistrationICP(
source, target, max_correspondence_distance, init_trans,
*estimation,
ICPConvergenceCriteria(relative_fitness, relative_rmse,
max_iterations));
for (auto _ : state) {
reg_result = RegistrationICP(
source, target, max_correspondence_distance, init_trans,
*estimation,
ICPConvergenceCriteria(relative_fitness, relative_rmse,
max_iterations));
core::cuda::Synchronize(device);
}
utility::LogDebug(" PointCloud Size: Source: {} Target: {}",
source.GetPoints().GetShape().ToString(),
target.GetPoints().GetShape().ToString());
utility::LogDebug(" Max iterations: {}, Max_correspondence_distance : {}",
max_iterations, max_correspondence_distance);
}
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPlane / CPU32,
core::Device("CPU:0"),
core::Float32,
TransformationEstimationType::PointToPlane)
->Unit(benchmark::kMillisecond);
#ifdef BUILD_CUDA_MODULE
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPlane / CUDA32,
core::Device("CUDA:0"),
core::Float32,
TransformationEstimationType::PointToPlane)
->Unit(benchmark::kMillisecond);
#endif
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPoint / CPU32,
core::Device("CPU:0"),
core::Float32,
TransformationEstimationType::PointToPoint)
->Unit(benchmark::kMillisecond);
#ifdef BUILD_CUDA_MODULE
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPoint / CUDA32,
core::Device("CUDA:0"),
core::Float32,
TransformationEstimationType::PointToPoint)
->Unit(benchmark::kMillisecond);
#endif
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPlane / CPU64,
core::Device("CPU:0"),
core::Float64,
TransformationEstimationType::PointToPlane)
->Unit(benchmark::kMillisecond);
#ifdef BUILD_CUDA_MODULE
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPlane / CUDA64,
core::Device("CUDA:0"),
core::Float64,
TransformationEstimationType::PointToPlane)
->Unit(benchmark::kMillisecond);
#endif
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPoint / CPU64,
core::Device("CPU:0"),
core::Float64,
TransformationEstimationType::PointToPoint)
->Unit(benchmark::kMillisecond);
#ifdef BUILD_CUDA_MODULE
BENCHMARK_CAPTURE(BenchmarkRegistrationICP,
PointToPoint / CUDA64,
core::Device("CUDA:0"),
core::Float64,
TransformationEstimationType::PointToPoint)
->Unit(benchmark::kMillisecond);
#endif
} // namespace registration
} // namespace pipelines
} // namespace t
} // namespace open3d
| [
"noreply@github.com"
] | noreply@github.com |
c75a8c8a29085af37d491e5f01d08eccb3344294 | 6f5962b952bd9c5ca6bbe5fb0704b0ae28c812ee | /cmon/src/cmon_file.h | 1b710cab8d7cc40ec94ecd69a60c3f71d7fc5a41 | [] | no_license | emwhbr/caramon | 75573ff67aa16c1af0868ca6073180f0f84bd1d9 | a2eb782fafc0ada3c1f33ae374d3e3cfa300e57c | refs/heads/master | 2021-01-10T12:35:42.944635 | 2017-03-05T12:29:15 | 2017-03-05T12:29:15 | 49,129,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,974 | h | // ************************************************************************
// * *
// * Copyright (C) 2015 Bonden i Nol (hakanbrolin@hotmail.com) *
// * *
// * This program is free software; you can redistribute it and/or modify *
// * it under the terms of the GNU General Public License as published by *
// * the Free Software Foundation; either version 2 of the License, or *
// * (at your option) any later version. *
// * *
// ************************************************************************
#ifndef __CMON_FILE_H__
#define __CMON_FILE_H__
#include <stdint.h>
#include <string>
using namespace std;
/////////////////////////////////////////////////////////////////////////////
// Definitions of macros
/////////////////////////////////////////////////////////////////////////////
// Flag values
#define CMON_FILE_READONLY 0x01
#define CMON_FILE_WRITEONLY 0x02
/////////////////////////////////////////////////////////////////////////////
// Class support types
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Definition of classes
/////////////////////////////////////////////////////////////////////////////
class cmon_file {
public:
cmon_file(const string pathname);
~cmon_file(void);
unsigned free_disk_space_size(void);
bool exists(void);
void open_file(unsigned flags);
void write_file(const uint8_t *data,
unsigned nbytes);
void read_file(uint8_t *data,
unsigned nbytes,
bool all);
bool is_eof(void);
void close_file(void);
private:
string m_pathname;
int m_fd;
};
#endif // __CMON_FILE_H__
| [
"hakanbrolin@hotmail.com"
] | hakanbrolin@hotmail.com |
d086639543a92f9e44733582513859082a9a884a | d9a2d4dff101af160c0ef5384bab38f28f4ef612 | /projects/j_project_datastructure/list.cpp | c521a74eb009e6c7b07ad4f660f9ec2590202bd3 | [] | no_license | hhool/cmakelist_examples | 5d2536b17269c793d211c34c3ad20447c14faf42 | 86dcb08e3f3080515b87093582620df922a41aca | refs/heads/master | 2023-03-19T11:25:17.952681 | 2020-08-10T02:14:29 | 2020-08-10T02:14:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,732 | cpp | #include "list.h"
namespace linklist
{
void init(LinkList* plist)
{
plist->next = nullptr;
}
void finit(LinkList* plist)
{
LNode* pnext = plist->next;
while (pnext)
{
plist->next = plist->next->next;
delete pnext;
pnext = plist->next;
}
plist->next = nullptr;
}
void insert_head(LinkList* plist, ElementType* d)
{
LNode* pnode = new LNode(d);
pnode->next = plist->next;
plist->next = pnode;
}
void insert_tail(LinkList* plist, ElementType* d)
{
LNode* pnode = new LNode(d);
LNode* last = plist;
while(last->next)
{
last = last->next;
}
last->next = pnode;
}
bool insert(LinkList* plist, int index, ElementType* d)
{
if (index < 0)
return false;
LNode* pnode = plist;
for (int i=0;i<index; i++)
{
if (pnode == nullptr)
return false;
pnode = pnode->next;
}
if (pnode == nullptr)
return false;
LNode* newnode = new LNode(d);
newnode->next = pnode->next;
pnode->next = newnode;
}
void remove_head(LinkList* plist)
{
if (plist->next)
{
LNode* pnext = plist->next;
plist->next = pnext->next;
delete pnext;
}
}
void remove_tail(LinkList* plist)
{
LNode* pprelast = plist->next;
if (pprelast == nullptr)
return;
if (pprelast->next == nullptr)
{
delete (pprelast->next);
pprelast->next = nullptr;
return;
}
while( pprelast->next && pprelast->next->next)
{
pprelast = pprelast->next;
}
delete (pprelast->next);
pprelast->next = nullptr;
}
bool remove(LinkList* plist, int index)
{
if (index < 0)
return false;
LNode* pnode = plist;
for (int i=0;i<index; i++)
{
if (pnode == nullptr)
return false;
pnode = pnode->next;
}
if (pnode == nullptr)
return false;
LNode* rmnode = pnode->next;
pnode->next = pnode->next->next;
delete rmnode;
}
void reverse(LinkList* plist){}
ElementType* get(LinkList* plist, int index)
{
if (index < 0)
return false;
LNode* pnode = plist;
for (int i=0;i<index; i++)
{
if (pnode == nullptr)
return nullptr;
pnode = pnode->next;
}
return pnode->data;
}
ElementType* get(LinkList* plist, ElementType key, int (*comp)(const ElementType& a, const ElementType& b))
{
LNode* pnext = plist->next;
while (pnext)
{
if ( 0 == comp(key, *(pnext->data)))
return pnext->data;
pnext = pnext->next;
}
return nullptr;
}
int length(LinkList* plist)
{
int count = 0;
LNode* pnext = plist->next;
while (pnext)
{
count++;
pnext = pnext->next;
}
return count;
}
bool isEmpty(LinkList* plist)
{
return plist->next == nullptr;
}
void print(LinkList* plist)
{
LNode* pnext = plist->next;
while (pnext)
{
pnext->print();
pnext = pnext->next;
}
printf("\n");
}
}
namespace twowaylinklist
{
void init(TwowayLinkList* plist)
{
plist->pre = plist;
plist->next = plist;
}
void finit(TwowayLinkList* plist)
{
Twoway_LNode* pnext = plist->next;
while (pnext != plist)
{
printf("rm %d->%d(0x%08x->0x%08x)\n", pnext->pre->data ? pnext->pre->data->key : 0, pnext->data ? pnext->data->key : 0, pnext->pre, pnext);
plist->next = pnext->next;
delete pnext;
pnext = plist->next;
}
plist->pre = plist;
plist->next = plist;
// while (!isEmpty(plist))
// {
// remove_head(plist);
// }
}
void _addnode(Twoway_LNode* pfront, Twoway_LNode* pnew)
{
if (pfront->next)
{
pfront->next->pre = pnew;
}
pnew->pre = pfront;
pnew->next = pfront->next;
pfront->next = pnew;
printf("add %d->%d(0x%08x->0x%08x)\n", pfront->data ? pfront->data->key : 0, pnew->data ? pnew->data->key : 0, pfront, pnew);
}
void _rmnode(Twoway_LNode* pdel)
{
printf("rm %d->%d(0x%08x->0x%08x)\n", pdel->pre->data ? pdel->pre->data->key : 0, pdel->data ? pdel->data->key : 0, pdel->pre, pdel);
if (pdel->pre)
{
pdel->pre->next = pdel->next;
}
if (pdel->next)
{
pdel->next->pre = pdel->pre;
}
}
void insert_head(TwowayLinkList* plist, ElementType* d)
{
Twoway_LNode* pnode = new Twoway_LNode(d);
_addnode(plist, pnode);
}
void insert_tail(TwowayLinkList* plist, ElementType* d)
{
Twoway_LNode* pnode = new Twoway_LNode(d);
Twoway_LNode* last = plist;
while(last->next != plist)
{
last = last->next;
}
_addnode(last, pnode);
}
bool insert(TwowayLinkList* plist, int index, ElementType* d)
{
if (index < 0)
return false;
Twoway_LNode* pnode = plist->next;
for (int i=1;i<index; i++)
{
if (pnode == plist)
return false;
pnode = pnode->next;
}
Twoway_LNode* newnode = new Twoway_LNode(d);
_addnode(pnode, newnode);
return true;
}
void remove_head(TwowayLinkList* plist)
{
Twoway_LNode* pnode = plist->next;
if (pnode != plist)
{
_rmnode(pnode);
delete pnode;
}
}
void remove_tail(TwowayLinkList* plist)
{
// Twoway_LNode* pprelast = plist->next;
// if (pprelast == plist)
// return;
// while( pprelast->next != plist)
// {
// pprelast = pprelast->next;
// }
// _rmnode(pprelast);
// delete pprelast;
Twoway_LNode* plast = plist->pre;
if (plast != plist)
{
_rmnode(plast);
delete plast;
}
}
bool remove(TwowayLinkList* plist, int index)
{
if (index < 0)
return false;
Twoway_LNode* pnode = plist->next;
for (int i=1;i<index; i++)
{
if (pnode == plist)
return false;
pnode = pnode->next;
}
if (pnode == plist)
return false;
_rmnode(pnode);
delete pnode;
}
void reverse(TwowayLinkList* plist)
{
Twoway_LNode* pnode = plist->next;
plist->next = plist->pre;
plist->pre = pnode;
while (pnode != plist)
{
Twoway_LNode* pnext = pnode->next;
pnode->next = pnode->pre;
pnode->pre = pnext;
pnode = pnext;
}
}
ElementType* get(TwowayLinkList* plist, int index)
{
if (index < 0)
return nullptr;
Twoway_LNode* pnode = plist->next;
for (int i=1;i<index; i++)
{
if (pnode == plist)
return nullptr;
pnode = pnode->next;
}
return pnode->data;
}
ElementType* get(TwowayLinkList* plist, ElementType key, int (*comp)(const ElementType& a, const ElementType& b))
{
Twoway_LNode* pnext = plist->next;
while (pnext != plist)
{
if ( 0 == comp(key, *(pnext->data)))
return pnext->data;
pnext = pnext->next;
}
return nullptr;
}
int length(TwowayLinkList* plist)
{
int count = 0;
Twoway_LNode* pnext = plist->next;
while (pnext != plist)
{
count++;
pnext = pnext->next;
}
return count;
}
bool isEmpty(TwowayLinkList* plist)
{
return plist->next == plist;
}
void print(TwowayLinkList* plist)
{
Twoway_LNode* pnext = plist->next;
while (pnext != plist)
{
//printf("0x%04x:", pnext);
printf("=>", pnext);
pnext->print();
pnext = pnext->next;
}
printf("\n");
}
void printReverse(TwowayLinkList* plist)
{
Twoway_LNode* ppre = plist->pre;
while (ppre != plist)
{
//printf("0x%04x:", ppre);
printf("<=", ppre);
ppre->print();
ppre = ppre->pre;
}
printf("\n");
}
} | [
"zhangtianren@baijiayun.com"
] | zhangtianren@baijiayun.com |
420153b60d84c1cc4834d79b6c4834f9eeb82f41 | f1dd8ccaf980d38612723f8bb688c913b238be9b | /solid-principles/interface-segregation/src/main/cpp/Point.hpp | 79eb69101e3a77cb4db91153d643aa9e0a1c60e6 | [] | no_license | jcavejr/SoftwareDesignPatterns | 001aff6cb7ea2cf246f336e28ee2db8e8a4602b2 | 462254925bf96589139b648e956262b59f7d0d38 | refs/heads/master | 2020-04-29T09:45:42.411756 | 2019-04-03T21:14:54 | 2019-04-03T21:14:54 | 176,037,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | hpp | #ifndef POINT_H
#define POINT_H
#include "Location.hpp"
#include "Printable.hpp"
class Point : public Location, public Printable {
protected:
double m_xLocation;
double m_yLocation;
public:
Point(double xLocation, double yLocation);
void printInfo();
double getYLocation();
double getXLocation();
void setYLocation(double yLocation);
void setXLocation(double xLocation);
};
#endif | [
"jcavejr@gmail.com"
] | jcavejr@gmail.com |
81a057aa2339c60cb3f07c802a0df4101b5e462d | 346c17a1b3feba55e3c8a0513ae97a4282399c05 | /src/operator/inst_users_op.cpp | eaab9862669ab932e515b856c46458de92e72b34 | [
"LicenseRef-scancode-cecill-b-en"
] | permissive | micmacIGN/micmac | af4ab545c3e1d9c04b4c83ac7e926a3ff7707df6 | 6e5721ddc65cb9b480e53b5914e2e2391d5ae722 | refs/heads/master | 2023-09-01T15:06:30.805394 | 2023-07-25T09:18:43 | 2023-08-30T11:35:30 | 74,707,998 | 603 | 156 | NOASSERTION | 2023-06-19T12:53:13 | 2016-11-24T22:09:54 | C++ | UTF-8 | C++ | false | false | 7,299 | cpp | /*Header-MicMac-eLiSe-25/06/2007
MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation
eLiSe : ELements of an Image Software Environnement
www.micmac.ign.fr
Copyright : Institut Geographique National
Author : Marc Pierrot Deseilligny
Contributors : Gregoire Maillet, Didier Boldo.
[1] M. Pierrot-Deseilligny, N. Paparoditis.
"A multiresolution and optimization-based image matching approach:
An application to surface reconstruction from SPOT5-HRS stereo imagery."
In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space
(With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006.
[2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance
d'images, adapte au contexte geograhique" to appears in
Bulletin d'information de l'Institut Geographique National, 2007.
Francais :
MicMac est un logiciel de mise en correspondance d'image adapte
au contexte de recherche en information geographique. Il s'appuie sur
la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la
licences Cecill-B. Voir en bas de fichier et http://www.cecill.info.
English :
MicMac is an open source software specialized in image matching
for research in geographic information. MicMac is built on the
eLiSe image library. MicMac is governed by the "Cecill-B licence".
See below and http://www.cecill.info.
Header-MicMac-eLiSe-25/06/2007*/
#include "StdAfx.h"
/***************************************************************/
/* */
/* Fnum_Ecart_Circ */
/* */
/***************************************************************/
class Fnum_Ecart_Circ : public Simple_OP_UN<REAL>
{
public :
Fnum_Ecart_Circ(REAL per,int din) :
_per (per),
_tmp ((din>=0) ? (NEW_TAB(din+1,REAL)) : 0)
{}
virtual ~Fnum_Ecart_Circ()
{
if (_tmp)
DELETE_TAB(_tmp);
}
private :
virtual Simple_OP_UN<REAL> * dup_comp(const Arg_Comp_Simple_OP_UN & arg)
{
return new Fnum_Ecart_Circ(_per,arg.dim_in());
}
virtual void calc_buf
(
REAL ** output,
REAL ** input,
INT nb,
const Arg_Comp_Simple_OP_UN &
);
REAL _per;
REAL * _tmp;
};
void Fnum_Ecart_Circ::calc_buf
(
REAL ** output,
REAL ** input,
INT nb,
const Arg_Comp_Simple_OP_UN & arg
)
{
INT din = arg.dim_in();
for (INT i=0; i<nb ; i++)
{
for (INT d=0; d<din ; d++)
_tmp[d] = input[d][i];
elise_sort(_tmp,din);
_tmp[din] = _tmp[0] + _per;
REAL ec_max = _tmp[1]-_tmp[0];
{
for (INT d =0; d<din; d++)
ec_max = ElMax (ec_max,_tmp[d+1]-_tmp[d]);
}
output[0][i] = _per -ec_max;
}
}
Fonc_Num ecart_circ(Fonc_Num f,REAL per)
{
return create_users_oper
(
0,
new Fnum_Ecart_Circ(per,-1),
f,
1
);
}
/***************************************************************/
/* */
/* Fnum_Grad_Bilin */
/* */
/***************************************************************/
class Fnum_Grad_Bilin : public Simple_OP_UN<REAL>
{
public :
Fnum_Grad_Bilin(Im2D_U_INT1 b) : _b (b), _d (b.data()) {}
private :
Im2D_U_INT1 _b;
U_INT1 ** _d;
virtual void calc_buf
(
REAL ** output,
REAL ** input,
INT nb,
const Arg_Comp_Simple_OP_UN &
);
};
void Fnum_Grad_Bilin::calc_buf
(
REAL ** output,
REAL ** input,
INT nb,
const Arg_Comp_Simple_OP_UN & arg
)
{
REAL * x = input[0];
REAL * y = input[1];
REAL * gx = output[0];
REAL * gy = output[1];
Tjs_El_User.ElAssert
(
arg.dim_in() == 2,
EEM0 << "need 2-d Func for grad_bilin"
);
Tjs_El_User.ElAssert
(
values_in_range(x,nb,1.0,_b.tx()-1.0)
&& values_in_range(y,nb,1.0,_b.ty()-1.0),
EEM0 << "Out of range in grad_bilin \n"
);
for (int i=0 ; i<nb ; i++)
{
INT xi,yi;
REAL x0 = x[i];
REAL y0 = y[i];
REAL p_1x = x0 - (xi= (INT) x0);
REAL p_1y = y0 - (yi= (INT) y0);
REAL p_0x = 1.0-p_1x;
REAL p_0y = 1.0-p_1y;
INT v_00 = _d[yi][xi];
INT v_10 = _d[yi][xi+1];
INT v_01 = _d[yi+1][xi];
INT v_11 = _d[yi+1][xi+1];
gx[i] = p_0y * (v_10-v_00) + p_1y * (v_11-v_01);
gy[i] = p_0x * (v_01-v_00) + p_1x * (v_11-v_10);
}
}
Fonc_Num grad_bilin(Fonc_Num f,Im2D_U_INT1 b)
{
return create_users_oper
(
0,
new Fnum_Grad_Bilin(b),
f,
2
);
}
/*Footer-MicMac-eLiSe-25/06/2007
Ce logiciel est un programme informatique servant à la mise en
correspondances d'images pour la reconstruction du relief.
Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
termes.
Footer-MicMac-eLiSe-25/06/2007*/
| [
"deseilligny@users.noreply.github.com"
] | deseilligny@users.noreply.github.com |
94c2d713bb56bda38a369cd832e0fe78b7ca9a10 | d1cee40adee73afdbce5b3582bbe4761b595c4e1 | /back/RtmpLivePushSDK/boost/boost/xpressive/sub_match.hpp | e83b26089b920843d143c3eab9f49c25e5cc45db | [
"BSL-1.0"
] | permissive | RickyJun/live_plugin | de6fb4fa8ef9f76fffd51e2e51262fb63cea44cb | e4472570eac0d9f388ccac6ee513935488d9577e | refs/heads/master | 2023-05-08T01:49:52.951207 | 2021-05-30T14:09:38 | 2021-05-30T14:09:38 | 345,919,594 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,246 | hpp | ///////////////////////////////////////////////////////////////////////////////
/// \file sub_match.hpp
/// Contains the definition of the class template sub_match\<\>
/// and associated helper functions
//
// Copyright 2008 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_XPRESSIVE_SUB_MATCH_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_SUB_MATCH_HPP_EAN_10_04_2005
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <iosfwd>
#include <string>
#include <utility>
#include <iterator>
#include <algorithm>
#include "assert.hpp"
#include "is_same.hpp"
#include "iterator_traits.hpp"
#include "detail_fwd.hpp"
//{{AFX_DOC_COMMENT
///////////////////////////////////////////////////////////////////////////////
// This is a hack to get Doxygen to show the inheritance relation between
// sub_match<T> and std::pair<T,T>.
#ifdef BOOST_XPRESSIVE_DOXYGEN_INVOKED
/// INTERNAL ONLY
namespace std
{
/// INTERNAL ONLY
template<typename, typename> struct pair {};
}
#endif
//}}AFX_DOC_COMMENT
namespace boost { namespace xpressive
{
///////////////////////////////////////////////////////////////////////////////
// sub_match
//
/// \brief Class template sub_match denotes the sequence of characters matched by a particular marked sub-expression.
///
/// When the marked sub-expression denoted by an object of type sub_match\<\> participated in a
/// regular expression match then member matched evaluates to true, and members first and second
/// denote the range of characters [first,second) which formed that match. Otherwise matched is false,
/// and members first and second contained undefined values.
///
/// If an object of type sub_match\<\> represents sub-expression 0 - that is to say the whole match -
/// then member matched is always true, unless a partial match was obtained as a result of the flag
/// match_partial being passed to a regular expression algorithm, in which case member matched is
/// false, and members first and second represent the character range that formed the partial match.
template<typename BidiIter>
struct sub_match
: std::pair<BidiIter, BidiIter>
{
private:
/// INTERNAL ONLY
///
struct dummy { int i_; };
typedef int dummy::*bool_type;
public:
typedef typename iterator_value<BidiIter>::type value_type;
typedef typename iterator_difference<BidiIter>::type difference_type;
typedef typename detail::string_type<value_type>::type string_type;
typedef BidiIter iterator;
sub_match()
: std::pair<BidiIter, BidiIter>()
, matched(false)
{
}
sub_match(BidiIter first, BidiIter second, bool matched_ = false)
: std::pair<BidiIter, BidiIter>(first, second)
, matched(matched_)
{
}
string_type str() const
{
return this->matched ? string_type(this->first, this->second) : string_type();
}
operator string_type() const
{
return this->matched ? string_type(this->first, this->second) : string_type();
}
difference_type length() const
{
return this->matched ? std::distance(this->first, this->second) : 0;
}
operator bool_type() const
{
return this->matched ? &dummy::i_ : 0;
}
bool operator !() const
{
return !this->matched;
}
/// \brief Performs a lexicographic string comparison
/// \param str the string against which to compare
/// \return the results of (*this).str().compare(str)
int compare(string_type const &str) const
{
return this->str().compare(str);
}
/// \overload
///
int compare(sub_match const &sub) const
{
return this->str().compare(sub.str());
}
/// \overload
///
int compare(value_type const *ptr) const
{
return this->str().compare(ptr);
}
/// \brief true if this sub-match participated in the full match.
bool matched;
};
///////////////////////////////////////////////////////////////////////////////
/// \brief insertion operator for sending sub-matches to ostreams
/// \param sout output stream.
/// \param sub sub_match object to be written to the stream.
/// \return sout \<\< sub.str()
template<typename BidiIter, typename Char, typename Traits>
inline std::basic_ostream<Char, Traits> &operator <<
(
std::basic_ostream<Char, Traits> &sout
, sub_match<BidiIter> const &sub
)
{
typedef typename iterator_value<BidiIter>::type char_type;
BOOST_MPL_ASSERT_MSG(
(boost::is_same<Char, char_type>::value)
, CHARACTER_TYPES_OF_STREAM_AND_SUB_MATCH_MUST_MATCH
, (Char, char_type)
);
if(sub.matched)
{
std::ostream_iterator<char_type, Char, Traits> iout(sout);
std::copy(sub.first, sub.second, iout);
}
return sout;
}
// BUGBUG make these more efficient
template<typename BidiIter>
bool operator == (sub_match<BidiIter> const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs.compare(rhs) == 0;
}
template<typename BidiIter>
bool operator != (sub_match<BidiIter> const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs.compare(rhs) != 0;
}
template<typename BidiIter>
bool operator < (sub_match<BidiIter> const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs.compare(rhs) < 0;
}
template<typename BidiIter>
bool operator <= (sub_match<BidiIter> const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs.compare(rhs) <= 0;
}
template<typename BidiIter>
bool operator >= (sub_match<BidiIter> const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs.compare(rhs) >= 0;
}
template<typename BidiIter>
bool operator > (sub_match<BidiIter> const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs.compare(rhs) > 0;
}
template<typename BidiIter>
bool operator == (typename iterator_value<BidiIter>::type const *lhs, sub_match<BidiIter> const &rhs)
{
return lhs == rhs.str();
}
template<typename BidiIter>
bool operator != (typename iterator_value<BidiIter>::type const *lhs, sub_match<BidiIter> const &rhs)
{
return lhs != rhs.str();
}
template<typename BidiIter>
bool operator < (typename iterator_value<BidiIter>::type const *lhs, sub_match<BidiIter> const &rhs)
{
return lhs < rhs.str();
}
template<typename BidiIter>
bool operator > (typename iterator_value<BidiIter>::type const *lhs, sub_match<BidiIter> const &rhs)
{
return lhs> rhs.str();
}
template<typename BidiIter>
bool operator >= (typename iterator_value<BidiIter>::type const *lhs, sub_match<BidiIter> const &rhs)
{
return lhs >= rhs.str();
}
template<typename BidiIter>
bool operator <= (typename iterator_value<BidiIter>::type const *lhs, sub_match<BidiIter> const &rhs)
{
return lhs <= rhs.str();
}
template<typename BidiIter>
bool operator == (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const *rhs)
{
return lhs.str() == rhs;
}
template<typename BidiIter>
bool operator != (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const *rhs)
{
return lhs.str() != rhs;
}
template<typename BidiIter>
bool operator < (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const *rhs)
{
return lhs.str() < rhs;
}
template<typename BidiIter>
bool operator > (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const *rhs)
{
return lhs.str() > rhs;
}
template<typename BidiIter>
bool operator >= (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const *rhs)
{
return lhs.str() >= rhs;
}
template<typename BidiIter>
bool operator <= (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const *rhs)
{
return lhs.str() <= rhs;
}
template<typename BidiIter>
bool operator == (typename iterator_value<BidiIter>::type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs == rhs.str();
}
template<typename BidiIter>
bool operator != (typename iterator_value<BidiIter>::type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs != rhs.str();
}
template<typename BidiIter>
bool operator < (typename iterator_value<BidiIter>::type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs < rhs.str();
}
template<typename BidiIter>
bool operator > (typename iterator_value<BidiIter>::type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs> rhs.str();
}
template<typename BidiIter>
bool operator >= (typename iterator_value<BidiIter>::type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs >= rhs.str();
}
template<typename BidiIter>
bool operator <= (typename iterator_value<BidiIter>::type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs <= rhs.str();
}
template<typename BidiIter>
bool operator == (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const &rhs)
{
return lhs.str() == rhs;
}
template<typename BidiIter>
bool operator != (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const &rhs)
{
return lhs.str() != rhs;
}
template<typename BidiIter>
bool operator < (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const &rhs)
{
return lhs.str() < rhs;
}
template<typename BidiIter>
bool operator > (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const &rhs)
{
return lhs.str() > rhs;
}
template<typename BidiIter>
bool operator >= (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const &rhs)
{
return lhs.str() >= rhs;
}
template<typename BidiIter>
bool operator <= (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const &rhs)
{
return lhs.str() <= rhs;
}
// Operator+ convenience function
template<typename BidiIter>
typename sub_match<BidiIter>::string_type
operator + (sub_match<BidiIter> const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs.str() + rhs.str();
}
template<typename BidiIter>
typename sub_match<BidiIter>::string_type
operator + (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const &rhs)
{
return lhs.str() + rhs;
}
template<typename BidiIter>
typename sub_match<BidiIter>::string_type
operator + (typename iterator_value<BidiIter>::type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs + rhs.str();
}
template<typename BidiIter>
typename sub_match<BidiIter>::string_type
operator + (sub_match<BidiIter> const &lhs, typename iterator_value<BidiIter>::type const *rhs)
{
return lhs.str() + rhs;
}
template<typename BidiIter>
typename sub_match<BidiIter>::string_type
operator + (typename iterator_value<BidiIter>::type const *lhs, sub_match<BidiIter> const &rhs)
{
return lhs + rhs.str();
}
template<typename BidiIter>
typename sub_match<BidiIter>::string_type
operator + (sub_match<BidiIter> const &lhs, typename sub_match<BidiIter>::string_type const &rhs)
{
return lhs.str() + rhs;
}
template<typename BidiIter>
typename sub_match<BidiIter>::string_type
operator + (typename sub_match<BidiIter>::string_type const &lhs, sub_match<BidiIter> const &rhs)
{
return lhs + rhs.str();
}
}} // namespace boost::xpressive
#endif
| [
"wenwenjun@weeget.cn"
] | wenwenjun@weeget.cn |
06774ae200051574cb409a2313e44db5a45a65bc | 5cad8d9664c8316cce7bc57128ca4b378a93998a | /CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/swing/text/html/NullView.h | 2947ee72769b20c635e0fade5ef3407867bfcaa3 | [
"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,128 | h |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __javax_swing_text_html_NullView__
#define __javax_swing_text_html_NullView__
#pragma interface
#include <javax/swing/text/View.h>
#include <gcj/array.h>
extern "Java"
{
namespace java
{
namespace awt
{
class Graphics;
class Shape;
}
}
namespace javax
{
namespace swing
{
namespace text
{
class Element;
class Position$Bias;
namespace html
{
class NullView;
}
}
}
}
}
class javax::swing::text::html::NullView : public ::javax::swing::text::View
{
public:
NullView(::javax::swing::text::Element *);
virtual void paint(::java::awt::Graphics *, ::java::awt::Shape *);
virtual jfloat getPreferredSpan(jint);
virtual ::java::awt::Shape * modelToView(jint, ::java::awt::Shape *, ::javax::swing::text::Position$Bias *);
virtual jint viewToModel(jfloat, jfloat, ::java::awt::Shape *, JArray< ::javax::swing::text::Position$Bias * > *);
static ::java::lang::Class class$;
};
#endif // __javax_swing_text_html_NullView__
| [
"xiangshijian1@huawei.com"
] | xiangshijian1@huawei.com |
0b4a80b2dcc6caba374215198f59d23444eded10 | bf9d7e67c2717653a0272abfa7dcf47691d504d4 | /server_group/server/ServerService.cpp | 4461bd4645859f50d0a4e733cb2d537395e62188 | [] | no_license | yuangu/easyserver | 592de68372a5a4175802ae24595aa27d561b0a06 | 3963e98f2b0c5595b37998f2999af33c7ce2c82a | refs/heads/master | 2020-05-23T10:21:10.578194 | 2014-07-30T13:21:21 | 2014-07-30T13:21:21 | 80,424,529 | 0 | 1 | null | 2017-01-30T13:38:39 | 2017-01-30T13:38:39 | null | GB18030 | C++ | false | false | 6,272 | cpp | #include "ServerHeader.h"
#include "ServerService.h"
#include "TimerForMain.h"
#include "ProtoSvrLogin.pb.h"
#include "protohandler/ProtobufDefine.h"
//const EventType EVT_TestEvent = "TestEvent";
//
//class TestComponent : public Component
//{
//public:
// static const string type;
//
// TestComponent()
// {
// BindGameEvent(EVT_TestEvent, TestComponent::onEventTest);
// }
//
// virtual ~TestComponent(){}
//
// void onEventTest(const GameEvent& evt)
// {
// string event = evt.event;
// event = event;
// LOGE("onEventTest evt=%s", evt.event.c_str());
//
// int hp = atoi(getOwner()->getProperties().getValue("hp"));
// int mp = atoi(getOwner()->getProperties().getValue("mp"));
// LOGE("Prop: hp=%d, mp=%d", hp, mp);
// }
//
//protected:
//private:
//};
//
//const string TestComponent::type = "TestComponent";
//////////////////////////////////////////////////////////////////////////
void execServiceOnInputCmd(ScriptObject* pScript, const string& cmd)
{
// 事件测试
{
//GameObject gameObj;
//gameObj.getProperties().addValue("hp", 100);
//gameObj.getProperties().addValue("mp", 200);
//gameObj.createComponent<TestComponent>();
//gameObj.notify(EVT_TestEvent);
}
//for (int i=0; i<1; i++) {
// ScriptObject* pScript2 = ScriptManager::getInstance().createScript();
// //ScriptManager::getInstance().destroyScript(pScript2);
//}
pScript = ScriptManager::getInstance().createScript();
printf("\n=============== 开始执行脚本 ================\n");
// 先初始化脚本路径搜索
pScript->dofile("package_path.lua");
pScript->dofile("loginserver/main.lua");
ScriptManager::getInstance().printInfo();
printf("\n=============== 结束脚本执行 ================\n");
ScriptManager::getInstance().destroyScript(pScript);
}
//////////////////////////////////////////////////////////////////////////
ServerServiceAsync::ServerServiceAsync()
: NetService("ServerServiceAsync")
{
mLocalPort = 0;
mMaxClient = 0;
}
ServerServiceAsync::~ServerServiceAsync()
{
}
void ServerServiceAsync::onInputCmd(const string& cmd)
{
if (cmd == "i") {
printf("task: %d\n", TCPTaskManager::getInstance().size());
}
// 执行lua函数
FUNC_PF("脚本执行时间");
execServiceOnInputCmd(NULL, cmd);
}
bool ServerServiceAsync::onInitialise()
{
// 初始化minidump
MiniDump::InitMiniDump("./crashlog/", mName.c_str());
// 初始化日志
string strLogFile = strformat("./log/%s/%s", mName.c_str(), mName.c_str());
ServerLogger::getInstance().start(strLogFile.c_str(), "super", true);
loadConfig();
mLocalPort = 7102;
// 开启服务
addTimer(new TimerForMain);
start( getLocalPort() );
updateWindowTitle();
LOGI("开始监听端口 %d", getLocalPort());
return true;
}
void ServerServiceAsync::onShutdown()
{
ServerLogger::getInstance().stop();
}
bool ServerServiceAsync::loadConfig()
{
pugi::xml_document doc;
if (!doc.load_file("./config/config.xml")) {
LOGE("加载config.xml文件失败");
return false;
}
pugi::xml_node node = doc.child("Config").child("Global").child("SuperServer");
mLocalPort = atoi(node.attribute("port").value());
mMaxClient = atoi(node.attribute("maxclient").value());
return true;
}
void ServerServiceAsync::updateWindowTitle()
{
string strTitle = strformat("ServerService %d",getLocalPort());
strTitle = Platform::utf8ToGbk(strTitle);
Platform::setWindowTitle(strTitle.c_str());
}
//////////////////////////////////////////////////////////////////////////
ServerServiceSync::ServerServiceSync()
: NetService("ServerServiceSync")
{
mLocalPort = 0;
mMaxClient = 0;
}
ServerServiceSync::~ServerServiceSync()
{
}
void ServerServiceSync::onInputCmd(const string& cmd)
{
if (cmd == "i") {
printf("task: %d\n", TCPTaskManager::getInstance().size());
}
// 执行lua函数
FUNC_PF("脚本执行时间");
execServiceOnInputCmd(NULL, cmd);
}
bool ServerServiceSync::onInitialise()
{
// 初始化minidump
MiniDump::InitMiniDump("./crashlog/", mName.c_str());
// 初始化日志
string strLogFile = strformat("./log/%s/%s", mName.c_str(), mName.c_str());
ServerLogger::getInstance().start(strLogFile.c_str(), "super", true);
loadConfig();
mLocalPort = 7102;
// 开启服务
addTimer(new TimerForMain);
start( getLocalPort() );
updateWindowTitle();
LOGI("开始监听端口 %d", getLocalPort());
return true;
}
void ServerServiceSync::onShutdown()
{
ServerLogger::getInstance().stop();
}
bool ServerServiceSync::loadConfig()
{
pugi::xml_document doc;
if (!doc.load_file("./config/config.xml")) {
LOGE("加载config.xml文件失败");
return false;
}
pugi::xml_node node = doc.child("Config").child("Global").child("SuperServer");
mLocalPort = atoi(node.attribute("port").value());
mMaxClient = atoi(node.attribute("maxclient").value());
return true;
}
void IterateProtoFile(const std::string& name)
{
// 在 DescriptorPool 中通过 .proto 文件名获取到 FileDescriptor
// FileDescriptor 对象描述了整个 .proto 文件
const google::protobuf::FileDescriptor* fileDescriptor
= google::protobuf::DescriptorPool::generated_pool()->FindFileByName(name);
if (!fileDescriptor)
return;
// 遍历整个 .proto 文件中定义的顶层 message
for (int i=0; i<fileDescriptor->message_type_count(); ++i)
{
// message_type 函数参数取值范围在 0 <= index < message_type_count()
// 索引值 i 对应 message 在 .proto 文件中的定义的顺序
const google::protobuf::Descriptor* descriptor = fileDescriptor->message_type(i);
descriptor = descriptor;
// ...
}
}
void ServerServiceSync::updateWindowTitle()
{
string strTitle = strformat("ServerService %d",getLocalPort());
strTitle = Platform::utf8ToGbk(strTitle);
Platform::setWindowTitle(strTitle.c_str());
//////////////////////////////////////////////////////////////////////////
//google::protobuf::Message* newQuery = createMessage("LoginCmd.RequestRegisterGameServer");
//assert(newQuery != NULL);
//LoginCmd::RequestRegisterGameServer::default_instance();
//LoginCmd::RequestRegisterGameServer cmd;
//LoginCmd::RequestRegisterGameServer* pMsg = (LoginCmd::RequestRegisterGameServer*)createMessage("LoginCmd.RequestRegisterGameServer");
//pMsg->set_id(1);
//IterateProtoFile("ProtoSvrLogin.proto");
}
| [
"crackgame@qq.com"
] | crackgame@qq.com |
5a5e72e025ee45165a8b4e2e251836fef0e5279f | 303e592c312459bf9eb3ce231b1357c4de91124b | /aoj/0084/0084.cpp | 57853f54c728d761be3fa9562a3a5419a97198c4 | [] | no_license | kohyatoh/contests | 866c60a1687f8a59d440da3356c6117f9596e8ce | b3dffeaf15564d57aec5c306f5f84bd448bc791f | refs/heads/master | 2021-01-17T15:06:23.216232 | 2016-07-18T14:06:05 | 2016-07-18T14:06:05 | 2,369,261 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 471 | cpp | #include <stdio.h>
#include <iostream>
#include <sstream>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
int main() {
string s;
getline(cin, s);
rep (i, s.size()) if (s[i] == '.' || s[i] == ',') s[i] = ' ';
istringstream sin(s);
bool f = false;
string w;
while (sin >> w) if (w.size() >= 3 && w.size() <= 6) {
if (f) cout << ' ';
f = true;
cout << w;
}
cout << endl;
return 0;
}
| [
"kohyatoh@yahoo.co.jp"
] | kohyatoh@yahoo.co.jp |
fb16f4629b224ffd4712e91b45c7a077e7423ee8 | 82ff9941c7d16c2be77b91733f2777c1a8d5fdb7 | /head/visionModule/statimg/statimg.cpp | 732698ec7853e27253f644304d03f4f6947f7ce2 | [] | no_license | dimatoys/robopicksel | 97fce007addc08982e21900e5ad28ed9b52e9e1c | b34dbe2a24faa905d9425f551631feb465df9190 | refs/heads/master | 2021-07-07T01:11:24.794026 | 2019-10-24T01:35:51 | 2019-10-24T01:35:51 | 101,575,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,615 | cpp | #include "statimg.h"
#include <math.h>
class TStatImgSegmentsExtractor : public TSegmentsExtractor {
TStatImgExtractorFactory* Parameters;
TMutableImage<unsigned char>* Image;
TMutableImage<short> AnomalyMatrix;
double* A;
int ASize;
double GetPixelAnomaly(int x, int y);
void MakeSmoothing();
void MakeAnomalyMatrix(int& biggestCoreIdx);
double GetAreaAnomaly(int ax, int ay);
void ExtractObjectFromCore(TArea* area, int coreIdx, int& xmin, int& xmax, int& ymin, int& ymax);
void ExtractObjectFromCore2(TArea* area, int coreIdx);
void DetectObjectType(TArea* area, int coreIdx);
void DrawAnomalies1(TMutableRGBImage* image);
void DrawAnomalies2(TMutableRGBImage* image);
void DrawAnomalies3(TMutableRGBImage* image);
public:
TStatImgSegmentsExtractor(TStatImgExtractorFactory* parameters,
TMutableImage<unsigned char>* image) :
AnomalyMatrix(image->Width / parameters->AreaCell, image->Height / parameters-> AreaCell, 1) {
Parameters = parameters;
Image = image;
A = NULL;
}
void ExtractSegments(std::list<TArea>& area);
void DrawDebugInfo(TMutableRGBImage* image);
~TStatImgSegmentsExtractor(){
if (A != NULL) {
delete A;
}
}
};
TSegmentsExtractor* TStatImgExtractorFactory::CreateExtractor(TMutableImage<unsigned char>* image) {
return new TStatImgSegmentsExtractor(this, image);
}
inline double f6(double* a, int x, int y) {
return a[0] + x * (a[1] + x * a[3] + y * a[5]) + y * (a[2] + y * a[4]);
}
double TStatImgSegmentsExtractor::GetPixelAnomaly(int x, int y) {
double* a = A;
int n = Parameters->RegressionMatrix.Depth;
double anomalies = 0;
for (int c = 0; c < Image->Depth; c++) {
double v = Image->Cell(x,y)[c] - f6(a, x, y);
a += n;
anomalies += v * v;
}
return anomalies;
}
double TStatImgSegmentsExtractor::GetAreaAnomaly(int ax, int ay) {
double anomalies = 0;
int areaCell = Parameters-> AreaCell;
for (int yc = 0; yc < areaCell; yc++) {
for (int xc = 0; xc < areaCell; xc++) {
int x = ax * areaCell + xc;
int y = ay * areaCell + yc;
anomalies += GetPixelAnomaly(x, y);
}
}
return anomalies / areaCell / areaCell;
}
void TStatImgSegmentsExtractor::MakeSmoothing() {
int size = Image->Depth * Parameters->RegressionMatrix.Depth;
if (A == NULL) {
ASize = size;
A = new double[ASize];
} else {
if (ASize != size) {
delete A;
ASize = size;
A = new double[ASize];
}
}
int n = Parameters->RegressionMatrix.Depth;
double* rm = Parameters->RegressionMatrix.Cell(0, 0);
double* a = A;
for (int c = 0; c < Image->Depth; c++) {
double* rm_ptr = rm;
for (int k = 0; k < n; k++) {
double v = 0;
for (int y = 0; y < Image->Height; y++) {
for (int x = 0; x < Image->Width; x++) {
v += Image->Cell(x, y)[c] * *rm_ptr++;
}
}
*a++ = v;
}
}
}
void TStatImgSegmentsExtractor::MakeAnomalyMatrix(int& biggestCoreIdx) {
MakeSmoothing();
//double threshold = Parameters->AnomalyThreshold * Parameters->AnomalyThreshold * 65536 * Image->Depth * Parameters-> AreaCell * Parameters-> AreaCell;
double threshold = Parameters->AnomalyThreshold * Parameters->AnomalyThreshold * 65536 * Image->Depth;
short yline[AnomalyMatrix.Width];
memset(yline, 0, AnomalyMatrix.Width * sizeof(short));
biggestCoreIdx = -1;
short biggestCoreSize = Parameters->MinCoreSize - 1;
for(int y0 = 0; y0 < AnomalyMatrix.Height; y0++) {
short xline = 0;
for(int x0 = 0; x0 < AnomalyMatrix.Width; x0++) {
/*
double anomalies = 0;
for (int yc = 0; yc < Parameters-> AreaCell; yc++) {
for (int xc = 0; xc < Parameters-> AreaCell; xc++) {
int x = x0 * Parameters-> AreaCell + xc;
int y = y0 * Parameters-> AreaCell + yc;
anomalies += GetPixelAnomaly(x, y);
}
}
*/
double anomalies = GetAreaAnomaly(x0, y0);
if (anomalies > threshold) {
++xline;
short ylinev = ++yline[x0];
short core = 1;
if ((x0 > 0) && (y0 > 0)) {
core += *AnomalyMatrix.Cell(x0 - 1, y0 - 1);
if (core > xline) {
core = xline;
}
if (core > ylinev) {
core = ylinev;
}
if (core > biggestCoreSize) {
biggestCoreSize = core;
biggestCoreIdx = AnomalyMatrix.Idx(x0, y0);
}
}
*AnomalyMatrix.Cell(x0, y0) = core;
//printf("MakeAnomalyMatrix: (%d,%d) = %d\n", x0, y0, core);
} else {
xline = 0;
yline[x0] = 0;
*AnomalyMatrix.Cell(x0, y0) = 0;
}
}
}
}
void TStatImgSegmentsExtractor::ExtractObjectFromCore(TArea* area, int coreIdx, int& xmin, int& xmax, int& ymin, int& ymax) {
int x0, y0;
AnomalyMatrix.IdxToXY(coreIdx, x0, y0);
short core = *AnomalyMatrix.Cell(coreIdx);
xmax = x0;
ymax = y0;
xmin = xmax - core + 1;
ymin = ymax - core + 1;
int size = core * core;
for (int i = 0; i < core; i++) {
int x, y;
for (x = x0 + 1; x < AnomalyMatrix.Width; ++x) {
if (*AnomalyMatrix.Cell(x, y0 - i) <= 0) {
break;
}
++size;
}
if (x - 1 > xmax) {
xmax = x - 1;
}
for (x = x0 - core ; x >= 0; --x) {
if (*AnomalyMatrix.Cell(x, y0 - i) <= 0) {
break;
}
++size;
}
if (x + 1 < xmin) {
xmin = x + 1;
}
for (y = y0 + 1; y < AnomalyMatrix.Height; ++y) {
if (*AnomalyMatrix.Cell(x0 - i, y) <= 0) {
break;
}
++size;
}
if (y - 1 > ymax) {
ymax = y - 1;
}
for (y = y0 - core; y >= 0; --y) {
if (*AnomalyMatrix.Cell(x0 - i, y) <= 0) {
break;
}
++size;
}
if (y + 1 < ymin) {
ymin = y + 1;
}
}
area->MinX = xmin * Parameters->AreaCell;
area->MinY = ymin * Parameters->AreaCell;
area->MaxX = (xmax + 1) * Parameters->AreaCell;
area->MaxY = (ymax + 1) * Parameters->AreaCell;
area->Size = size * Parameters->AreaCell * Parameters->AreaCell;
area->AtBorder = (xmin == 0 ? BORDER_LEFT : 0) +
(xmax == AnomalyMatrix.Width -1 ? BORDER_RIGHT : 0) +
(ymin == 0 ? BORDER_TOP : 0) +
(ymin == AnomalyMatrix.Height - 1 ? BORDER_BOTTOM : 0);
}
void TStatImgSegmentsExtractor::ExtractObjectFromCore2(TArea* area, int coreIdx) {
int frontier[2][AnomalyMatrix.ImageSize()];
int currentFrontier = 0;
int currentFrontierIdx = 0;
frontier[currentFrontier][currentFrontierIdx++] = coreIdx;
short* ptr = AnomalyMatrix.Cell(coreIdx);
*ptr = -*ptr;
int xmin, xmax, ymin, ymax;
AnomalyMatrix.IdxToXY(coreIdx, xmin, ymin);
xmax = xmin;
ymax = ymin;
int size = 0;
while(currentFrontierIdx > 0) {
int newFrontier = 1 - currentFrontier;
int newFrontierIdx = 0;
size += currentFrontierIdx;
for (int i = 0; i < currentFrontierIdx; ++i) {
int x, y;
AnomalyMatrix.IdxToXY(frontier[currentFrontier][i], x, y);
if (x > 0) {
int newIdx = AnomalyMatrix.Idx(x - 1, y);
ptr = AnomalyMatrix.Cell(newIdx);
if (*ptr > 0) {
*ptr = -*ptr;
frontier[newFrontier][newFrontierIdx++] = newIdx;
if (x - 1 < xmin) {
xmin = x - 1;
}
}
}
if (x + 1 < AnomalyMatrix.Width) {
int newIdx = AnomalyMatrix.Idx(x + 1, y);
ptr = AnomalyMatrix.Cell(newIdx);
if (*ptr > 0) {
*ptr = -*ptr;
frontier[newFrontier][newFrontierIdx++] = newIdx;
if (x + 1 > xmax) {
xmax = x + 1;
}
}
}
if (y > 0) {
int newIdx = AnomalyMatrix.Idx(x, y - 1);
ptr = AnomalyMatrix.Cell(newIdx);
if (*ptr > 0) {
*ptr = -*ptr;
frontier[newFrontier][newFrontierIdx++] = newIdx;
if (y - 1 < ymin) {
ymin = y - 1;
}
}
}
if (y + 1 < AnomalyMatrix.Height) {
int newIdx = AnomalyMatrix.Idx(x, y + 1);
ptr = AnomalyMatrix.Cell(newIdx);
if (*ptr > 0) {
*ptr = -*ptr;
frontier[newFrontier][newFrontierIdx++] = newIdx;
if (y + 1 > ymax) {
ymax = y + 1;
}
}
}
}
currentFrontier = newFrontier;
currentFrontierIdx = newFrontierIdx;
}
area->MinX = xmin * Parameters->AreaCell;
area->MinY = ymin * Parameters->AreaCell;
area->MaxX = (xmax + 1) * Parameters->AreaCell;
area->MaxY = (ymax + 1) * Parameters->AreaCell;
area->Size = size * Parameters->AreaCell * Parameters->AreaCell;
area->AtBorder = (xmin == 0 ? BORDER_LEFT : 0) +
(xmax == AnomalyMatrix.Width -1 ? BORDER_RIGHT : 0) +
(ymin == 0 ? BORDER_TOP : 0) +
(ymin == AnomalyMatrix.Height - 1 ? BORDER_BOTTOM : 0);
}
void TStatImgSegmentsExtractor::DetectObjectType(TArea* area, int coreIdx) {
int x0, y0;
AnomalyMatrix.IdxToXY(coreIdx, x0, y0);
//printf("DetectObjectType: (x,y)=(%d,%d) core=%d area=%d\n", x0, y0, (int)*AnomalyMatrix.Cell(coreIdx), Parameters->AreaCell);
x0 *= Parameters->AreaCell;
y0 *= Parameters->AreaCell;
short coreSize = (*AnomalyMatrix.Cell(coreIdx) - 1) * Parameters->AreaCell;
//printf("DetectObjectType: (X,Y)=(%d,%d) size=%d\n", x0, y0, (int)coreSize);
int redblue = 0;
for (int i = 0; i < coreSize; i++) {
//printf("DetectObjectType: i=%d (x,y) = (%d,%d)\n", i, x0 - i, y0 - i);
unsigned char* cell = Image->Cell(x0 - i, y0 - i);
for (int c = 0; c < Image->Depth; c++) {
redblue += (cell[0] - (int)cell[2]);
}
}
//printf("DetectObjectType: redblue=%d\n", redblue);
area->ObjectType = redblue > 0 ? 1 : 2;
}
/*
void TStatImgSegmentsExtractor::ExtractSegments(std::list<TArea>& areas) {
if (Parameters->RegressionMatrix.ReAllocate(Image->Width, Image->Height, Parameters->RegressionLevel)) {
MakeRegressionMatrix(&Parameters->RegressionMatrix);
}
int biggestCoreIdx = -1;
MakeAnomalyMatrix(biggestCoreIdx);
if (biggestCoreIdx >= Parameters->MinCoreSize) {
int xmin, xmax, ymin, ymax;
printf("ExtractSegments: Core size: %d\n", (int)*AnomalyMatrix.Cell(biggestCoreIdx));
TArea area;
ExtractObjectFromCore(&area, biggestCoreIdx, xmin, xmax, ymin, ymax);
//printf("ExtractSegments: extracted\n");
DetectObjectType(&area, biggestCoreIdx);
//printf("ExtractSegments: detected\n");
areas.push_back(area);
}
}
*/
void TStatImgSegmentsExtractor::ExtractSegments(std::list<TArea>& areas) {
if (Parameters->RegressionMatrix.ReAllocate(Image->Width, Image->Height, Parameters->RegressionLevel)) {
MakeRegressionMatrix(&Parameters->RegressionMatrix);
}
int biggestCoreIdx = -1;
MakeAnomalyMatrix(biggestCoreIdx);
if (biggestCoreIdx >= Parameters->MinCoreSize) {
int size = AnomalyMatrix.ImageSize();
for (int i = size - 1; i >= 0; --i) {
if (*AnomalyMatrix.Cell(i) >= Parameters->MinCoreSize) {
TArea area;
ExtractObjectFromCore2(&area, i);
/*
int xmin, xmax, ymin, ymax;
ExtractObjectFromCore(&area, i, xmin, xmax, ymin, ymax);
for (int y = ymin; y <=ymax; ++y) {
for (int x = xmin; x <= xmax; ++x) {
short* ptr = AnomalyMatrix.Cell(x, y);
*ptr = -abs(*ptr);
}
}
*/
areas.push_back(area);
}
}
}
}
void TStatImgSegmentsExtractor::DrawDebugInfo(TMutableRGBImage* image) {
switch (Mode) {
case 1:
DrawAnomalies1(image);
break;
case 2:
DrawAnomalies2(image);
break;
case 3:
DrawAnomalies3(image);
break;
}
}
void TStatImgSegmentsExtractor::DrawAnomalies1(TMutableRGBImage* image) {
unsigned char colors[][3] = {{ 0xFF, 0xFF, 0xFF},
{ 0xFF, 0xFF, 0x80},
{ 0xFF, 0x80, 0xFF},
{ 0xFF, 0x80, 0x80},
{ 0x80, 0xFF, 0xFF},
{ 0x80, 0xFF, 0x80},
{ 0x80, 0x80, 0xFF},
{ 0x80, 0x80, 0x80},
{ 0xFF, 0xFF, 0x00},
{ 0xFF, 0x00, 0xFF},
{ 0xFF, 0x00, 0xFF},
{ 0xFF, 0x00, 0x00},
{ 0x00, 0xFF, 0xFF},
{ 0x00, 0xFF, 0x00},
{ 0x00, 0x00, 0xFF},
{ 0x00, 0x00, 0x00}};
unsigned char* colorObj = colors[0];
//printf("DebugInfo: w=%d h=%d\n", image->Width, image->Height);
for (int y = 0; y < AnomalyMatrix.Height; y++) {
for (int x =0; x < AnomalyMatrix.Width; x++) {
//printf("(%d,%d) %d\n", x, y, a);
if (*AnomalyMatrix.Cell(x, y) != 0) {
image->DrawPointer(x * Parameters->AreaCell + Parameters->AreaCell / 2, y * Parameters->AreaCell + Parameters->AreaCell / 2, 4, colors[(int)abs(*AnomalyMatrix.Cell(x, y)) % 16]);
}
}
}
}
void TStatImgSegmentsExtractor::DrawAnomalies2(TMutableRGBImage* image) {
/*
double min = 1e10;
double max = 0;
for (int y = 0; y < image->Height; y++) {
for (int x =0; x < image->Width; x++) {
double anomaly = GetPixelAnomaly(x, y);
if (anomaly < min) {
min = anomaly;
}
if (anomaly > max) {
max = anomaly;
}
}
}
printf("anomaly: min=%f max=%f\n", min, max);
*/
const int max = 20000;
const int bars = 50;
const int interval = max / bars;
int histogram[bars];
memset(histogram, 0, bars * sizeof(int));
for (int y = 0; y < image->Height; y++) {
for (int x =0; x < image->Width; x++) {
double anomaly = GetPixelAnomaly(x, y);
int box = (int)(anomaly / interval);
if (box >= bars) {
box = bars - 1;
}
histogram[box]++;
}
}
for (int i = 0 ; i < bars - 1; i++) {
printf("%u-%u: %u\n", i * interval, (i + 1) * interval, histogram[i]);
}
printf("%u-*****: %u\n", (bars - 1) * interval, histogram[bars - 1]);
for (int y = 0; y < image->Height; y++) {
for (int x =0; x < image->Width; x++) {
//unsigned char ar = (unsigned char)(255 * (GetPixelAnomaly(x, y) - min) / (max - min));
//unsigned int ar = (unsigned int)GetPixelAnomaly(x, y) * 255 / 21000;
//if (ar > 255) {
// ar = 255;
//}
unsigned char ar = GetPixelAnomaly(x, y) > 3500 ? 255 : 0;
image->Cell(x, y)[0] = ar;
image->Cell(x, y)[1] = ar;
image->Cell(x, y)[2] = ar;
}
}
}
void TStatImgSegmentsExtractor::DrawAnomalies3(TMutableRGBImage* image) {
unsigned char colors[][3] = {{ 0xFF, 0xFF, 0xFF},
{ 0xFF, 0xFF, 0x80},
{ 0xFF, 0x80, 0xFF},
{ 0xFF, 0x80, 0x80},
{ 0x80, 0xFF, 0xFF},
{ 0x80, 0xFF, 0x80},
{ 0x80, 0x80, 0xFF},
{ 0x80, 0x80, 0x80},
{ 0xFF, 0xFF, 0x00},
{ 0xFF, 0x00, 0xFF},
{ 0xFF, 0x00, 0xFF},
{ 0xFF, 0x00, 0x00},
{ 0x00, 0xFF, 0xFF},
{ 0x00, 0xFF, 0x00},
{ 0x00, 0x00, 0xFF},
{ 0x00, 0x00, 0x00}};
unsigned char* colorObj = colors[0];
//printf("DebugInfo: w=%d h=%d\n", image->Width, image->Height);
for (int y = 0; y < AnomalyMatrix.Height; y++) {
for (int x =0; x < AnomalyMatrix.Width; x++) {
double anomalies = sqrt(GetAreaAnomaly(x, y) / (65536 * Image->Depth));
printf("(%d,%d) %f\n", x, y, anomalies);
/*unsigned char color = (unsigned char)(anomalies * 256);
unsigned char rgb[3];
rgb[0] = color;
rgb[1] = color;
rgb[2] = color;
image->DrawPointer(x * Parameters->AreaCell + Parameters->AreaCell / 2, y * Parameters->AreaCell + Parameters->AreaCell / 2, 4, rgb);
*/
int c = (anomalies - 0.1) * 100;
if (c < 0) {
c = 0;
} else {
if (c > 15) {
c = 15;
}
}
if (anomalies > Parameters->AnomalyThreshold) {
image->DrawPointer(x * Parameters->AreaCell + Parameters->AreaCell / 2, y * Parameters->AreaCell + Parameters->AreaCell / 2, 4, colors[c]);
}
}
}
}
| [
"robopicksel@gmail.com"
] | robopicksel@gmail.com |
fa6acc4133f9daec80000f98ead2ce2b8dad31f4 | e557ce74c9fe34aa2b68441254b7def699067501 | /src/libtsduck/dtv/descriptors/tsTargetRegionDescriptor.cpp | 5ea1be9d86f65fc5d2990cd276041192fbd3bea9 | [
"BSD-2-Clause"
] | permissive | cedinu/tsduck-mod | 53d9b4061d0eab9864d40b1d47b34f5908f99d8a | 6c97507b63e7882a146eee3613d4184b7e535101 | refs/heads/master | 2023-05-10T12:56:33.185589 | 2023-05-02T09:00:57 | 2023-05-02T09:00:57 | 236,732,523 | 0 | 0 | BSD-2-Clause | 2021-09-23T08:36:08 | 2020-01-28T12:41:10 | C++ | UTF-8 | C++ | false | false | 8,755 | cpp | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2023, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
#include "tsTargetRegionDescriptor.h"
#include "tsDescriptor.h"
#include "tsTablesDisplay.h"
#include "tsPSIRepository.h"
#include "tsPSIBuffer.h"
#include "tsDuckContext.h"
#include "tsxmlElement.h"
#define MY_XML_NAME u"target_region_descriptor"
#define MY_CLASS ts::TargetRegionDescriptor
#define MY_DID ts::DID_DVB_EXTENSION
#define MY_EDID ts::EDID_TARGET_REGION
#define MY_STD ts::Standards::DVB
TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::ExtensionDVB(MY_EDID), MY_XML_NAME, MY_CLASS::DisplayDescriptor);
//----------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------
ts::TargetRegionDescriptor::TargetRegionDescriptor() :
AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0),
country_code(),
regions()
{
}
void ts::TargetRegionDescriptor::clearContent()
{
country_code.clear();
regions.clear();
}
ts::TargetRegionDescriptor::TargetRegionDescriptor(DuckContext& duck, const Descriptor& desc) :
TargetRegionDescriptor()
{
deserialize(duck, desc);
}
ts::TargetRegionDescriptor::Region::Region() :
country_code(),
region_depth(0),
primary_region_code(0),
secondary_region_code(0),
tertiary_region_code(0)
{
}
//----------------------------------------------------------------------------
// This is an extension descriptor.
//----------------------------------------------------------------------------
ts::DID ts::TargetRegionDescriptor::extendedTag() const
{
return MY_EDID;
}
//----------------------------------------------------------------------------
// Serialization
//----------------------------------------------------------------------------
void ts::TargetRegionDescriptor::serializePayload(PSIBuffer& buf) const
{
buf.putLanguageCode(country_code);
for (const auto& it : regions) {
const bool has_cc = it.country_code.size() == 3;
buf.putBits(0xFF, 5);
buf.putBit(has_cc);
buf.putBits(it.region_depth, 2);
if (has_cc) {
buf.putLanguageCode(it.country_code);
}
if (it.region_depth >= 1) {
buf.putUInt8(it.primary_region_code);
if (it.region_depth >= 2) {
buf.putUInt8(it.secondary_region_code);
if (it.region_depth >= 3) {
buf.putUInt16(it.tertiary_region_code);
}
}
}
}
}
//----------------------------------------------------------------------------
// Deserialization
//----------------------------------------------------------------------------
void ts::TargetRegionDescriptor::deserializePayload(PSIBuffer& buf)
{
buf.getLanguageCode(country_code);
while (buf.canRead()) {
Region region;
buf.skipBits(5);
const bool has_cc = buf.getBool();
buf.getBits(region.region_depth, 2);
if (has_cc) {
buf.getLanguageCode(region.country_code);
}
if (region.region_depth >= 1) {
region.primary_region_code = buf.getUInt8();
if (region.region_depth >= 2) {
region.secondary_region_code = buf.getUInt8();
if (region.region_depth >= 3) {
region.tertiary_region_code = buf.getUInt16();
}
}
}
regions.push_back(region);
}
}
//----------------------------------------------------------------------------
// Static method to display a descriptor.
//----------------------------------------------------------------------------
void ts::TargetRegionDescriptor::DisplayDescriptor(TablesDisplay& disp, PSIBuffer& buf, const UString& margin, DID did, TID tid, PDS pds)
{
if (buf.canReadBytes(3)) {
disp << margin << "Country code: \"" << buf.getLanguageCode() << "\"" << std::endl;
for (size_t index = 0; buf.canReadBytes(1); ++index) {
disp << margin << "- Region #" << index << std::endl;
buf.skipBits(5);
const bool has_cc = buf.getBool();
const uint8_t depth = buf.getBits<uint8_t>(2);
if (has_cc) {
disp << margin << " Country code: \"" << buf.getLanguageCode() << "\"" << std::endl;
}
if (depth >= 1) {
disp << margin << UString::Format(u" Primary region code: 0x%X (%<d)", {buf.getUInt8()}) << std::endl;
if (depth >= 2) {
disp << margin << UString::Format(u" Secondary region code: 0x%X (%<d)", {buf.getUInt8()}) << std::endl;
if (depth >= 3) {
disp << margin << UString::Format(u" Tertiary region code: 0x%X (%<d)", {buf.getUInt16()}) << std::endl;
}
}
}
}
}
}
//----------------------------------------------------------------------------
// XML serialization
//----------------------------------------------------------------------------
void ts::TargetRegionDescriptor::buildXML(DuckContext& duck, xml::Element* root) const
{
root->setAttribute(u"country_code", country_code);
for (const auto& it : regions) {
xml::Element* e = root->addElement(u"region");
e->setAttribute(u"country_code", it.country_code, true);
if (it.region_depth >= 1) {
e->setIntAttribute(u"primary_region_code", it.primary_region_code, true);
if (it.region_depth >= 2) {
e->setIntAttribute(u"secondary_region_code", it.secondary_region_code, true);
if (it.region_depth >= 3) {
e->setIntAttribute(u"tertiary_region_code", it.tertiary_region_code, true);
}
}
}
}
}
//----------------------------------------------------------------------------
// XML deserialization
//----------------------------------------------------------------------------
bool ts::TargetRegionDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element)
{
xml::ElementVector xregions;
bool ok =
element->getAttribute(country_code, u"country_code", true, u"", 3, 3) &&
element->getChildren(xregions, u"region");
for (size_t i = 0; ok && i < xregions.size(); ++i) {
Region region;
ok = xregions[i]->getAttribute(region.country_code, u"country_code", false, u"", 3, 3) &&
xregions[i]->getIntAttribute(region.primary_region_code, u"primary_region_code", false) &&
xregions[i]->getIntAttribute(region.secondary_region_code, u"secondary_region_code", false) &&
xregions[i]->getIntAttribute(region.tertiary_region_code, u"tertiary_region_code", false);
if (xregions[i]->hasAttribute(u"tertiary_region_code")) {
region.region_depth = 3;
}
else if (xregions[i]->hasAttribute(u"secondary_region_code")) {
region.region_depth = 2;
}
else if (xregions[i]->hasAttribute(u"primary_region_code")) {
region.region_depth = 1;
}
else {
region.region_depth = 0;
}
regions.push_back(region);
}
return ok;
}
| [
"thierry@lelegard.fr"
] | thierry@lelegard.fr |
8e3f165d3b9df0429feec39eb5fd0608b6131d75 | 38c10c01007624cd2056884f25e0d6ab85442194 | /components/autofill/core/browser/autofill_download_manager_unittest.cc | b5ba01c250c056914b243291e12d6cd7ccc07f3a | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 19,988 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill/core/browser/autofill_download_manager.h"
#include <list>
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/histogram_tester.h"
#include "base/test/test_timeouts.h"
#include "base/thread_task_runner_handle.h"
#include "components/autofill/core/browser/autofill_field.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/form_structure.h"
#include "components/autofill/core/browser/test_autofill_driver.h"
#include "components/autofill/core/common/form_data.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "net/url_request/url_request_status.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::ASCIIToUTF16;
namespace autofill {
namespace {
// Call |fetcher->OnURLFetchComplete()| as the URLFetcher would when
// a response is received. Params allow caller to set fake status.
void FakeOnURLFetchComplete(net::TestURLFetcher* fetcher,
int response_code,
const std::string& response_body) {
fetcher->set_url(GURL());
fetcher->set_status(net::URLRequestStatus());
fetcher->set_response_code(response_code);
fetcher->SetResponseString(response_body);
fetcher->delegate()->OnURLFetchComplete(fetcher);
}
} // namespace
// This tests AutofillDownloadManager. AutofillDownloadTest implements
// AutofillDownloadManager::Observer and creates an instance of
// AutofillDownloadManager. Then it records responses to different initiated
// requests, which are verified later. To mock network requests
// TestURLFetcherFactory is used, which creates URLFetchers that do not
// go over the wire, but allow calling back HTTP responses directly.
// The responses in test are out of order and verify: successful query request,
// successful upload request, failed upload request.
class AutofillDownloadTest : public AutofillDownloadManager::Observer,
public testing::Test {
public:
AutofillDownloadTest()
: prefs_(test::PrefServiceForTesting()),
request_context_(new net::TestURLRequestContextGetter(
base::ThreadTaskRunnerHandle::Get())),
download_manager_(&driver_, prefs_.get(), this) {
driver_.SetURLRequestContext(request_context_.get());
}
void LimitCache(size_t cache_size) {
download_manager_.set_max_form_cache_size(cache_size);
}
// AutofillDownloadManager::Observer implementation.
void OnLoadedServerPredictions(const std::string& response_xml) override {
ResponseData response;
response.response = response_xml;
response.type_of_response = QUERY_SUCCESSFULL;
responses_.push_back(response);
}
void OnUploadedPossibleFieldTypes() override {
ResponseData response;
response.type_of_response = UPLOAD_SUCCESSFULL;
responses_.push_back(response);
}
void OnServerRequestError(const std::string& form_signature,
AutofillDownloadManager::RequestType request_type,
int http_error) override {
ResponseData response;
response.signature = form_signature;
response.error = http_error;
response.type_of_response =
request_type == AutofillDownloadManager::REQUEST_QUERY ?
REQUEST_QUERY_FAILED : REQUEST_UPLOAD_FAILED;
responses_.push_back(response);
}
enum ResponseType {
QUERY_SUCCESSFULL,
UPLOAD_SUCCESSFULL,
REQUEST_QUERY_FAILED,
REQUEST_UPLOAD_FAILED,
};
struct ResponseData {
ResponseType type_of_response;
int error;
std::string signature;
std::string response;
ResponseData() : type_of_response(REQUEST_QUERY_FAILED), error(0) {}
};
base::MessageLoop message_loop_;
std::list<ResponseData> responses_;
scoped_ptr<PrefService> prefs_;
scoped_refptr<net::TestURLRequestContextGetter> request_context_;
TestAutofillDriver driver_;
AutofillDownloadManager download_manager_;
};
TEST_F(AutofillDownloadTest, QueryAndUploadTest) {
// Create and register factory.
net::TestURLFetcherFactory factory;
FormData form;
FormFieldData field;
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("email");
field.name = ASCIIToUTF16("email");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("email2");
field.name = ASCIIToUTF16("email2");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("password");
field.name = ASCIIToUTF16("password");
field.form_control_type = "password";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
FormStructure *form_structure = new FormStructure(form);
ScopedVector<FormStructure> form_structures;
form_structures.push_back(form_structure);
form.fields.clear();
field.label = ASCIIToUTF16("address");
field.name = ASCIIToUTF16("address");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("address2");
field.name = ASCIIToUTF16("address2");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("city");
field.name = ASCIIToUTF16("city");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure = new FormStructure(form);
form_structures.push_back(form_structure);
form.fields.clear();
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("password");
field.name = ASCIIToUTF16("password");
field.form_control_type = "password";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure = new FormStructure(form);
form_structures.push_back(form_structure);
// Request with id 0.
base::HistogramTester histogram;
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 1);
// Set upload to 100% so requests happen.
download_manager_.SetPositiveUploadRate(1.0);
download_manager_.SetNegativeUploadRate(1.0);
// Request with id 1.
EXPECT_TRUE(download_manager_.StartUploadRequest(
*(form_structures[0]), true, ServerFieldTypeSet(), std::string()));
// Request with id 2.
EXPECT_TRUE(download_manager_.StartUploadRequest(
*(form_structures[1]), false, ServerFieldTypeSet(), std::string()));
// Request with id 3. Upload request with a non-empty additional password form
// signature.
EXPECT_TRUE(download_manager_.StartUploadRequest(*(form_structures[2]), false,
ServerFieldTypeSet(), "42"));
const char *responses[] = {
"<autofillqueryresponse>"
"<field autofilltype=\"0\" />"
"<field autofilltype=\"3\" />"
"<field autofilltype=\"5\" />"
"<field autofilltype=\"9\" />"
"<field autofilltype=\"0\" />"
"<field autofilltype=\"30\" />"
"<field autofilltype=\"31\" />"
"<field autofilltype=\"33\" />"
"</autofillqueryresponse>",
"<autofilluploadresponse positiveuploadrate=\"0.5\" "
"negativeuploadrate=\"0.3\"/>",
"<html></html>",
};
// Return them out of sequence.
net::TestURLFetcher* fetcher = factory.GetFetcherByID(1);
ASSERT_TRUE(fetcher);
FakeOnURLFetchComplete(fetcher, 200, std::string(responses[1]));
// After that upload rates would be adjusted to 0.5/0.3
EXPECT_DOUBLE_EQ(0.5, download_manager_.GetPositiveUploadRate());
EXPECT_DOUBLE_EQ(0.3, download_manager_.GetNegativeUploadRate());
fetcher = factory.GetFetcherByID(2);
ASSERT_TRUE(fetcher);
FakeOnURLFetchComplete(fetcher, 404, std::string(responses[2]));
fetcher = factory.GetFetcherByID(0);
ASSERT_TRUE(fetcher);
FakeOnURLFetchComplete(fetcher, 200, std::string(responses[0]));
EXPECT_EQ(3U, responses_.size());
EXPECT_EQ(AutofillDownloadTest::UPLOAD_SUCCESSFULL,
responses_.front().type_of_response);
EXPECT_EQ(0, responses_.front().error);
EXPECT_EQ(std::string(), responses_.front().signature);
// Expected response on non-query request is an empty string.
EXPECT_EQ(std::string(), responses_.front().response);
responses_.pop_front();
EXPECT_EQ(AutofillDownloadTest::REQUEST_UPLOAD_FAILED,
responses_.front().type_of_response);
EXPECT_EQ(404, responses_.front().error);
EXPECT_EQ(form_structures[1]->FormSignature(),
responses_.front().signature);
// Expected response on non-query request is an empty string.
EXPECT_EQ(std::string(), responses_.front().response);
responses_.pop_front();
EXPECT_EQ(responses_.front().type_of_response,
AutofillDownloadTest::QUERY_SUCCESSFULL);
EXPECT_EQ(0, responses_.front().error);
EXPECT_EQ(std::string(), responses_.front().signature);
EXPECT_EQ(responses[0], responses_.front().response);
responses_.pop_front();
// Set upload to 0% so no new requests happen.
download_manager_.SetPositiveUploadRate(0.0);
download_manager_.SetNegativeUploadRate(0.0);
// No actual requests for the next two calls, as we set upload rate to 0%.
EXPECT_FALSE(download_manager_.StartUploadRequest(
*(form_structures[0]), true, ServerFieldTypeSet(), std::string()));
EXPECT_FALSE(download_manager_.StartUploadRequest(
*(form_structures[1]), false, ServerFieldTypeSet(), std::string()));
fetcher = factory.GetFetcherByID(4);
EXPECT_EQ(NULL, fetcher);
// Modify form structures to miss the cache.
field.label = ASCIIToUTF16("Address line 2");
field.name = ASCIIToUTF16("address2");
field.form_control_type = "text";
form.fields.push_back(field);
form_structure = new FormStructure(form);
form_structures.push_back(form_structure);
// Request with id 4.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures.get()));
fetcher = factory.GetFetcherByID(4);
ASSERT_TRUE(fetcher);
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 2);
fetcher->set_backoff_delay(TestTimeouts::action_max_timeout());
FakeOnURLFetchComplete(fetcher, 500, std::string(responses[0]));
EXPECT_EQ(AutofillDownloadTest::REQUEST_QUERY_FAILED,
responses_.front().type_of_response);
EXPECT_EQ(500, responses_.front().error);
// Expected response on non-query request is an empty string.
EXPECT_EQ(std::string(), responses_.front().response);
responses_.pop_front();
// Query requests should be ignored for the next 10 seconds.
EXPECT_FALSE(download_manager_.StartQueryRequest(form_structures.get()));
fetcher = factory.GetFetcherByID(5);
EXPECT_EQ(NULL, fetcher);
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 2);
// Set upload required to true so requests happen.
form_structures[0]->upload_required_ = UPLOAD_REQUIRED;
// Request with id 4.
EXPECT_TRUE(download_manager_.StartUploadRequest(
*(form_structures[0]), true, ServerFieldTypeSet(), std::string()));
fetcher = factory.GetFetcherByID(5);
ASSERT_TRUE(fetcher);
fetcher->set_backoff_delay(TestTimeouts::action_max_timeout());
FakeOnURLFetchComplete(fetcher, 503, std::string(responses[2]));
EXPECT_EQ(AutofillDownloadTest::REQUEST_UPLOAD_FAILED,
responses_.front().type_of_response);
EXPECT_EQ(503, responses_.front().error);
responses_.pop_front();
// Upload requests should be ignored for the next 10 seconds.
EXPECT_FALSE(download_manager_.StartUploadRequest(
*(form_structures[0]), true, ServerFieldTypeSet(), std::string()));
fetcher = factory.GetFetcherByID(6);
EXPECT_EQ(NULL, fetcher);
}
TEST_F(AutofillDownloadTest, QueryTooManyFieldsTest) {
// Create and register factory.
net::TestURLFetcherFactory factory;
// Create a query that contains too many fields for the server.
std::vector<FormData> forms(21);
ScopedVector<FormStructure> form_structures;
for (auto& form : forms) {
for (size_t i = 0; i < 5; ++i) {
FormFieldData field;
field.label = base::IntToString16(i);
field.name = base::IntToString16(i);
field.form_control_type = "text";
form.fields.push_back(field);
}
FormStructure* form_structure = new FormStructure(form);
form_structures.push_back(form_structure);
}
// Check whether the query is aborted.
EXPECT_FALSE(download_manager_.StartQueryRequest(form_structures.get()));
}
TEST_F(AutofillDownloadTest, QueryNotTooManyFieldsTest) {
// Create and register factory.
net::TestURLFetcherFactory factory;
// Create a query that contains a lot of fields, but not too many for the
// server.
std::vector<FormData> forms(25);
ScopedVector<FormStructure> form_structures;
for (auto& form : forms) {
for (size_t i = 0; i < 4; ++i) {
FormFieldData field;
field.label = base::IntToString16(i);
field.name = base::IntToString16(i);
field.form_control_type = "text";
form.fields.push_back(field);
}
FormStructure* form_structure = new FormStructure(form);
form_structures.push_back(form_structure);
}
// Check that the query is not aborted.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures.get()));
}
TEST_F(AutofillDownloadTest, CacheQueryTest) {
// Create and register factory.
net::TestURLFetcherFactory factory;
FormData form;
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
form.fields.push_back(field);
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
form.fields.push_back(field);
FormStructure *form_structure = new FormStructure(form);
ScopedVector<FormStructure> form_structures0;
form_structures0.push_back(form_structure);
// Add a slightly different form, which should result in a different request.
field.label = ASCIIToUTF16("email");
field.name = ASCIIToUTF16("email");
form.fields.push_back(field);
form_structure = new FormStructure(form);
ScopedVector<FormStructure> form_structures1;
form_structures1.push_back(form_structure);
// Add another slightly different form, which should also result in a
// different request.
field.label = ASCIIToUTF16("email2");
field.name = ASCIIToUTF16("email2");
form.fields.push_back(field);
form_structure = new FormStructure(form);
ScopedVector<FormStructure> form_structures2;
form_structures2.push_back(form_structure);
// Limit cache to two forms.
LimitCache(2);
const char *responses[] = {
"<autofillqueryresponse>"
"<field autofilltype=\"0\" />"
"<field autofilltype=\"3\" />"
"<field autofilltype=\"5\" />"
"</autofillqueryresponse>",
"<autofillqueryresponse>"
"<field autofilltype=\"0\" />"
"<field autofilltype=\"3\" />"
"<field autofilltype=\"5\" />"
"<field autofilltype=\"9\" />"
"</autofillqueryresponse>",
"<autofillqueryresponse>"
"<field autofilltype=\"0\" />"
"<field autofilltype=\"3\" />"
"<field autofilltype=\"5\" />"
"<field autofilltype=\"9\" />"
"<field autofilltype=\"0\" />"
"</autofillqueryresponse>",
};
base::HistogramTester histogram;
// Request with id 0.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures0.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 1);
// No responses yet
EXPECT_EQ(0U, responses_.size());
net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
ASSERT_TRUE(fetcher);
FakeOnURLFetchComplete(fetcher, 200, std::string(responses[0]));
ASSERT_EQ(1U, responses_.size());
EXPECT_EQ(responses[0], responses_.front().response);
responses_.clear();
// No actual request - should be a cache hit.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures0.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 2);
// Data is available immediately from cache - no over-the-wire trip.
ASSERT_EQ(1U, responses_.size());
EXPECT_EQ(responses[0], responses_.front().response);
responses_.clear();
// Request with id 1.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures1.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 3);
// No responses yet
EXPECT_EQ(0U, responses_.size());
fetcher = factory.GetFetcherByID(1);
ASSERT_TRUE(fetcher);
FakeOnURLFetchComplete(fetcher, 200, std::string(responses[1]));
ASSERT_EQ(1U, responses_.size());
EXPECT_EQ(responses[1], responses_.front().response);
responses_.clear();
// Request with id 2.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures2.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 4);
fetcher = factory.GetFetcherByID(2);
ASSERT_TRUE(fetcher);
FakeOnURLFetchComplete(fetcher, 200, std::string(responses[2]));
ASSERT_EQ(1U, responses_.size());
EXPECT_EQ(responses[2], responses_.front().response);
responses_.clear();
// No actual requests - should be a cache hit.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures1.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 5);
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures2.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 6);
ASSERT_EQ(2U, responses_.size());
EXPECT_EQ(responses[1], responses_.front().response);
EXPECT_EQ(responses[2], responses_.back().response);
responses_.clear();
// The first structure should've expired.
// Request with id 3.
EXPECT_TRUE(download_manager_.StartQueryRequest(form_structures0.get()));
histogram.ExpectUniqueSample("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_SENT, 7);
// No responses yet
EXPECT_EQ(0U, responses_.size());
fetcher = factory.GetFetcherByID(3);
ASSERT_TRUE(fetcher);
FakeOnURLFetchComplete(fetcher, 200, std::string(responses[0]));
ASSERT_EQ(1U, responses_.size());
EXPECT_EQ(responses[0], responses_.front().response);
}
} // namespace autofill
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
b1c4280791ace5c437e1e06af8b338fa36d5563f | dfb6c1f525908ae85e575babe292c6c54431a947 | /Classes/Const/TwitterConst.h | 362f8e2093a0bb7e5282cddc318efda0050dadc5 | [] | no_license | momons/hateru_cocos2dx | c3fe616ee28b25ae6c00e43dc42da9b67bceaee2 | 184ebb03f9a03774ee207b6a4efaaf562e31de3a | refs/heads/master | 2020-04-15T14:29:40.459659 | 2019-04-25T12:54:29 | 2019-04-25T12:54:29 | 60,107,035 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 595 | h | //
// TwitterConst.h
// hateru_cocos2dx
//
// Created by Kazunari Hara on 2019/04/10.
//
#ifndef TwitterConst_h
#define TwitterConst_h
#include <string>
using namespace std;
/// Twitter定数定義クラス
class TwitterConst final {
public:
/// コンシューマキー
static const string consumerKey;
/// コンシューマサークレット
static const string consumerSecret;
private:
/**
* コンストラクタ
*/
TwitterConst() {}
/**
* デストラクタ
*/
~TwitterConst() {}
};
#endif /* TwitterConst_h */
| [
"kazu@nikuq.com"
] | kazu@nikuq.com |
24218f1cc86a8cd8fc413c5b08f782bd25581270 | efff48379a3059f0e60938ec879f37f7b594ccf3 | /chessSGS/Classes/GameOverLayer.h | 62093d2822b93e21fb9f39710b93877807907097 | [] | no_license | wxg456852/sanguosha | 7d31da291690a8c3d730a798f47f6e02f20133f6 | 9910c1728ee1055c78837afb5e144719b4ca24b1 | refs/heads/master | 2020-03-24T21:10:40.481123 | 2018-05-12T04:33:18 | 2018-05-12T04:33:18 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 331 | h | /*
游戏结束后显示在最上层的 操作layer
*/
#pragma once
#include "cocos2d.h"
class GameOverLayer :public cocos2d::LayerColor
{
public:
bool init();
void onEnter();
void onExit();
void update(float delta);
CREATE_FUNC(GameOverLayer);
void menuRepPlay(Ref*pSender);
void menuExit(Ref* pSender);
private:
}; | [
"274575817@qq.com"
] | 274575817@qq.com |
06ef8ce706bb195d03c9326574bc7c69733c3584 | 6c169c72f76cd0bfbf6f005bba681ba007a16346 | /Strings/Strings.cpp | 5a14c11d173a1301656e2252dbc1cf81692f7047 | [] | no_license | CompetitiveCode/hackerrank-cpp | 1274759152078764989676c6fd03c6a84a530fd9 | 6adb81352add0eeb9ced068cf6cdc015acff541a | refs/heads/master | 2022-01-11T16:35:51.299010 | 2019-06-20T12:37:38 | 2019-06-20T12:37:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | cpp | //Answer to Strings
#include <iostream>
#include <string>
using namespace std;
int main() {
string a,b;
cin>>a;
cin>>b;
cout<<a.size()<<" "<<b.size()<<"\n";
cout<<a+b<<"\n";
char c=a[0],d=b[0];
a[0]=d;
b[0]=c;
cout<<a<<" "<<b;
return 0;
}
/*
Declaration:
string a = "abc";
Size:
int len = a.size();
Concatenate two strings:
string a = "abc";
string b = "def";
string c = a + b; // c = "abcdef".
Accessing element:
string s = "abc";
char c0 = s[0]; // c0 = 'a'
char c1 = s[1]; // c1 = 'b'
char c2 = s[2]; // c2 = 'c'
s[0] = 'z'; // s = "zbc"
P.S.: We will use cin/cout to read/write a string.
*/ | [
"admin@remedcu.com"
] | admin@remedcu.com |
3f7342ac4f44bfab08682e61768973a48355f61f | 45925a8c5573084e2b9333f185134bd80549fe19 | /src/menuitem.cc | 710de28d35dd5306e60715befcde5cc017e8e818 | [] | no_license | thelazt/whooman | ede8ca90886af2f9f2ea7a6cfd2643de8f15853d | e468c2b7509e02d8a82e16fa9af2e2515179cc29 | refs/heads/master | 2023-02-27T15:25:07.014510 | 2021-02-04T16:14:58 | 2021-02-04T16:14:58 | 117,605,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,338 | cc | #include "menuitem.h"
// Quick & ugly hacked menu...
#include "player.h"
#include "utils.h"
#include "input.h"
#include "menu.h"
MenuItem * MenuItem::active = nullptr;
MenuItem * MenuItem::first = nullptr;
bool MenuItem::navBlocked = false;
bool MenuItem::pointBlocked = false;
MenuItem::MenuItem() : prev(nullptr), next(nullptr), current_action(ACTION_NONE) {
if (first == nullptr) {
next = prev = active = first = this;
} else {
next = first;
prev = first->prev;
first->prev = prev->next = this;
}
}
void MenuItem::navigate(bool up, bool down, bool left, bool right, bool press) {
assert(active != nullptr);
active->navigationHelper(up, down, left, right, press);
}
bool MenuItem::pointer(int x, int y, bool pressed) {
MenuItem * i = first;
do {
assert(i != nullptr);
if (i->pointerHelper(x, y, pressed))
return true;
i = i->next;
} while (i != first);
return false;
}
void MenuItem::showAll() {
MenuItem * i = first;
do {
assert(i != nullptr);
i->show();
i = i->next;
} while (i != first);
}
Sprite * MenuItemSelect::button = nullptr;
Sprite * MenuItemSelect::label = nullptr;
enum MenuItem::Mode MenuItemSelect::buttonHelper(enum Action action) {
if (!isAllowed(action))
return INACTIVE;
else if (active == this)
return current_action == action ? PRESSED : ACTIVE;
else
return NORMAL;
}
MenuItemSelect::MenuItemSelect(unsigned short x, unsigned short y) : x(x), yTop(y - height), yBottom(y + 80) {
if (button == nullptr)
button = new Sprite("img/menu_select.png", width, height);
if (label == nullptr)
label = new Sprite("img/menu_label.png", 128, 25);
}
void MenuItemSelect::action(Action a, bool &block) {
if (a == ACTION_NONE) {
if (block) {
block = false;
current_action = ACTION_NONE;
}
} else if (!block && a != current_action) {
if (a != ACTION_NONE) {
if (active != this) {
active->current_action = ACTION_NONE;
active = this;
}
handle(a);
block = true;
}
current_action = a;
}
}
void MenuItemSelect::navigationHelper(bool up, bool down, bool left, bool right, bool press) {
(void) press;
if (up) {
action(ACTION_UP, navBlocked);
} else if (down) {
action(ACTION_DOWN, navBlocked);
} else if (left || right) {
if (!navBlocked) {
current_action = ACTION_NONE;
active = left ? prev : next;
active->current_action = ACTION_NONE;
navBlocked = true;
}
} else {
action(ACTION_NONE, navBlocked);
}
}
bool MenuItemSelect::pointerHelper(int x, int y, bool pressed) {
if (x >= this->x && x < this->x + width && y >= this->yTop && y < this->yBottom + height) {
if (pressed && y >= this->yTop && y < this->yTop + height) {
action(MenuItem::ACTION_UP, pointBlocked);
} else if (pressed && y >= this->yBottom && y < this->yBottom + height) {
action(MenuItem::ACTION_DOWN, pointBlocked);
} else {
action(MenuItem::ACTION_NONE, pointBlocked);
pointBlocked = false;
}
return true;
} else {
return false;
}
}
void MenuItemSelect::show() {
draw();
button->draw(ACTION_UP + 2 * buttonHelper(ACTION_UP), x, yTop);
button->draw(ACTION_DOWN + 2 * buttonHelper(ACTION_DOWN), x, yBottom);
}
Sprite * MenuItemPlayerInput::input = nullptr;
void MenuItemPlayerInput::handle(enum Action action) {
while (true) {
int i = static_cast<int>(player[p].input);
if (action == ACTION_UP) {
if (--i < 0)
i = Input::NONE;
} else if (action == ACTION_DOWN) {
if (++i > Input::NONE)
i = 0;
}
player[p].input = static_cast<Input::Method>(i);
int controls = 0;
for (unsigned i = 0; i < 4; i++)
if (player[p].input == player[i].input)
controls++;
// At least 2 Players
if (player[p].input == Input::NONE && controls <= 2)
return;
// AI always okay
else if (player[p].input == Input::AI)
return;
// Each Input device can only be used once
else if (controls == 1)
return;
}
}
void MenuItemPlayerInput::draw() {
input->draw(player[p].input, px, py);
}
Input::Method MenuItemPlayerInput::getDefault(unsigned short p) {
switch (p) {
case 0: return Input::KEYBOARD_ARROW;
case 1: return Input::KEYBOARD_WASD;
case 2: return Input::AI;
default: return Input::NONE;
}
}
MenuItemPlayerInput::MenuItemPlayerInput(unsigned short p)
: MenuItemSelect(221 + p * 200, 375), p(p), px(170 + p * 200), py(380) {
if (input == nullptr) {
input = new Sprite("img/menu_control.png", 96, 72);
}
player[p].input = getDefault(p);
}
size_t MenuItemPlayerSkin::skins[maxPlayer];
constexpr const char * MenuItemPlayerSkin::sprites[];
void MenuItemPlayerSkin::load(unsigned short p) {
assert(p < size(skins));
assert(skins[p] < size(sprites));
player[p].load(sprites[skins[p]]);
}
void MenuItemPlayerSkin::handle(enum Action action) {
bool unique;
do {
if (action == ACTION_UP) {
if (skins[p]-- == 0)
skins[p] = size(sprites) - 1;
} else if (action == ACTION_DOWN) {
if (++skins[p] >= static_cast<int>(size(sprites)))
skins[p] = 0;
}
unique = true;
for (unsigned i = 0; i < 4; i++)
if (p != i && skins[p] == skins[i]) {
unique = false;
break;
}
} while (!unique);
load(p);
}
void MenuItemPlayerSkin::draw() {
label->draw(p + (active == this || active == next ? 7 : 0), px - 2, py - 55);
player[p].skin->draw(1, px, py + 5);
}
MenuItemPlayerSkin::MenuItemPlayerSkin(unsigned short p)
: MenuItemSelect(157 + p * 200, 375), p(p), px(148 + p * 200), py(375) {
assert(p < size(skins));
skins[p] = p;
load(p);
}
Sprite * MenuItemArenaSize::arenaSizes = nullptr;
bool MenuItemArenaSize::isAllowed(enum Action action) {
return (action == ACTION_UP && size > 0) || (action == ACTION_DOWN && size < 2);
}
void MenuItemArenaSize::handle(enum Action action) {
if (isAllowed(action)) {
if (action == ACTION_UP)
size--;
else if (action == ACTION_DOWN)
size++;
}
}
void MenuItemArenaSize::draw() {
arenaSizes->draw(size, 148, 664);
}
MenuItemArenaSize::MenuItemArenaSize(int size) : MenuItemSelect(157, 605), size(size) {
assert(size > 0 && size < 2);
if (arenaSizes == nullptr) {
arenaSizes = new Sprite("img/menu_size.png", 80, 16);
}
}
unsigned short MenuItemArenaSize::getWidth() {
switch (size) {
case 0: return 9;
case 2: return 15;
default: return 13;
}
}
unsigned short MenuItemArenaSize::getHeight() {
switch (size) {
case 0: return 11;
case 2: return 19;
default: return 15;
}
}
Sprite * MenuItemArenaName::arenaNames = nullptr;
void MenuItemArenaName::handle(enum Action action) {
if (action == ACTION_UP) {
if (--arena < 0)
arena = Game::ARENA_RANDOM;
} else if (action == ACTION_DOWN) {
if (++arena > Game::ARENA_RANDOM)
arena = 0;
}
}
void MenuItemArenaName::draw() {
label->draw(active == prev || active == this || active == next ? 11 : 4, 165, 550);
arenaNames->draw(arena, 185, 607);
}
MenuItemArenaName::MenuItemArenaName(Game::ArenaName arena) : MenuItemSelect(205, 605), arena(arena) {
if (arenaNames == nullptr) {
arenaNames = new Sprite("img/menu_playgrounds.png", 96, 59);
}
}
enum Game::ArenaName MenuItemArenaName::get() {
return static_cast<enum Game::ArenaName>(arena);
}
Sprite * MenuItemArenaLayout::arenaLayouts = nullptr;
void MenuItemArenaLayout::handle(enum Action action) {
if (action == ACTION_UP) {
if (--layout < 0)
layout = Game::LAYOUT_RANDOM;
} else if (action == ACTION_DOWN) {
if (++layout > Game::LAYOUT_RANDOM)
layout = 0;
}
}
void MenuItemArenaLayout::draw() {
arenaLayouts->draw(layout, 232, 664);
}
MenuItemArenaLayout::MenuItemArenaLayout(Game::LayoutName layout) : MenuItemSelect(257, 605), layout(layout) {
if (arenaLayouts == nullptr) {
arenaLayouts = new Sprite("img/menu_layout.png", 104, 16);
}
}
enum Game::LayoutName MenuItemArenaLayout::get() {
return static_cast<enum Game::LayoutName>(layout);
}
Sprite * MenuItemSet::itemsets = nullptr;
void MenuItemSet::handle(enum Action action) {
if (action == ACTION_UP) {
if (--itemset < 0)
itemset = Item::SET_RANDOM;
} else if (action == ACTION_DOWN) {
if (++itemset > Item::SET_RANDOM)
itemset = 0;
}
}
void MenuItemSet::draw() {
label->draw(active == this ? 13 : 6, 365, 550);
itemsets->draw(itemset, 390, 608);
}
MenuItemSet::MenuItemSet(Item::ItemSet itemset) : MenuItemSelect(400, 605), itemset(itemset) {
if (itemsets == nullptr) {
itemsets = new Sprite("img/menu_items.png", 74, 74);
}
}
enum Item::ItemSet MenuItemSet::get() {
return static_cast<enum Item::ItemSet>(itemset);
}
Sprite * MenuItemRound::roundSprite = nullptr;
bool MenuItemRound::isAllowed(enum Action action) {
return (action == ACTION_UP && rounds > 3) || (action == ACTION_DOWN && rounds < 7);
}
void MenuItemRound::handle(enum Action action) {
if (isAllowed(action)) {
if (action == ACTION_UP)
rounds -= 2;
else if (action == ACTION_DOWN)
rounds += 2;
}
}
void MenuItemRound::draw() {
label->draw(active == this ? 12 : 5, 535, 550);
roundSprite->draw((rounds - 3) / 2, 572, 615);
}
MenuItemRound::MenuItemRound(int rounds) : MenuItemSelect(570, 605), rounds(rounds) {
assert(rounds == 3 || rounds == 5 || rounds == 7);
if (roundSprite == nullptr) {
roundSprite = new Sprite("img/menu_round.png", 52, 60);
}
}
unsigned short MenuItemRound::get() {
return rounds;
}
Sprite * MenuItemButton::button = nullptr;
MenuItem * MenuItemButton::firstButton = nullptr;
MenuItem * MenuItemButton::lastButton = nullptr;
/*bool MenuItemButton::navDown = false;
bool MenuItemButton::pointerDown = false;
*/
MenuItemButton::MenuItemButton(enum Button b) : navDown(false), pointerDown(false), b(b), x(703), y(580 + b * 40) {
if (button == nullptr)
button = new Sprite("img/menu_button.png", width, height);
if (firstButton == nullptr)
firstButton = this;
lastButton = this;
}
void MenuItemButton::switchButton(MenuItem * next) {
if (!navBlocked) {
current_action = ACTION_NONE;
active = next;
active->current_action = ACTION_NONE;
navBlocked = true;
navDown = false;
}
}
void MenuItemButton::navigationHelper(bool up, bool down, bool left, bool right, bool press) {
if (up) {
if (firstButton != this)
switchButton(prev);
} else if (down) {
if (lastButton != this)
switchButton(next);
} else if (left || right) {
switchButton(left ? firstButton->prev : lastButton->next);
} else if (press) {
if (!navBlocked) {
navBlocked = true;
navDown = true;
}
} else {
if (navBlocked) {
navBlocked = false;
navDown = false;
current_action = ACTION_NONE;
}
}
}
bool MenuItemButton::pointerHelper(int x, int y, bool pressed) {
if (x >= this->x && x < this->x + width && y >= this->y && y < this->y + height) {
if (pressed) {
if (active != this) {
current_action = ACTION_NONE;
active = this;
}
if (!pointBlocked) {
pointerDown = true;
pointBlocked = true;
}
} else {
pointBlocked = false;
pointerDown = false;
}
return true;
} else {
pointBlocked = false;
pointerDown = false;
return false;
}
}
void MenuItemButton::show() {
button->draw(b + 3 * (active == this ? (navDown || pointerDown ? PRESSED : ACTIVE) : NORMAL), x, y);
}
bool MenuItemButton::pressed(bool release) {
if (active == this && (navDown || pointerDown)) {
if (release) {
navDown = false;
pointerDown = false;
}
return true;
} else {
navDown = false;
pointerDown = false;
return false;
}
}
| [
"heinloth@cs.fau.de"
] | heinloth@cs.fau.de |
8f13e84d6517af30f27375c0acf1ec1f298f0e81 | 492f3f0bfa78c1d6cdf4a9ed4c85ba31fa1e58c7 | /include/bgkoctomap/bgkoctree_node.h | 5a180ab7159ff32afa63eff38ac3ebfd84943213 | [] | no_license | DrZhouKarl/MultilayerMapping | dbdbf30acdbd77861ae35e8360c326ae87fa4a5d | a9b6d6010470f8062bfd2feee2bd785e8a19957c | refs/heads/master | 2023-04-13T14:04:17.662217 | 2021-04-27T01:20:44 | 2021-04-27T01:20:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,272 | h | #ifndef LA3DM_BGK_OCCUPANCY_H
#define LA3DM_BGK_OCCUPANCY_H
#include <iostream>
#include <fstream>
namespace la3dm {
/// Occupancy state: before pruning: FREE, OCCUPIED, UNKNOWN; after pruning: PRUNED
enum class State : char {
FREE, OCCUPIED, UNKNOWN, PRUNED
};
/*
* @brief Inference ouputs and occupancy state.
*
* Occupancy has member variables: m_A and m_B (kernel densities of positive
* and negative class, respectively) and State.
* Before using this class, set the static member variables first.
*/
class Occupancy {
friend std::ostream &operator<<(std::ostream &os, const Occupancy &oc);
friend std::ofstream &operator<<(std::ofstream &os, const Occupancy &oc);
friend std::ifstream &operator>>(std::ifstream &is, Occupancy &oc);
friend class BGKOctoMap;
public:
/*
* @brief Constructors and destructor.
*/
Occupancy() :
m_A(Occupancy::prior_A),
m_B(Occupancy::prior_B),
state(State::UNKNOWN),
tm_A(Occupancy::prior_A),
tm_B(Occupancy::prior_B) {
classified = false; }
Occupancy(float A, float B);
Occupancy(const Occupancy &other) : m_A(other.m_A), m_B(other.m_B), state(other.state) { }
Occupancy &operator=(const Occupancy &other) {
m_A = other.m_A;
m_B = other.m_B;
state = other.state;
return *this;
}
~Occupancy() { }
/*
* @brief Exact updates for nonparametric Bayesian kernel inference
* @param ybar kernel density estimate of positive class (occupied)
* @param kbar kernel density of negative class (unoccupied)
*/
void update(float ybar, float kbar);
void update_traversability(float ybar, float kbar);
/// Get probability of occupancy.
float get_prob() const;
float get_prob_traversability() const;
/// Get variance of occupancy (uncertainty)
inline float get_var() const { return (m_A * m_B) / ( (m_A + m_B) * (m_A + m_B) * (m_A + m_B + 1.0f)); }
/*
* @brief Get occupancy state of the node.
* @return occupancy state (see State).
*/
inline State get_state() const { return state; }
/// Prune current node; set state to PRUNED.
inline void prune() { state = State::PRUNED; }
/// Only FREE and OCCUPIED nodes can be equal.
inline bool operator==(const Occupancy &rhs) const {
return this->state != State::UNKNOWN && this->state == rhs.state;
}
bool classified;
private:
// For occupancy
float m_A;
float m_B;
State state;
static float sf2;
static float ell; // length-scale
static float prior_A; // prior on alpha
static float prior_B; // prior on beta
static float free_thresh; // FREE occupancy threshold
static float occupied_thresh; // OCCUPIED occupancy threshold
static float var_thresh;
// For traversability
float tm_A;
float tm_B;
};
//typedef Occupancy OcTreeNode;
}
#endif // LA3DM_BGK_OCCUPANCY_H
| [
"ganlu@umich.edu"
] | ganlu@umich.edu |
0c691712725e0e2a6c8138618b4cd0f5e32f995f | d9ba9d41a1225797872d596558bdffda25944f7f | /serie/serie.ino | 8b89716cf115ec689566b5221be5fce110046ad3 | [] | no_license | VictorMartinDzib/Arduino-Examples | 6dab0cb7a6e85fb9c5f35e8a9e9342aed6783d4d | 2e257336924ab46ae5fdbbaf337e5f1081f52a99 | refs/heads/master | 2020-12-27T06:31:57.353734 | 2020-04-06T18:42:44 | 2020-04-06T18:42:44 | 237,796,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | ino | int pinArray[] = {13,11,12,10,9,8,7,6,5,4};
int controlLed = 13; // LED de control
int waitNextLed = 100;
int tailLength = 11; // Número de LED-s conectados (que es también el tamaño del array)
int lineSize = 11;
void setup(){
int i;
pinMode (controlLed, OUTPUT);
for(i = 0; i < lineSize; i++)
{
pinMode(pinArray[i], OUTPUT);
}
}
void loop(){
int i;
int tailCounter = tailLength;
digitalWrite(controlLed, HIGH);
for (i=0; i<lineSize; i++)
{
digitalWrite(pinArray[i],HIGH);
delay(waitNextLed);
if (tailCounter == 0){
digitalWrite(pinArray[i-tailLength],LOW);
}else if(tailCounter > 0){
tailCounter--;
}
}
for (i=(lineSize-tailLength); i<lineSize; i++){
digitalWrite(pinArray[i],LOW);
delay(waitNextLed);
}
}
| [
"richtzq211@gmail.com"
] | richtzq211@gmail.com |
7987218cd832379f0477f08c5a9d4c957f1902c1 | 543baf3f63e6a6b47534b524e54fa90c37613959 | /codeforce/374/c.cpp | 63032c4e8c2bdf19cdab8ba89489a4257becbd8a | [] | no_license | funtion/algorithmProblems | ac9341f9fc5233cffe51d2140404983763b66265 | dd27afc25670ea3ad2a681dc382a3e500e530c1a | refs/heads/master | 2020-05-04T05:15:44.150235 | 2014-01-12T10:53:27 | 2014-01-12T10:53:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,727 | cpp | #include <iostream>
#include <map>
using namespace std;
map<char,int> fk;
char mp[2000][2000];
int mid[2000][2000];
bool loop;
int n,m;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
int cnt[1000100];
inline bool ck(int x,int y){
return 0<=x&&x<n&&0<=y&&y<m;
}
void s(int x,int y,int id,int type){
cout<<"sss"<<x<<' '<<y<<endl;
if(loop)
return;
int iid = fk[mp[x][y]];
cout<<iid<<endl;
mid[x][y] = id;
if(type == 0){
for(int i=0;i<4;i++){
int xx = x+dx[i],yy = y+dy[i];
bool reach = ck(xx,yy);
if(reach&&fk[mp[xx][yy]] == (iid+1)%4){
if(reach && mid[xx][yy] == id){
loop = true;cout<<"loop"<<xx<<' '<<yy<<endl;
}
s(xx,yy,id,1);
}
if(reach&&fk[mp[xx][yy]] == (iid+4-1)%4){
if(reach && mid[xx][yy] == id){
loop = true;cout<<"loop"<<xx<<' '<<yy<<endl;
}
s(xx,yy,id,-1);
}
}
}else if(type == 1){
for(int i=0;i<4;i++){
int xx = x+dx[i],yy = y+dy[i];
bool reach = ck(xx,yy);
if(reach&&fk[mp[xx][yy]] == (iid+1)%4){
if(reach && mid[xx][yy] == id){
loop = true;
//cout<<"loop"<<x<<':'<<xx<<' '<<y<<':'<<yy<<' '<<fk[mp[xx][yy]]<<endl;
}
s(xx,yy,id,1);
}
}
}else{
for(int i=0;i<4;i++){
int xx = x+dx[i],yy = y+dy[i];
bool reach = ck(xx,yy);
if(reach&&fk[mp[xx][yy]] == (iid+4-1)%4){
if(reach && mid[xx][yy] == id){
loop = true;cout<<"loop"<<xx<<' '<<yy<<endl;
}
s(xx,yy,id,-1);
}
}
}
}
int main(){
fk['D'] = 0;
fk['I'] = 1;
fk['M'] = 2;
fk['A'] = 3;
cin>>n>>m;
int t = 0;
for(int i=0;i<n;i++)cin>>mp[i];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(mp[i][j] == 'D' && mid[i][j] == 0){
s(i,j,++t,0);
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<mid[i][j]<< ' ';
}
cout<<endl;
}
if(loop){
cout<<"Poor Dima!\n";
}else{
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cnt[mid[i][j]]++;
}
}
int ans = 0;
for(int i=1;i<=t;i++){
if(cnt[i]>ans)
ans = cnt[i];
}
if(ans>=4){
cout<<ans/4<<endl;
}else{
cout<<"Poor Dima!\n";
}
}
return 0;
} | [
"acm@acm.com"
] | acm@acm.com |
0f8d4ff24e0ef7189a6a6626cc99aeae5ab7f6da | 41f59e08ba58512f34b35ec6691e8c6e50f4a046 | /network/threading.cpp | 58d7ff68b3b8c9fde40fee957951effb90dedab9 | [] | no_license | UNIDY2002/Doudizhu | 515f5aeaa50859ea39448a6f4516a9e91e0b6d53 | 8e1af9dcfe680f17b19124df3d20d5cc7fef28e1 | refs/heads/master | 2022-12-07T22:22:24.857706 | 2020-09-07T14:30:10 | 2020-09-07T14:30:10 | 292,559,041 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,035 | cpp | #include "threading.h"
WaitForConnectionThread::WaitForConnectionThread(QObject *parent, QTcpSocket *socket, DecentralizedClient *policy) :
QThread(nullptr), socket(socket), policy(policy) {}
WaitForConnectionThread::~WaitForConnectionThread() = default;
void WaitForConnectionThread::run() {
emit policy->postMessageToWelcome("已发送连接请求");
if (socket->waitForConnected() && socket->waitForReadyRead(100)) {
auto message = read(socket);
if (message.type == CONFIRM_CONNECTION) {
bool ok;
auto number = message.payload.toInt(&ok);
if (ok) {
if (number < 2) {
emit policy->postMessageToWelcome("连接成功,请稍候");
policy->waitForGameStarts();
} else {
emit policy->postMessageToWelcome("人数已满,请重试");
}
} else {
emit policy->postMessageToWelcome("连接失败,请重试");
}
} else {
emit policy->postMessageToWelcome("连接失败,请重试");
}
} else {
emit policy->postMessageToWelcome("连接超时,请重试");
// TODO: why cannot exit with code 0 in this case?
}
}
WaitForReadyReadThread::WaitForReadyReadThread(DecentralizedClient *parent, QTcpSocket *socket, GameLogic *logic) :
QThread(nullptr), policy(parent), socket(socket), logic(logic) {}
WaitForReadyReadThread::~WaitForReadyReadThread() = default;
// TODO: why isn't readyRead signal available?
void WaitForReadyReadThread::run() {
while (true) {
if (socket->waitForReadyRead(100)) {
Message message;
while ((message = read(socket)).type) {
if (message.type == GAME_STARTS) {
policy->processGameStartsMessage(message, logic);
return;
} else {
logic->onMessage(message);
}
}
}
}
} | [
"UNIDY2002@outlook.com"
] | UNIDY2002@outlook.com |
5adafe6073bb614f093efc82067383731d18e829 | d60ebb5f7a0577e81b730ca0a7ecee321b6a533e | /tests/cppcorba-empty-model/expected/cpp/JniCache.cpp | 40bb7ba4728a90420e358b2456851955b843f95c | [
"Apache-2.0"
] | permissive | matejhrazdira/corba-binding | 8dbcbff47a855be0c1277954f8a38c52768d873e | 1f4ceaaadf8b02c641325581f0c9968a146a5b8a | refs/heads/master | 2020-12-30T16:02:12.623437 | 2020-04-27T08:07:59 | 2020-04-27T08:07:59 | 91,199,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,195 | cpp | #include "JniCache.h"
namespace corbabinding {
JniCache::JniCache(JNIEnv * _env_) {
{
jclass _cls_ = _env_->FindClass("java/lang/Boolean");
java.lang.Boolean._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.lang.Boolean._ctor_ = _env_->GetStaticMethodID(_cls_, "valueOf", "(Z)Ljava/lang/Boolean;");
java.lang.Boolean.booleanValue = _env_->GetMethodID(_cls_, "booleanValue", "()Z");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/lang/Byte");
java.lang.Byte._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.lang.Byte._ctor_ = _env_->GetStaticMethodID(_cls_, "valueOf", "(B)Ljava/lang/Byte;");
java.lang.Byte.byteValue = _env_->GetMethodID(_cls_, "byteValue", "()B");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/lang/Integer");
java.lang.Integer._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.lang.Integer._ctor_ = _env_->GetStaticMethodID(_cls_, "valueOf", "(I)Ljava/lang/Integer;");
java.lang.Integer.intValue = _env_->GetMethodID(_cls_, "intValue", "()I");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/lang/Long");
java.lang.Long._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.lang.Long._ctor_ = _env_->GetStaticMethodID(_cls_, "valueOf", "(J)Ljava/lang/Long;");
java.lang.Long.longValue = _env_->GetMethodID(_cls_, "longValue", "()J");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/lang/Float");
java.lang.Float._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.lang.Float._ctor_ = _env_->GetStaticMethodID(_cls_, "valueOf", "(F)Ljava/lang/Float;");
java.lang.Float.floatValue = _env_->GetMethodID(_cls_, "floatValue", "()F");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/lang/Double");
java.lang.Double._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.lang.Double._ctor_ = _env_->GetStaticMethodID(_cls_, "valueOf", "(D)Ljava/lang/Double;");
java.lang.Double.doubleValue = _env_->GetMethodID(_cls_, "doubleValue", "()D");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/lang/Character");
java.lang.Character._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.lang.Character._ctor_ = _env_->GetStaticMethodID(_cls_, "valueOf", "(C)Ljava/lang/Character;");
java.lang.Character.charValue = _env_->GetMethodID(_cls_, "charValue", "()C");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/util/ArrayList");
java.util.ArrayList._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
java.util.ArrayList._ctor_ = _env_->GetMethodID(_cls_, "<init>", "(I)V");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("java/util/List");
java.util.List.add = _env_->GetMethodID(_cls_, "add", "(Ljava/lang/Object;)Z");
java.util.List.get = _env_->GetMethodID(_cls_, "get", "(I)Ljava/lang/Object;");
java.util.List.size = _env_->GetMethodID(_cls_, "size", "()I");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("Var");
_impl_._var_._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
_impl_._var_._ctor_ = _env_->GetMethodID(_cls_, "<init>", "(Ljava/lang/Object;)V");
_impl_._var_._get_ = _env_->GetMethodID(_cls_, "get", "()Ljava/lang/Object;");
_impl_._var_._set_ = _env_->GetMethodID(_cls_, "set", "(Ljava/lang/Object;)V");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("CorbaException");
_impl_._corba_exception_._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
_impl_._corba_exception_._ctor_ = _env_->GetMethodID(_cls_, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("AlreadyDisposedException");
_impl_._already_disposed_exception_._cls_ = (jclass) _env_->NewGlobalRef(_cls_);
_impl_._already_disposed_exception_._ctor_ = _env_->GetMethodID(_cls_, "<init>", "()V");
_env_->DeleteLocalRef(_cls_);
}
{
jclass _cls_ = _env_->FindClass("EventConsumer");
_impl_._event_consumer_._callback_ = _env_->GetMethodID(_cls_, "onEvent", "(Ljava/lang/Object;)V");
_env_->DeleteLocalRef(_cls_);
}
}
JniCache::~JniCache() {}
} /* namespace corbabinding */
| [
"matejhrazdira@gmail.com"
] | matejhrazdira@gmail.com |
efa2031bac5c46a303f287675d0cb07da371b0b8 | 4367b2933b974b6ccdd3a2f122419ca91001bf97 | /CS 172 Exam 1/CS 172 Exam 1/Movie.cpp | 59d020281fb23582d2414c3858eddcdd36dd7b5e | [] | no_license | lsmith17/Exam1 | c5b6076e60bbe9c2433e5e924a2a84c471f2fd1d | 9da85af26e212d43ca5b2498956497f78c4fe775 | refs/heads/master | 2021-01-01T15:19:11.056512 | 2014-05-31T05:56:05 | 2014-05-31T05:56:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | cpp | //I affirm that all code given below was written solely by me, Logan Smith, and that any help I received adhered to the rules stated for this exam.
#include"Movie.h"
Movie::Movie(){ // default movie which is a comedy.
title = "Longest Yard";
genre = "Comedy";
showtime = 0;
}
Movie::Movie(string new_title, string new_genre, int new_showtime){
title = new_title;
genre = new_genre;
showtime = new_showtime;
}
string Movie::GetTitle(){ //allows you to get name of movie
return title;
}
string Movie::GetGenre(){ //allows you to find out the genre of the movie
return genre;
}
int Movie::GetShowtime(){ //allows you to know when the movie is playing/currently playing
return showtime;
}
| [
"lsmith17@my.whitworth.edu"
] | lsmith17@my.whitworth.edu |
53e2729450f33d957be999384ad982672b960781 | eae743ab965993d91686ecd6d6f4a1f9dd8adbfb | /Project3/Project3/car.h | 60b56328f6dbeb089caea9a57cde7de55e805c57 | [
"MIT"
] | permissive | DanielTongAwesome/System_Software_Projects | 19088b1a70130d091b05fff66f327982d46213c0 | 5ce29e35f8906965c4c6a98d6abc5b5f15cfef36 | refs/heads/master | 2021-09-27T14:35:54.367258 | 2018-11-09T04:13:41 | 2018-11-09T04:13:41 | 150,636,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | h | #ifndef __CAR__
#define __CAR__
#include <stdio.h>
#include <iostream>
#include "../rt.h"
class CarClass: public ActiveClass {
private:
int car_number; // indicate the car number
int car_speed = 0;; // car current speed
int car_accelerate = 0; // car current acceleration
public:
CarClass(int car_number); // car class constructor
void Accelerate(int acceleration); // call to accelerate the car
void Cruise(); // change to cruiser mode
void Stop(); // stop the vehicle
~CarClass(); // car class destructor
private:
int DisplayCarClassData(void *ThreadArgs) {
for (int i = 0; i < 10; i++) {
printf("%d Car No.%2d Current Speed -- %4d Current Acceleration -- %3d \n", i, car_number, car_speed, car_accelerate);
Sleep(2000);
}
return 0;
}
// This is the main parent threaad for the class, when we create objects of this class
// this function is run. Here is creates two child threads of it's own which are just member functions
// of the same class and have access to the same class member variables, so they communicate with each other
int main() {
ClassThread<CarClass> CarPrintThread(this, &CarClass::DisplayCarClassData, SUSPENDED, NULL);
CarPrintThread.Resume();
for (int i = 0; i < 1000; i++) {
car_speed = car_speed + car_accelerate;
Sleep(10);
}
CarPrintThread.WaitForThread();
return 0;
}
};
#endif | [
"danieltongubc@gmail.com"
] | danieltongubc@gmail.com |
95040b6459b58d1254822dedd331424e8024796a | 40dfe5a6dc38f35b6dfd87aea20581372be0a9a6 | /03_cuda/floyd_dlazdice_sekvencni/funkceSpolecne.hpp | 81618d61bad67389b0c813c547d4b97de403b074 | [] | no_license | VojtechMyslivec/PAP-NCG | c9679a05cd156fea6d8ea030e3723821c4a1742a | d503537e8a53e7603a01a8f0b2714cbd0e7ab6ca | refs/heads/master | 2021-01-20T02:19:20.247431 | 2015-05-14T10:10:13 | 2015-05-14T10:10:13 | 31,473,256 | 2 | 0 | null | 2015-05-13T21:56:16 | 2015-02-28T19:14:04 | C++ | UTF-8 | C++ | false | false | 4,351 | hpp | /** funkceSpolecne.hpp
*
* Autori: Vojtech Myslivec <vojtech.myslivec@fit.cvut.cz>, FIT CVUT v Praze
* Zdenek Novy <zdenek.novy@fit.cvut.cz>, FIT CVUT v Praze
*
* Datum: unor-kveten 2015
*
* Popis: Semestralni prace z predmetu MI-PAP:
* Hledani nejkratsich cest v grafu
* Algoritmus Floyd-Warshall pomoci dlazdickovani
* Spolecne funkce pro nacitani / vypis dat
*
*
*/
#ifndef FUNKCE_SPOLECNE_aohiuefijn39nvkjns92
#define FUNKCE_SPOLECNE_aohiuefijn39nvkjns92
#define MIN( a, b ) ( a < b ? a : b )
#include <iostream>
// polovina z 32b unsigned -- tak, aby 2* nekonecno bylo stale dostatecne velke
// je to 2^30
#define NEKONECNO 0x40000000
#define MAIN_OK 0
#define MAIN_ERR_USAGE 1
#define MAIN_ERR_VSTUP 2
#define MAIN_ERR_GRAF 3
#define MAIN_ERR_NEOCEKAVANA 10
#define NACTI_OK 0
#define NACTI_NEKONECNO 1
#define NACTI_ERR_PRAZDNO 2
#define NACTI_ERR_ZNAMENKO 3
#define NACTI_ERR_CISLO 4
#define NACTI_ERR_TEXT 5
#define GRAF_ORIENTOVANY 0
#define GRAF_NEORIENTOVANY 1
#define GRAF_CHYBA 2
using namespace std;
// vypise usage na vystupni stream os, vola se s argumentem argv[0]
// jako jmenem programu
void vypisUsage( ostream & os, const char * jmenoProgramu );
// smaze alokovany graf (provadi kontrolu ukazatele na NULL) a nastavi
// ukazatel(e) na NULL
void uklid( unsigned ** graf, unsigned pocetUzlu );
// zkonstroluje, zda vstupni stream is je uz prazdny (muze obsahovat prazdne znaky)
//
// true stream je prazdny
// false stream neni/nebyl prazdny
bool zkontrolujPrazdnyVstup( istream & is );
// Funkce zajisti nacteni a kontrolu parametru.
// Do vystupnich promenych uklada:
// souborSGrafem jmeno souboru se vstupnimi daty -- prepinac -f (povinny!)
// navrat navratovy kod v pripade selhani / chyby
// tedy v pripade vraceni false
//
// Navratove hodnoty
// false Chyba vstupu -- prepinacu. Danou chybu vrati na stderr
// a ulozu navratovou hodnotu do parametru navrat.
// Prepinac -h prinuti funkci skoncit s chybou, ale navratova
// hodnota bude MAIN_OK.
// true Vse v poradku, parametry byly uspesne nacteny
bool parsujArgumenty( int argc, char ** argv, char *& souborSGrafem, unsigned & navrat );
// nacte jednu unsigned hodnotu ze vstupu
// pokud misto unsigned cisla nalezne - (nasledovanou prazdnym znakem)
// ulozi do hodnoty DIJKSTRA_NEKONECNO
//
// NACTI_OK v poradku se podarilo nacist jednu unsigned hodnotu
// NACTI_NEKONECNO na vstupu byl znak '-' oddeleny mezerami, do hodnoty byla
// prirazena hodnota NEKONECNO
// NACTI_ERR_TEXT na vstupu byl nejaky retezec zacinajici znakem -
// NACTI_ERR_PRAZDNO na vstupu jiz nebyl zadny platny znak
// NACTI_ERR_ZNAMENKO na vstupu byla zaporna hodnota
// NACTI_ERR_CISLO na vstupu nebylo cislo
unsigned nactiHodnotu( istream & is, unsigned & hodnota );
// funkce, ktera ze vstupniho streamu is nacte graf ve formatu
// n w(i,j), kde n je pocet uzlu (unsigned n > 0) a nasleduje
// n^2 unsigned hodnot, reprezentujici matici vah hran z uzlu i do j
// vaha muze byt nahrazen znakem '-' (ohranicenym prazdnymi znaky),
// ktery reprezentuje nekonecno.
//
// true uspesne nacteni grafu
// false chyba vstupu
bool nactiGraf( istream & is, unsigned ** & graf, unsigned & pocetUzlu );
// funkce otevre soubor s nazvem v c stringu a z neho se pokusi nacist graf
//
// true uspesne nacteni dat ze souboru
// false chyba souboru ci chyba vstupu
bool nactiData( const char * jmenoSouboru, unsigned ** & graf, unsigned & pocetUzlu );
// funkce, ktera zkontroluje graf, zda je orientovany ci neorientovany
// a ve spravnem formatu
//
// GRAF_ORIENTOVANY graf je orientovany
// GRAF_NEORIENTOVANY graf je neorientovany
// GRAF_CHYBA chyba formatu
// pro vsechny i musi platit, ze w(i,i) = graf[i][i] = 0
unsigned kontrolaGrafu( unsigned ** graf, unsigned pocetUzlu ); // graf by mel byt const..
// vypise graf (formatovanou w-matici) do vystupniho streamu os
void vypisGrafu( ostream & os, unsigned ** graf, unsigned pocetUzlu ); // graf by mel byt const..
#endif // FUNKCE_SPOLECNE_aohiuefijn39nvkjns92
| [
"vojtech.myslivec@fit.cvut.cz"
] | vojtech.myslivec@fit.cvut.cz |
cdcb51f42a91b19ec0adc1098147476a7da0dc86 | 6cecdbbe6eb721a0e43c07ed2b31bdcc9e553c55 | /Sail2D/Runs/first_multiarc_300_2/case/constant/polyMesh/boundary | ff58d8d0c975e1d2e4adeb379c96b4fd05e9f78b | [] | no_license | kiranhegde/Gmsh | 799d8cbefb7dd3f3d35ded15b40292fd3ede6468 | fefa906dabfddd9b87cc1f0256df81b4735420e1 | refs/heads/master | 2021-01-19T23:21:57.414954 | 2015-01-21T02:02:37 | 2015-01-21T02:02:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,682 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class polyBoundaryMesh;
location "constant/polyMesh";
object boundary;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
5
(
wings
{
type wall;
physicalType wall;
inGroups 1(wall);
nFaces 1800;
startFace 243606;
}
outlet
{
type patch;
physicalType patch;
nFaces 20;
startFace 245406;
}
tunnel
{
type wall;
physicalType wall;
inGroups 1(wall);
nFaces 40;
startFace 245426;
}
inlet
{
type patch;
physicalType patch;
nFaces 20;
startFace 245466;
}
defaultFaces
{
type empty;
inGroups 1(empty);
nFaces 244546;
startFace 245486;
}
)
// ************************************************************************* //
| [
"rlee32@gatech.edu"
] | rlee32@gatech.edu | |
bc2a52b23eccfc068d7d2f6b561d88390f7324f5 | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/browser/media/router/mojo/media_router_desktop_unittest.cc | 0250c6f14d1258b71dab25f120524d327bbdc6a1 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 7,926 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/router/mojo/media_router_desktop.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <string>
#include <utility>
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/media/router/event_page_request_manager.h"
#include "chrome/browser/media/router/event_page_request_manager_factory.h"
#include "chrome/browser/media/router/media_router_feature.h"
#include "chrome/browser/media/router/test/media_router_mojo_test.h"
#include "chrome/browser/media/router/test/provider_test_helpers.h"
#include "components/media_router/common/media_source.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::Invoke;
using testing::Mock;
using testing::Return;
namespace media_router {
namespace {
const char kOrigin[] = "http://origin/";
const char kRouteId[] = "routeId";
const char kSource[] = "source1";
class NullMessageObserver : public RouteMessageObserver {
public:
NullMessageObserver(MediaRouter* router, const MediaRoute::Id& route_id)
: RouteMessageObserver(router, route_id) {}
~NullMessageObserver() final {}
void OnMessagesReceived(const std::vector<mojom::RouteMessagePtr>) final {}
};
} // namespace
class MediaRouterDesktopTest : public MediaRouterMojoTest {
public:
MediaRouterDesktopTest() {}
~MediaRouterDesktopTest() override {}
DualMediaSinkService* media_sink_service() {
return media_sink_service_.get();
}
MockCastMediaSinkService* cast_media_sink_service() {
return cast_media_sink_service_;
}
protected:
std::unique_ptr<MediaRouterMojoImpl> CreateMediaRouter() override {
std::unique_ptr<MockCastMediaSinkService> cast_media_sink_service;
// We disable the DIAL MRP because initializing the DIAL MRP requires
// initialization of objects it depends on, which is outside the scope of
// this unit test. DIAL MRP initialization is covered by Media Router
// browser tests.
feature_list_.InitAndDisableFeature(kDialMediaRouteProvider);
cast_media_sink_service = std::make_unique<MockCastMediaSinkService>();
cast_media_sink_service_ = cast_media_sink_service.get();
media_sink_service_ =
std::unique_ptr<DualMediaSinkService>(new DualMediaSinkService(
std::move(cast_media_sink_service),
std::make_unique<MockDialMediaSinkService>(),
std::make_unique<MockCastAppDiscoveryService>()));
return std::unique_ptr<MediaRouterDesktop>(
new MediaRouterDesktop(profile(), media_sink_service_.get()));
}
private:
base::test::ScopedFeatureList feature_list_;
std::unique_ptr<DualMediaSinkService> media_sink_service_;
// Owned by |media_sink_service_|.
MockCastMediaSinkService* cast_media_sink_service_;
DISALLOW_COPY_AND_ASSIGN(MediaRouterDesktopTest);
};
#if defined(OS_WIN)
TEST_F(MediaRouterDesktopTest, EnableMdnsAfterEachRegister) {
EXPECT_CALL(mock_extension_provider_, EnableMdnsDiscovery()).Times(0);
EXPECT_CALL(*cast_media_sink_service(), StartMdnsDiscovery()).Times(0);
RegisterExtensionProvider();
base::RunLoop().RunUntilIdle();
EXPECT_CALL(mock_extension_provider_, EnableMdnsDiscovery()).Times(0);
EXPECT_CALL(*cast_media_sink_service(), StartMdnsDiscovery());
router()->OnUserGesture();
base::RunLoop().RunUntilIdle();
// EnableMdnsDiscovery() is called on this RegisterExtensionProvider() because
// we've already seen an mdns-enabling event.
EXPECT_CALL(mock_extension_provider_, EnableMdnsDiscovery()).Times(0);
EXPECT_CALL(*cast_media_sink_service(), StartMdnsDiscovery());
RegisterExtensionProvider();
base::RunLoop().RunUntilIdle();
}
#endif
TEST_F(MediaRouterDesktopTest, OnUserGesture) {
EXPECT_CALL(mock_extension_provider_,
UpdateMediaSinks(MediaSource::ForUnchosenDesktop().id()));
router()->OnUserGesture();
base::RunLoop().RunUntilIdle();
}
TEST_F(MediaRouterDesktopTest, SyncStateToMediaRouteProvider) {
MediaSource media_source(kSource);
std::unique_ptr<MockMediaSinksObserver> sinks_observer;
std::unique_ptr<MockMediaRoutesObserver> routes_observer;
std::unique_ptr<NullMessageObserver> messages_observer;
ProvideTestRoute(MediaRouteProviderId::EXTENSION, kRouteId);
router()->OnSinkAvailabilityUpdated(
MediaRouteProviderId::EXTENSION,
mojom::MediaRouter::SinkAvailability::PER_SOURCE);
EXPECT_CALL(mock_extension_provider_,
StartObservingMediaSinks(media_source.id()));
sinks_observer = std::make_unique<MockMediaSinksObserver>(
router(), media_source, url::Origin::Create(GURL(kOrigin)));
EXPECT_TRUE(sinks_observer->Init());
EXPECT_CALL(mock_extension_provider_,
StartObservingMediaRoutes(media_source.id()));
routes_observer =
std::make_unique<MockMediaRoutesObserver>(router(), media_source.id());
EXPECT_CALL(mock_extension_provider_,
StartListeningForRouteMessages(kRouteId));
messages_observer = std::make_unique<NullMessageObserver>(router(), kRouteId);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(Mock::VerifyAndClearExpectations(&mock_extension_provider_));
}
TEST_F(MediaRouterDesktopTest, ProvideSinks) {
std::vector<MediaSinkInternal> sinks;
MediaSink sink("sinkId", "sinkName", SinkIconType::CAST,
MediaRouteProviderId::EXTENSION);
CastSinkExtraData extra_data;
net::IPAddress ip_address;
EXPECT_TRUE(ip_address.AssignFromIPLiteral("192.168.1.3"));
extra_data.ip_endpoint = net::IPEndPoint(ip_address, 0);
extra_data.capabilities = 2;
extra_data.cast_channel_id = 3;
MediaSinkInternal expected_sink(sink, extra_data);
sinks.push_back(expected_sink);
const std::string kCastProviderName = "cast";
// |router()| is already registered with |media_sink_service_| during
// |SetUp()|.
EXPECT_CALL(mock_extension_provider_, ProvideSinks(kCastProviderName, sinks));
media_sink_service()->OnSinksDiscovered(kCastProviderName, sinks);
base::RunLoop().RunUntilIdle();
EXPECT_CALL(mock_extension_provider_, ProvideSinks(kCastProviderName, sinks));
static_cast<MediaRouterDesktop*>(router())->ProvideSinksToExtension();
base::RunLoop().RunUntilIdle();
const std::string kDialProviderName = "dial";
EXPECT_CALL(mock_extension_provider_, ProvideSinks(kCastProviderName, sinks));
EXPECT_CALL(mock_extension_provider_, ProvideSinks(kDialProviderName, sinks))
.Times(0);
media_sink_service()->OnSinksDiscovered(kDialProviderName, sinks);
static_cast<MediaRouterDesktop*>(router())->ProvideSinksToExtension();
base::RunLoop().RunUntilIdle();
}
// Tests that auto-join and Cast SDK join requests are routed to the extension
// MediaRouteProvider.
TEST_F(MediaRouterDesktopTest, SendCastJoinRequestsToExtension) {
TestJoinRoute(kAutoJoinPresentationId);
TestJoinRoute(kCastPresentationIdPrefix + std::string("123"));
}
TEST_F(MediaRouterDesktopTest, ExtensionMrpRecoversFromConnectionError) {
MediaRouterDesktop* media_router_desktop =
static_cast<MediaRouterDesktop*>(router());
auto* extension_mrp_proxy =
media_router_desktop->extension_provider_proxy_.get();
// |media_router_desktop| detects connection error and reconnects with
// |extension_mrp_proxy|.
for (int i = 0; i < MediaRouterDesktop::kMaxMediaRouteProviderErrorCount;
i++) {
ignore_result(extension_mrp_proxy->receiver_.Unbind());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(extension_mrp_proxy->receiver_.is_bound());
}
ignore_result(extension_mrp_proxy->receiver_.Unbind());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(extension_mrp_proxy->receiver_.is_bound());
}
} // namespace media_router
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
6af2784eedaa8a6fdcb23ee75643fb950ecd2c98 | 2bf2db289430b17ea4342ac8f76f8a808ac8bef6 | /teacher/Scene5ManyCubesIndividual.h | 56e087b70e93ec0a6669d330ff9b91687f6907f0 | [
"MIT"
] | permissive | chrischiao/modern-opengl | 2a97bb1ba1d990676334f6c919b3ed285db96e53 | 3d3af217f9b81c4e6a157dc3be489cf639996a15 | refs/heads/main | 2023-03-24T19:06:31.520739 | 2021-02-13T19:43:23 | 2021-02-13T19:43:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,111 | h | #pragma once
#include <GL/glew.h>
#include <AABB.h>
#include <BoxMesh.h>
#include <ShaderData.h>
#include <ShaderLoader.h>
#include <Random.h>
class Scene
{
public:
bool initialize()
{
// ------------------------------------------------------------------------
// 1- Load scene data
// ------------------------------------------------------------------------
std::vector<BoxVertex> vertices;
std::vector<unsigned int> elements;
getBoxMesh(vertices, elements);
_numElements = elements.size();
auto randomColor = make_random(0.2f, 1.0f, 123.0f);
auto randomAngle = make_random(0.0f, glm::radians(360.0f), 123.0f);
auto randomAxis = make_random(-1.0f, 1.0f, 123.0f);
auto randomScale = make_random(0.5f, 1.2f, 123.0f);
unsigned int numX = 20;
unsigned int numY = 20;
unsigned int numZ = 20;
_sceneSize = numX * numY * numZ;
// pre-allocate exact memory that will be used
_transforms.reserve(_sceneSize);
_materials.reserve(_sceneSize);
// Check if data would fit in a single SSBO
int maxSSBOSize = 0;
glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &maxSSBOSize);
if(_transforms.size()*sizeof(TransformData) > (unsigned int)maxSSBOSize || _materials.size()*sizeof(MaterialData) > (unsigned int)maxSSBOSize)
{
return false;
}
// Generate the scene
for(unsigned int z = 0; z < numZ; ++z)
{
for(unsigned int y = 0; y < numY; ++y)
{
for(unsigned int x = 0; x < numX; ++x)
{
glm::mat4 s = glm::scale(glm::mat4(), glm::vec3(randomScale(), randomScale(), randomScale()));
glm::mat4 r = glm::rotate(glm::mat4(), randomAngle(), glm::vec3(randomAxis(), randomAxis(), randomAxis()));
glm::mat4 t = glm::translate(glm::mat4(), glm::vec3(x*2.0f, y*2.0f, z*2.0f));
glm::mat4 m4 = t * r * s;
_transforms.push_back(toTransform(m4));
MaterialData material;
material.diffuse = glm::vec4(randomColor(), randomColor(), randomColor(), 1.0f);
material.specular = glm::vec4(1.0f, 1.0f, 1.0f, 128.0f);
_materials.push_back(material);
for(auto v : vertices)
{
_bounds.expand(glm::vec3(m4 * glm::vec4(v.position, 1.0f)));
}
}
}
}
// ------------------------------------------------------------------------
// 2- Create buffers and transfer data to GPU
// ------------------------------------------------------------------------
GLuint vbo;
glCreateBuffers(1, &vbo);
glNamedBufferStorage(vbo, vertices.size()*sizeof(BoxVertex), vertices.data(), 0); // flags = 0
GLuint ebo;
glCreateBuffers(1, &ebo);
glNamedBufferStorage(ebo, elements.size()*sizeof(unsigned int), elements.data(), 0); // flags = 0
// ------------------------------------------------------------------------
// 3- Setup vertex array object
// ------------------------------------------------------------------------
GLuint bufferIndex = 0;
// create vao
glCreateVertexArrays(1, &_vao);
// bind vbo to vao
glVertexArrayVertexBuffer(_vao, bufferIndex, vbo, 0, sizeof(BoxVertex)); // offset = 0, stride = sizeof(BoxVertex)
// setup position attrib
glEnableVertexArrayAttrib(_vao, IN_POSITION);
glVertexArrayAttribBinding(_vao, IN_POSITION, bufferIndex);
glVertexArrayAttribFormat(_vao, IN_POSITION, 3, GL_FLOAT, GL_FALSE, 0); // size = 3, normalized = false, offset = 0
// setup normal attrib
glEnableVertexArrayAttrib(_vao, IN_NORMAL);
glVertexArrayAttribBinding(_vao, IN_NORMAL, bufferIndex);
glVertexArrayAttribFormat(_vao, IN_NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(BoxVertex::position)); // size = 3, normalized = false, offset = sizeof(BoxVertex::position)
// bind ebo
glVertexArrayElementBuffer(_vao, ebo);
// ------------------------------------------------------------------------
// 4- Create shader program
// ------------------------------------------------------------------------
ShaderLoader loader;
if(!loader.addFile(GL_VERTEX_SHADER, "../src/Scene5ManyCubesIndividual.vert", "../src/ShaderData.h"))
{
return false;
}
if(!loader.addFile(GL_FRAGMENT_SHADER, "../src/Scene5ManyCubesIndividual.frag", "../src/ShaderData.h"))
{
return false;
}
if(!loader.link(_program))
{
return false;
}
// ------------------------------------------------------------------------
// 5- Setup storage buffers to store per-instance data
// ------------------------------------------------------------------------
glCreateBuffers(1, &_transformSSBO);
glNamedBufferStorage(_transformSSBO, sizeof(TransformData), nullptr, GL_DYNAMIC_STORAGE_BIT); // data = nullptr, flags = dynamic (enable buffersubdata)
glCreateBuffers(1, &_materialSSBO);
glNamedBufferStorage(_materialSSBO, sizeof(MaterialData), nullptr, GL_DYNAMIC_STORAGE_BIT); // data = nullptr, flags = dynamic (enable buffersubdata)
return true;
}
const AABB& getBounds()
{
return _bounds;
}
void draw(const CameraData& cameraData)
{
glUseProgram(_program);
glBindVertexArray(_vao);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, SB_TRANSFORM, _transformSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, SB_MATERIAL, _materialSSBO);
for(unsigned int i = 0; i < _sceneSize; ++i)
{
glNamedBufferSubData(_transformSSBO, 0, sizeof(TransformData), &_transforms.at(i));
glNamedBufferSubData(_materialSSBO, 0, sizeof(MaterialData), &_materials.at(i));
glDrawElements(GL_TRIANGLES, _numElements, GL_UNSIGNED_INT, 0); // offset = 0
}
}
private:
TransformData toTransform(const glm::mat4& m)
{
TransformData t;
// last row of mat4 is always 0,0,0,1 (affine transform)
// glm uses m[col][row]
t.row0[0] = m[0][0];
t.row0[1] = m[1][0];
t.row0[2] = m[2][0];
t.row0[3] = m[3][0];
t.row1[0] = m[0][1];
t.row1[1] = m[1][1];
t.row1[2] = m[2][1];
t.row1[3] = m[3][1];
t.row2[0] = m[0][2];
t.row2[1] = m[1][2];
t.row2[2] = m[2][2];
t.row2[3] = m[3][2];
return t;
}
AABB _bounds;
unsigned int _numElements;
unsigned int _sceneSize;
GLuint _vao;
GLuint _program;
GLuint _transformSSBO;
std::vector<TransformData> _transforms;
GLuint _materialSSBO;
std::vector<MaterialData> _materials;
};
| [
""
] | |
83ada56d8da19526ea47737687f6b2c831b86fcb | 03e1a82d1e83dd76aa10d926abf819640653411b | /__history/17.4/temp.cpp | 238b4c6c14b2126597a293cd935a261662f30d80 | [] | no_license | gbakkk5951/OI | 879d95c0b96df543d03d01b864bd47af2ba9c0c8 | a3fe8894e604e9aac08c2db6e36c1b77f3882c43 | refs/heads/master | 2018-09-20T10:09:23.170608 | 2018-07-09T11:52:21 | 2018-07-09T11:52:21 | 115,510,457 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | cpp | #include<cstdio>
struct _main{
struct tp{
tp *l;tp*r;
int val;
}in1,in2;
_main(){
tp*now=&in1;
now->val=15;
printf("%d",now->val);
}
}instance;int main(){}
| [
"526406038@qq.com"
] | 526406038@qq.com |
87c27cf920883beefecb1491dd305e5de8856435 | 003e6e7b62d2e7b9c7d1b4d01081bc07ac322dc5 | /library/base/dainty_base_string_impl.cpp | 5d543fe8a657af634f4d406bb10857eb48e3009d | [
"MIT"
] | permissive | ChipHunter/dainty | 3fc0780708fce4e5bd6cfa0e63c8261c0fcf7812 | f885b4cb0eabf423d2c0093fa2f4b07f3ce52b8f | refs/heads/master | 2020-06-18T06:31:08.892006 | 2019-07-09T21:32:36 | 2019-07-09T21:32:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,535 | cpp | /******************************************************************************
MIT License
Copyright (c) 2018 kieme, frits.germs@gmx.net
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 <cstdio>
#include <cstring>
#include <cstdlib>
#include "dainty_base_assert.h"
#include "dainty_base_terminal.h"
#include "dainty_base_string_impl.h"
namespace dainty
{
namespace base
{
namespace string
{
////////////////////////////////////////////////////////////////////////////////
t_void display(t_fmt, P_cstr_ fmt, ...) noexcept {
va_list args;
va_start(args, fmt);
std::vprintf(fmt, args);
va_end(args);
}
inline t_n_ multiple_of_64_(t_n_ n) noexcept {
if (n%64)
n = (n - n%64) + 64;
return n;
}
t_n_ calc_n_(t_n_ chars, t_n_ blks) noexcept {
return blks*64 + multiple_of_64_(chars + 1);
}
p_cstr_ alloc_(t_n_ n) noexcept {
p_cstr_ str = (p_cstr_)std::malloc(n);
if (!str)
assert_now(P_cstr("malloc failed to allocate"));
return str;
}
t_void dealloc_(p_cstr_ str) noexcept {
if (str)
std::free(str);
}
p_cstr_ realloc_(p_cstr_ str, t_n_ n) noexcept {
str = (p_cstr_)std::realloc(str, n);
if (!str)
assert_now(P_cstr("realloc failed to allocate"));
return str;
}
p_cstr_ sso_alloc_(p_cstr_ sso, t_n_ sso_max, t_n_& max) noexcept {
if (max > sso_max)
return alloc_(max);
max = sso_max;
return sso;
}
p_cstr_ sso_alloc_(p_cstr_ sso, t_n_ sso_max, p_cstr_ curr,
t_n_ max) noexcept {
if (max > sso_max) {
if (curr != sso)
return realloc_(curr, max);
p_cstr_ tmp = alloc_(max);
memcpy(tmp, curr, max);
return tmp;
}
return curr;
}
t_n_ build_(p_cstr_ dst, t_n_ max, P_cstr_ fmt, va_list vars,
t_overflow_grow) noexcept {
va_list args;
va_copy(args, vars);
t_n_ n = std::vsnprintf(dst, max, fmt, args);
va_end(args);
return n;
}
t_n_ build_(p_cstr_ dst, t_n_ max, P_cstr_ fmt, va_list vars,
t_overflow_assert) noexcept {
auto n = std::vsnprintf(dst, max, fmt, vars);
assert_if_false(n > 0 && (t_n_)n < max,
P_cstr("failed to build, buffer might be too small"));
return n;
}
t_n_ build_(p_cstr_ dst, t_n_ max, P_cstr_ fmt, va_list vars,
t_overflow_truncate) noexcept {
auto n = std::vsnprintf(dst, max, fmt, vars);
assert_if_false(n > 0, P_cstr("failed to build, std::vsnprintf failed"));
if ((t_n_)n >= max)
n = max - 1;
return n;
}
t_n_ copy_(p_cstr_ dst, t_n_ max, P_cstr_ src, t_n_ n,
t_overflow_assert) noexcept {
t_n_ cnt = 0, min = max - 1 < n ? max - 1 : n;
for (; cnt < min && src[cnt]; ++cnt)
dst[cnt] = src[cnt];
if (src[cnt] && cnt != n)
assert_now(P_cstr("buffer not big enough"));
dst[cnt] = '\0';
return cnt;
}
t_n_ copy_(p_cstr_ dst, t_n_ max, P_cstr_ src, t_n_ n,
t_overflow_truncate) noexcept {
t_n_ cnt = 0, min = max - 1 < n ? max - 1 : n;
for (; cnt < min && src[cnt]; ++cnt)
dst[cnt] = src[cnt];
dst[cnt] = '\0';
return cnt;
}
t_n_ copy_(p_cstr_ dst, t_n_ max, P_cstr_ src,
t_overflow_assert) noexcept {
t_n_ cnt = 0, min = max - 1;
for (; cnt < min && src[cnt]; ++cnt)
dst[cnt] = src[cnt];
if (src[cnt])
assert_now(P_cstr("buffer not big enough"));
dst[cnt] = '\0';
return cnt;
}
t_n_ copy_(p_cstr_ dst, t_n_ max, P_cstr_ src,
t_overflow_truncate) noexcept {
t_n_ cnt = 0, min = max - 1;
for (; cnt < min && src[cnt]; ++cnt)
dst[cnt] = src[cnt];
dst[cnt] = '\0';
return cnt;
}
t_n_ fill_(p_cstr_ dst, t_n_ max, R_block block,
t_overflow_assert) noexcept {
auto bmax = get(block.max);
if (bmax > max - 1)
assert_now(P_cstr("buffer not big enough"));
for (t_n_ cnt = 0; cnt < bmax; ++cnt)
dst[cnt] = block.c;
dst[bmax] = '\0';
return bmax;
}
t_n_ fill_(p_cstr_ dst, t_n_ max, R_block block,
t_overflow_truncate) noexcept {
auto bmax = get(block.max);
t_n_ min = max - 1 < bmax ? max - 1 : bmax;
for (t_n_ cnt = 0; cnt < min; ++cnt)
dst[cnt] = block.c;
dst[min] = '\0';
return min;
}
t_void display_(R_crange range, R_crange prefix, R_crange postfix) noexcept {
terminal::t_out out;
out << prefix << range << postfix;
}
t_void display_(P_cstr_ str, t_n_ len) noexcept {
if (len && str[len - 1] == '\n')
std::printf("%s", str);
else
std::printf("%s\n", str);
}
t_void display_n_(P_cstr_ str, t_n_ max) noexcept {
if (max && str[max-1] == '\n')
std::printf("%.*s", static_cast<t_int>(max), str);
else
std::printf("%.*s\n", static_cast<t_int>(max), str);
}
t_bool equal_(R_crange lh, R_crange rh) noexcept {
auto len1 = get(lh.n), len2 = get(rh.n);
if (len1 == len2)
return lh.ptr != rh.ptr ? (std::strncmp(lh.ptr, rh.ptr, len1) == 0)
: true;
return false;
}
t_bool less_(R_crange lh, R_crange rh) noexcept {
auto len1 = get(lh.n), len2 = get(rh.n);
if (lh.ptr != rh.ptr) {
auto ret = std::strncmp(lh.ptr, rh.ptr, len1 < len2 ? len1 : len2);
if (ret == 0)
return len1 < len2;
return ret < 0;
}
return false;
}
t_bool less_equal_(R_crange lh, R_crange rh) noexcept {
auto len1 = get(lh.n), len2 = get(rh.n);
if (lh.ptr != rh.ptr) {
auto ret = std::strncmp(lh.ptr, rh.ptr, len1 < len2 ? len1 : len2);
if (ret == 0)
return len1 <= len2;
return ret < 0;
}
return true;
}
t_n_ length_(P_cstr_ str) noexcept {
return std::strlen(str);
}
t_n_ length_(P_cstr_ fmt, va_list vars) noexcept {
va_list args;
va_copy(args, vars);
t_n_ require = std::vsnprintf(NULL, 0, fmt, args);
va_end(args);
return require;
}
t_bool match_(P_cstr_ str, P_cstr_ pattern) noexcept {
P_cstr_ l = nullptr; // XXX not fully correct
while (*pattern && *str) {
if (*pattern == *str) ++pattern;
else if (*pattern == '*') l = ++pattern;
else if (*pattern == '?') { ++pattern;
} else if (l) {
if (pattern != l) {
pattern = l;
continue;
}
} else
return false;
++str;
}
return *str ? (t_bool)l : !*pattern;
}
t_n_ count_(t_char c, P_cstr_ str) noexcept {
t_n_ cnt = 0;
for (; *str; ++str)
if (*str == c)
++cnt;
return cnt;
}
///////////////////////////////////////////////////////////////////////////////
t_ullong to_uint_(t_n_& use, t_char first, t_char last, t_n_ max_n,
P_cstr_ str) noexcept {
t_ullong value = 0;
P_cstr_ p = str, max_p = str + max_n;
for (; p < max_p && *p <= '9' && *p >= '0'; ++p);
if (p != str) {
if (p == max_p && (*str > first || (*str == first && p[-1] > last)))
--p;
use = p-- - str;
for (t_ullong i = 1; p >= str; i *= 10)
value += (*p-- - '0') * i;
} else
use = 0;
return value;
}
t_llong to_sint_(t_n_& use, t_char first, t_char last_min,
t_char last_max, t_n_ max_n, P_cstr_ str) noexcept {
const t_bool neg = *str == '-';
const t_char last = neg ? last_min : last_max;
P_cstr_ begin = str + (neg || *str == '+');
return static_cast<t_llong>(
to_uint_(use, first, last, max_n - (begin == str), begin))
* (neg ? -1 : 1);
}
t_ullong hex_to_uint_(t_n_& use, t_n_ max_n, P_cstr_ str) noexcept {
t_ullong value = 0;
P_cstr_ p = str, max_p = str + max_n;
for (; p < max_p &&
((*p <= '9' && *p >= '0') ||
(*p <= 'f' && *p >= 'a') ||
(*p <= 'F' && *p >= 'A')); ++p);
if (p != str) {
use = p-- - str;
for (t_ullong i = 1; p >= str; i *= 16) {
if (*p >= '0' && *p <= '9')
value += (*p-- - '0') * i;
else if (*p >= 'a' && *p <= 'f')
value += (*p-- - 'a' + 10) * i;
else
value += (*p-- - 'A' + 10) * i;
}
} else
use = 0;
return value;
}
///////////////////////////////////////////////////////////////////////////////
t_n_ uint_to_str_(p_cstr_ dst, t_n_ max, t_ullong value) noexcept {
t_n_ req = 0;
if (max) {
if (!value) {
if (max > 1)
*dst++ = '0';
*dst = '\0';
req = 1;
} else {
t_char tmp[20];
for (; value; value/=10)
tmp[req++] = value%10 + '0';
t_ix_ ix = max - 1;
t_ix_ end = (ix < req ? ix : req);
ix = 0;
for (t_ix_ last = req - 1; ix < end; ++ix)
dst[ix] = tmp[last--];
dst[ix] = '\0';
}
}
return req;
}
t_n_ int_to_str_(p_cstr_ dst, t_n_ max, t_llong value) noexcept {
T_bool neg = value < 0;
if (neg) {
if (max > 2)
*dst++ = '-';
}
return uint_to_str_(dst, max - neg, neg ? -value : value) + neg;
}
t_n_ hex_to_str_(p_cstr_ dst, t_n_ max, t_ullong value) noexcept {
t_n_ req = 0;
if (max) {
if (!value) {
if (max > 1)
*dst++ = '0';
*dst = '\0';
req = 1;
} else {
T_char tbl[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
t_char tmp[16];
for (; value; value/=16)
tmp[req++] = tbl[value%16];
t_ix_ last = req - 1;
t_ix_ end = (max < req ? max - 1 : last);
t_ix_ ix = 0;
for (; ix < end; ++ix)
dst[ix] = tmp[last--];
dst[ix] = '\0';
}
}
return req;
}
///////////////////////////////////////////////////////////////////////////////
t_void scan_(P_cstr_ str, t_n_ n, P_cstr_ fmt, va_list args) noexcept {
auto cnt = std::vsscanf(str, fmt, args);
if (cnt != static_cast<t_int>(n))
assert_now(P_cstr("scanf could not find you value(s)"));
}
t_void scan_fmt_(P_cstr_ str, t_n_ n, P_cstr_ fmt, ...) noexcept {
va_list args;
va_start(args, fmt);
scan_(str, n, fmt, args);
va_end(args);
}
///////////////////////////////////////////////////////////////////////////////
t_n_ skip_(R_crange range, t_char ch) noexcept {
t_n_ max = get(range.n);
if (max >= 1 && range[t_ix{0}] == ch)
return 1;
assert_now(P_cstr("can't skip charater"));
return 0;
}
t_n_ skip_(R_crange range, t_n_ n) noexcept {
t_n_ max = get(range.n);
if (n <= max)
return n;
assert_now(P_cstr("buffer not big enough"));
return 0;
}
t_n_ skip_(R_crange range, R_crange src) noexcept {
auto ix_begin = t_ix{0}, ix_end = t_ix{get(src.n)};
auto tmp = mk_range(range, ix_begin, ix_end);
if (tmp == src)
return get(src.n);
assert_now(P_cstr("range not the same"));
return 0;
}
t_n_ skip_(R_crange range, R_block block) noexcept {
auto max = get(range.n), n = get(block.max);
if (n <= max) {
t_ix_ ix = 0;
for (; ix < n && range[t_ix{ix}] == block.c; ++ix);
if (ix == n)
return n;
}
assert_now(P_cstr("range not the same"));
return 0;
}
t_n_ skip_until_(R_crange range, t_char ch, t_plus1_ plus1) noexcept {
auto max = get(range.n);
if (max) {
t_ix_ ix = 0;
for (; ix < max && range[t_ix{ix}] != ch; ++ix);
if (ix < max)
return ix + plus1;
}
assert_now(P_cstr("dont find char"));
return 0;
}
t_n_ skip_until_(R_crange range, R_crange value, t_plus1_ plus1) noexcept {
auto max = get(range.n), value_max = get(value.n);
if (max && max > value_max) {
t_ix_ ix = 0, k = 0;
for (; ix < max && k < value_max; ++ix)
k = range[t_ix{ix}] == value[t_ix{k}] ? k + 1 : 0;
if (k == value_max)
return plus1 == PLUS1 ? ix : ix - value_max;
}
assert_now(P_cstr("dont find substring"));
return 0;
}
t_n_ skip_all_(R_crange range, t_char ch) noexcept {
auto max = get(range.n);
if (max) {
t_ix_ ix = 0;
for (; ix < max && range[t_ix{ix}] == ch; ++ix);
if (ix <= max)
return ix;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
t_n_ snip_n_(R_crange range, p_snippet snip, t_n_ n) noexcept {
auto max = get(range.n);
if (max && max > n) {
*snip = range;
return max;
}
assert_now(P_cstr("not large enough"));
return 0;
}
t_n_ snip_char_(R_crange range, p_snippet snip, t_char ch,
t_plus1_ plus1, t_incl_char_ incl_char) noexcept {
auto max = get(range.n);
if (max) {
t_ix_ ix = 0;
for (; ix < max && range[t_ix{ix}] != ch; ++ix);
if (ix < max) {
*snip = t_crange{range.ptr, t_n{ix + incl_char}};
return ix + plus1;
}
}
assert_now(P_cstr("not found"));
return 0;
}
t_n_ snip_char_eol_(R_crange range, p_snippet snip, t_char ch,
t_plus1_ plus1, t_incl_char_ incl_char) noexcept {
auto max = get(range.n);
if (max) {
t_ix_ ix = 0;
for (; ix < max && range[t_ix{ix}] != ch; ++ix);
if (ix < max) {
*snip = t_crange{range.ptr, t_n{ix + incl_char}};
return ix + plus1;
}
*snip = range;
return max;
}
assert_now(P_cstr("not found"));
return 0;
}
t_n_ snip_char_(R_crange range, p_snippet snip, p_char_select select,
t_plus1_ plus1, t_incl_char_ incl_char) noexcept {
auto max = get(range.n);
if (max) {
t_ix_ ix = 0;
for (; ix < max; ++ix) {
for (t_char ch : select->range) {
if (range[t_ix{ix}] == ch) {
select->choice = ch;
*snip = t_crange{range.ptr, t_n{ix + incl_char}};
return ix + plus1;
}
}
}
}
select->choice = EOL;
return 0;
}
t_n_ snip_char_eol_(R_crange range, p_snippet snip, p_char_select select,
t_plus1_ plus1, t_incl_char_ incl_char) noexcept {
auto max = get(range.n);
if (max) {
t_ix_ ix = 0;
for (; ix < max; ++ix) {
for (t_char ch : select->range) {
if (range[t_ix{ix}] == ch) {
select->choice = ch;
*snip = t_crange{range.ptr, t_n{ix + incl_char}};
return ix + plus1;
}
}
}
select->choice = EOL;
*snip = range;
return max;
}
select->choice = EOL;
return 0;
}
///////////////////////////////////////////////////////////////////////////////
t_n_ shift_left_(p_cstr_ str, t_n_ max, t_n_ len, t_n_ width) noexcept {
t_n_ n = max - 1;
if (len < max) {
if (len <= width) {
if (width < max)
n = width;
for (t_ix_ ix = len; ix < n; ++ix)
str[ix] = ' ';
} else
n = width;
str[n] = '\0';
} else if (width < max) {
str[width] = '\0';
n = width;
}
return n;
}
t_n_ shift_right_(p_cstr_ str, t_n_ max, t_n_ len, t_n_ width) noexcept {
return len < max ? len : max - 1; // XXX do next
}
t_n_ shift_centre_(p_cstr_ str, t_n_ max, t_n_ len, t_n_ width) noexcept {
return shift_left_(str, max, len, width);
}
////////////////////////////////////////////////////////////////////////////////
}
}
}
| [
"frits.germs@gmx.net"
] | frits.germs@gmx.net |
bd12c88010fd45e3643b7d9deef11c275f83bbbb | fbe68d84e97262d6d26dd65c704a7b50af2b3943 | /third_party/virtualbox/src/VBox/Frontends/VirtualBox/src/widgets/UIPortForwardingTable.cpp | fb9faea0381911bed32f444e9881a2cc57c51759 | [
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"CDDL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"MPL-1.0",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"OpenSSL",
"MIT"
] | permissive | thalium/icebox | c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb | 6f78952d58da52ea4f0e55b2ab297f28e80c1160 | refs/heads/master | 2022-08-14T00:19:36.984579 | 2022-02-22T13:10:31 | 2022-02-22T13:10:31 | 190,019,914 | 585 | 109 | MIT | 2022-01-13T20:58:15 | 2019-06-03T14:18:12 | C++ | UTF-8 | C++ | false | false | 40,681 | cpp | /* $Id: UIPortForwardingTable.cpp $ */
/** @file
* VBox Qt GUI - UIPortForwardingTable class implementation.
*/
/*
* Copyright (C) 2010-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifdef VBOX_WITH_PRECOMPILED_HEADERS
# include <precomp.h>
#else /* !VBOX_WITH_PRECOMPILED_HEADERS */
/* Qt includes: */
# include <QHBoxLayout>
# include <QMenu>
# include <QAction>
# include <QHeaderView>
# include <QStyledItemDelegate>
# include <QItemEditorFactory>
# include <QComboBox>
# include <QLineEdit>
# include <QSpinBox>
/* GUI includes: */
# include "UIDesktopWidgetWatchdog.h"
# include "UIPortForwardingTable.h"
# include "UIMessageCenter.h"
# include "UIConverter.h"
# include "UIIconPool.h"
# include "UIToolBar.h"
# include "QITableView.h"
/* Other VBox includes: */
# include <iprt/cidr.h>
#endif /* !VBOX_WITH_PRECOMPILED_HEADERS */
/* External includes: */
#include <math.h>
#if 0 /* Decided to not use it for now. */
/* IPv4 validator: */
class IPv4Validator : public QValidator
{
Q_OBJECT;
public:
/* Constructor/destructor: */
IPv4Validator(QObject *pParent) : QValidator(pParent) {}
~IPv4Validator() {}
/* Handler: Validation stuff: */
QValidator::State validate(QString &strInput, int& /*iPos*/) const
{
QString strStringToValidate(strInput);
strStringToValidate.remove(' ');
QString strDot("\\.");
QString strDigits("(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)");
QRegExp intRegExp(QString("^(%1?(%2(%1?(%2(%1?(%2%1?)?)?)?)?)?)?$").arg(strDigits).arg(strDot));
RTNETADDRIPV4 Network, Mask;
if (strStringToValidate == "..." || RTCidrStrToIPv4(strStringToValidate.toLatin1().constData(), &Network, &Mask) == VINF_SUCCESS)
return QValidator::Acceptable;
else if (intRegExp.indexIn(strStringToValidate) != -1)
return QValidator::Intermediate;
else
return QValidator::Invalid;
}
};
/* IPv6 validator: */
class IPv6Validator : public QValidator
{
Q_OBJECT;
public:
/* Constructor/destructor: */
IPv6Validator(QObject *pParent) : QValidator(pParent) {}
~IPv6Validator() {}
/* Handler: Validation stuff: */
QValidator::State validate(QString &strInput, int& /*iPos*/) const
{
QString strStringToValidate(strInput);
strStringToValidate.remove(' ');
QString strDigits("([0-9a-fA-F]{0,4})");
QRegExp intRegExp(QString("^%1(:%1(:%1(:%1(:%1(:%1(:%1(:%1)?)?)?)?)?)?)?$").arg(strDigits));
if (intRegExp.indexIn(strStringToValidate) != -1)
return QValidator::Acceptable;
else
return QValidator::Invalid;
}
};
#endif /* Decided to not use it for now. */
/** Port Forwarding data types. */
enum UIPortForwardingDataType
{
UIPortForwardingDataType_Name,
UIPortForwardingDataType_Protocol,
UIPortForwardingDataType_HostIp,
UIPortForwardingDataType_HostPort,
UIPortForwardingDataType_GuestIp,
UIPortForwardingDataType_GuestPort,
UIPortForwardingDataType_Max
};
/* Name editor: */
class NameEditor : public QLineEdit
{
Q_OBJECT;
Q_PROPERTY(NameData name READ name WRITE setName USER true);
public:
/* Constructor: */
NameEditor(QWidget *pParent = 0) : QLineEdit(pParent)
{
setFrame(false);
setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
setValidator(new QRegExpValidator(QRegExp("[^,:]*"), this));
}
private:
/* API: Name stuff: */
void setName(NameData name)
{
setText(name);
}
/* API: Name stuff: */
NameData name() const
{
return text();
}
};
/* Protocol editor: */
class ProtocolEditor : public QComboBox
{
Q_OBJECT;
Q_PROPERTY(KNATProtocol protocol READ protocol WRITE setProtocol USER true);
public:
/* Constructor: */
ProtocolEditor(QWidget *pParent = 0) : QComboBox(pParent)
{
addItem(gpConverter->toString(KNATProtocol_UDP), QVariant::fromValue(KNATProtocol_UDP));
addItem(gpConverter->toString(KNATProtocol_TCP), QVariant::fromValue(KNATProtocol_TCP));
}
private:
/* API: Protocol stuff: */
void setProtocol(KNATProtocol p)
{
for (int i = 0; i < count(); ++i)
{
if (itemData(i).value<KNATProtocol>() == p)
{
setCurrentIndex(i);
break;
}
}
}
/* API: Protocol stuff: */
KNATProtocol protocol() const
{
return itemData(currentIndex()).value<KNATProtocol>();
}
};
/* IPv4 editor: */
class IPv4Editor : public QLineEdit
{
Q_OBJECT;
Q_PROPERTY(IpData ip READ ip WRITE setIp USER true);
public:
/* Constructor: */
IPv4Editor(QWidget *pParent = 0) : QLineEdit(pParent)
{
setFrame(false);
setAlignment(Qt::AlignCenter);
// Decided to not use it for now:
// setValidator(new IPv4Validator(this));
}
private:
/* API: IP stuff: */
void setIp(IpData ip)
{
setText(ip);
}
/* API: IP stuff: */
IpData ip() const
{
return text() == "..." ? QString() : text();
}
};
/* IPv6 editor: */
class IPv6Editor : public QLineEdit
{
Q_OBJECT;
Q_PROPERTY(IpData ip READ ip WRITE setIp USER true);
public:
/* Constructor: */
IPv6Editor(QWidget *pParent = 0) : QLineEdit(pParent)
{
setFrame(false);
setAlignment(Qt::AlignCenter);
// Decided to not use it for now:
// setValidator(new IPv6Validator(this));
}
private:
/* API: IP stuff: */
void setIp(IpData ip)
{
setText(ip);
}
/* API: IP stuff: */
IpData ip() const
{
return text() == "..." ? QString() : text();
}
};
/* Port editor: */
class PortEditor : public QSpinBox
{
Q_OBJECT;
Q_PROPERTY(PortData port READ port WRITE setPort USER true);
public:
/* Constructor: */
PortEditor(QWidget *pParent = 0) : QSpinBox(pParent)
{
setFrame(false);
setRange(0, (1 << (8 * sizeof(ushort))) - 1);
}
private:
/* API: Port stuff: */
void setPort(PortData port)
{
setValue(port.value());
}
/* API: Port stuff: */
PortData port() const
{
return value();
}
};
/** QITableViewCell extension used as Port Forwarding table-view cell. */
class UIPortForwardingCell : public QITableViewCell
{
Q_OBJECT;
public:
/** Constructs table cell passing @a pParent to the base-class.
* @param strName Brings the name. */
UIPortForwardingCell(QITableViewRow *pParent, const NameData &strName)
: QITableViewCell(pParent)
, m_strText(strName)
{}
/** Constructs table cell passing @a pParent to the base-class.
* @param enmProtocol Brings the protocol type. */
UIPortForwardingCell(QITableViewRow *pParent, KNATProtocol enmProtocol)
: QITableViewCell(pParent)
, m_strText(gpConverter->toString(enmProtocol))
{}
/** Constructs table cell passing @a pParent to the base-class.
* @param strIp Brings the IP address. */
UIPortForwardingCell(QITableViewRow *pParent, const IpData &strIP)
: QITableViewCell(pParent)
, m_strText(strIP)
{}
/** Constructs table cell passing @a pParent to the base-class.
* @param uHostPort Brings the port. */
UIPortForwardingCell(QITableViewRow *pParent, PortData uPort)
: QITableViewCell(pParent)
, m_strText(QString::number(uPort.value()))
{}
/** Returns the cell text. */
virtual QString text() const /* override */ { return m_strText; }
private:
/** Holds the cell text. */
QString m_strText;
};
/** QITableViewRow extension used as Port Forwarding table-view row. */
class UIPortForwardingRow : public QITableViewRow
{
Q_OBJECT;
public:
/** Constructs table row passing @a pParent to the base-class.
* @param strName Brings the unique rule name.
* @param enmProtocol Brings the rule protocol type.
* @param strHostIp Brings the rule host IP address.
* @param uHostPort Brings the rule host port.
* @param strGuestIp Brings the rule guest IP address.
* @param uGuestPort Brings the rule guest port. */
UIPortForwardingRow(QITableView *pParent,
const NameData &strName, KNATProtocol enmProtocol,
const IpData &strHostIp, PortData uHostPort,
const IpData &strGuestIp, PortData uGuestPort)
: QITableViewRow(pParent)
, m_strName(strName), m_enmProtocol(enmProtocol)
, m_strHostIp(strHostIp), m_uHostPort(uHostPort)
, m_strGuestIp(strGuestIp), m_uGuestPort(uGuestPort)
{
/* Create cells: */
createCells();
}
/** Destructs table row. */
~UIPortForwardingRow()
{
/* Destroy cells: */
destroyCells();
}
/** Returns the unique rule name. */
NameData name() const { return m_strName; }
/** Defines the unique rule name. */
void setName(const NameData &strName)
{
m_strName = strName;
delete m_cells[UIPortForwardingDataType_Name];
m_cells[UIPortForwardingDataType_Name] = new UIPortForwardingCell(this, m_strName);
}
/** Returns the rule protocol type. */
KNATProtocol protocol() const { return m_enmProtocol; }
/** Defines the rule protocol type. */
void setProtocol(KNATProtocol enmProtocol)
{
m_enmProtocol = enmProtocol;
delete m_cells[UIPortForwardingDataType_Protocol];
m_cells[UIPortForwardingDataType_Protocol] = new UIPortForwardingCell(this, m_enmProtocol);
}
/** Returns the rule host IP address. */
IpData hostIp() const { return m_strHostIp; }
/** Defines the rule host IP address. */
void setHostIp(const IpData &strHostIp)
{
m_strHostIp = strHostIp;
delete m_cells[UIPortForwardingDataType_HostIp];
m_cells[UIPortForwardingDataType_HostIp] = new UIPortForwardingCell(this, m_strHostIp);
}
/** Returns the rule host port. */
PortData hostPort() const { return m_uHostPort; }
/** Defines the rule host port. */
void setHostPort(PortData uHostPort)
{
m_uHostPort = uHostPort;
delete m_cells[UIPortForwardingDataType_HostPort];
m_cells[UIPortForwardingDataType_HostPort] = new UIPortForwardingCell(this, m_uHostPort);
}
/** Returns the rule guest IP address. */
IpData guestIp() const { return m_strGuestIp; }
/** Defines the rule guest IP address. */
void setGuestIp(const IpData &strGuestIp)
{
m_strGuestIp = strGuestIp;
delete m_cells[UIPortForwardingDataType_GuestIp];
m_cells[UIPortForwardingDataType_GuestIp] = new UIPortForwardingCell(this, m_strGuestIp);
}
/** Returns the rule guest port. */
PortData guestPort() const { return m_uGuestPort; }
/** Defines the rule guest port. */
void setGuestPort(PortData uGuestPort)
{
m_uGuestPort = uGuestPort;
delete m_cells[UIPortForwardingDataType_GuestPort];
m_cells[UIPortForwardingDataType_GuestPort] = new UIPortForwardingCell(this, m_uGuestPort);
}
protected:
/** Returns the number of children. */
virtual int childCount() const /* override */
{
/* Return cell count: */
return UIPortForwardingDataType_Max;
}
/** Returns the child item with @a iIndex. */
virtual QITableViewCell *childItem(int iIndex) const /* override */
{
/* Make sure index within the bounds: */
AssertReturn(iIndex >= 0 && iIndex < m_cells.size(), 0);
/* Return corresponding cell: */
return m_cells[iIndex];
}
private:
/** Creates cells. */
void createCells()
{
/* Create cells on the basis of variables we have: */
m_cells.resize(UIPortForwardingDataType_Max);
m_cells[UIPortForwardingDataType_Name] = new UIPortForwardingCell(this, m_strName);
m_cells[UIPortForwardingDataType_Protocol] = new UIPortForwardingCell(this, m_enmProtocol);
m_cells[UIPortForwardingDataType_HostIp] = new UIPortForwardingCell(this, m_strHostIp);
m_cells[UIPortForwardingDataType_HostPort] = new UIPortForwardingCell(this, m_uHostPort);
m_cells[UIPortForwardingDataType_GuestIp] = new UIPortForwardingCell(this, m_strGuestIp);
m_cells[UIPortForwardingDataType_GuestPort] = new UIPortForwardingCell(this, m_uGuestPort);
}
/** Destroys cells. */
void destroyCells()
{
/* Destroy cells: */
qDeleteAll(m_cells);
m_cells.clear();
}
/** Holds the unique rule name. */
NameData m_strName;
/** Holds the rule protocol type. */
KNATProtocol m_enmProtocol;
/** Holds the rule host IP address. */
IpData m_strHostIp;
/** Holds the rule host port. */
PortData m_uHostPort;
/** Holds the rule guest IP address. */
IpData m_strGuestIp;
/** Holds the rule guest port. */
PortData m_uGuestPort;
/** Holds the cell instances. */
QVector<UIPortForwardingCell*> m_cells;
};
/* Port forwarding data model: */
class UIPortForwardingModel : public QAbstractTableModel
{
Q_OBJECT;
public:
/** Constructs Port Forwarding model passing @a pParent to the base-class.
* @param rules Brings the list of port forwarding rules to load initially. */
UIPortForwardingModel(QITableView *pParent, const UIPortForwardingDataList &rules = UIPortForwardingDataList());
/** Destructs Port Forwarding model. */
~UIPortForwardingModel();
/** Returns the number of children. */
int childCount() const;
/** Returns the child item with @a iIndex. */
QITableViewRow *childItem(int iIndex) const;
/* API: Rule stuff: */
const UIPortForwardingDataList rules() const;
void addRule(const QModelIndex &index);
void delRule(const QModelIndex &index);
/* API: Index flag stuff: */
Qt::ItemFlags flags(const QModelIndex &index) const;
/* API: Index row-count stuff: */
int rowCount(const QModelIndex &parent = QModelIndex()) const;
/* API: Index column-count stuff: */
int columnCount(const QModelIndex &parent = QModelIndex()) const;
/* API: Header data stuff: */
QVariant headerData(int iSection, Qt::Orientation orientation, int iRole) const;
/* API: Index data stuff: */
QVariant data(const QModelIndex &index, int iRole) const;
bool setData(const QModelIndex &index, const QVariant &value, int iRole = Qt::EditRole);
private:
/** Return the parent table-view reference. */
QITableView *parentTable() const;
/* Variable: Data stuff: */
QList<UIPortForwardingRow*> m_dataList;
};
/** QITableView extension used as Port Forwarding table-view. */
class UIPortForwardingView : public QITableView
{
Q_OBJECT;
public:
/** Constructs Port Forwarding table-view. */
UIPortForwardingView() {}
protected:
/** Returns the number of children. */
virtual int childCount() const /* override */;
/** Returns the child item with @a iIndex. */
virtual QITableViewRow *childItem(int iIndex) const /* override */;
};
/*********************************************************************************************************************************
* Class UIPortForwardingModel implementation. *
*********************************************************************************************************************************/
UIPortForwardingModel::UIPortForwardingModel(QITableView *pParent, const UIPortForwardingDataList &rules /* = UIPortForwardingDataList() */)
: QAbstractTableModel(pParent)
{
/* Fetch the incoming data: */
foreach (const UIDataPortForwardingRule &rule, rules)
m_dataList << new UIPortForwardingRow(pParent,
rule.name, rule.protocol,
rule.hostIp, rule.hostPort,
rule.guestIp, rule.guestPort);
}
UIPortForwardingModel::~UIPortForwardingModel()
{
/* Delete the cached data: */
qDeleteAll(m_dataList);
m_dataList.clear();
}
int UIPortForwardingModel::childCount() const
{
/* Return row count: */
return rowCount();
}
QITableViewRow *UIPortForwardingModel::childItem(int iIndex) const
{
/* Make sure index within the bounds: */
AssertReturn(iIndex >= 0 && iIndex < m_dataList.size(), 0);
/* Return corresponding row: */
return m_dataList[iIndex];
}
const UIPortForwardingDataList UIPortForwardingModel::rules() const
{
/* Return the cached data: */
UIPortForwardingDataList data;
foreach (const UIPortForwardingRow *pRow, m_dataList)
data << UIDataPortForwardingRule(pRow->name(), pRow->protocol(),
pRow->hostIp(), pRow->hostPort(),
pRow->guestIp(), pRow->guestPort());
return data;
}
void UIPortForwardingModel::addRule(const QModelIndex &index)
{
beginInsertRows(QModelIndex(), m_dataList.size(), m_dataList.size());
/* Search for existing "Rule [NUMBER]" record: */
uint uMaxIndex = 0;
QString strTemplate("Rule %1");
QRegExp regExp(strTemplate.arg("(\\d+)"));
for (int i = 0; i < m_dataList.size(); ++i)
if (regExp.indexIn(m_dataList[i]->name()) > -1)
uMaxIndex = regExp.cap(1).toUInt() > uMaxIndex ? regExp.cap(1).toUInt() : uMaxIndex;
/* If index is valid => copy data: */
if (index.isValid())
m_dataList << new UIPortForwardingRow(parentTable(),
strTemplate.arg(++uMaxIndex), m_dataList[index.row()]->protocol(),
m_dataList[index.row()]->hostIp(), m_dataList[index.row()]->hostPort(),
m_dataList[index.row()]->guestIp(), m_dataList[index.row()]->guestPort());
/* If index is NOT valid => use default values: */
else
m_dataList << new UIPortForwardingRow(parentTable(),
strTemplate.arg(++uMaxIndex), KNATProtocol_TCP,
QString(""), 0, QString(""), 0);
endInsertRows();
}
void UIPortForwardingModel::delRule(const QModelIndex &index)
{
if (!index.isValid())
return;
beginRemoveRows(QModelIndex(), index.row(), index.row());
delete m_dataList.at(index.row());
m_dataList.removeAt(index.row());
endRemoveRows();
}
Qt::ItemFlags UIPortForwardingModel::flags(const QModelIndex &index) const
{
/* Check index validness: */
if (!index.isValid())
return Qt::NoItemFlags;
/* All columns have similar flags: */
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
int UIPortForwardingModel::rowCount(const QModelIndex&) const
{
return m_dataList.size();
}
int UIPortForwardingModel::columnCount(const QModelIndex&) const
{
return UIPortForwardingDataType_Max;
}
QVariant UIPortForwardingModel::headerData(int iSection, Qt::Orientation orientation, int iRole) const
{
/* Display role for horizontal header: */
if (iRole == Qt::DisplayRole && orientation == Qt::Horizontal)
{
/* Switch for different columns: */
switch (iSection)
{
case UIPortForwardingDataType_Name: return UIPortForwardingTable::tr("Name");
case UIPortForwardingDataType_Protocol: return UIPortForwardingTable::tr("Protocol");
case UIPortForwardingDataType_HostIp: return UIPortForwardingTable::tr("Host IP");
case UIPortForwardingDataType_HostPort: return UIPortForwardingTable::tr("Host Port");
case UIPortForwardingDataType_GuestIp: return UIPortForwardingTable::tr("Guest IP");
case UIPortForwardingDataType_GuestPort: return UIPortForwardingTable::tr("Guest Port");
default: break;
}
}
/* Return wrong value: */
return QVariant();
}
QVariant UIPortForwardingModel::data(const QModelIndex &index, int iRole) const
{
/* Check index validness: */
if (!index.isValid())
return QVariant();
/* Switch for different roles: */
switch (iRole)
{
/* Display role: */
case Qt::DisplayRole:
{
/* Switch for different columns: */
switch (index.column())
{
case UIPortForwardingDataType_Name: return m_dataList[index.row()]->name();
case UIPortForwardingDataType_Protocol: return gpConverter->toString(m_dataList[index.row()]->protocol());
case UIPortForwardingDataType_HostIp: return m_dataList[index.row()]->hostIp();
case UIPortForwardingDataType_HostPort: return m_dataList[index.row()]->hostPort().value();
case UIPortForwardingDataType_GuestIp: return m_dataList[index.row()]->guestIp();
case UIPortForwardingDataType_GuestPort: return m_dataList[index.row()]->guestPort().value();
default: return QVariant();
}
}
/* Edit role: */
case Qt::EditRole:
{
/* Switch for different columns: */
switch (index.column())
{
case UIPortForwardingDataType_Name: return QVariant::fromValue(m_dataList[index.row()]->name());
case UIPortForwardingDataType_Protocol: return QVariant::fromValue(m_dataList[index.row()]->protocol());
case UIPortForwardingDataType_HostIp: return QVariant::fromValue(m_dataList[index.row()]->hostIp());
case UIPortForwardingDataType_HostPort: return QVariant::fromValue(m_dataList[index.row()]->hostPort());
case UIPortForwardingDataType_GuestIp: return QVariant::fromValue(m_dataList[index.row()]->guestIp());
case UIPortForwardingDataType_GuestPort: return QVariant::fromValue(m_dataList[index.row()]->guestPort());
default: return QVariant();
}
}
/* Alignment role: */
case Qt::TextAlignmentRole:
{
/* Switch for different columns: */
switch (index.column())
{
case UIPortForwardingDataType_Name:
case UIPortForwardingDataType_Protocol:
case UIPortForwardingDataType_HostPort:
case UIPortForwardingDataType_GuestPort:
return (int)(Qt::AlignLeft | Qt::AlignVCenter);
case UIPortForwardingDataType_HostIp:
case UIPortForwardingDataType_GuestIp:
return Qt::AlignCenter;
default: return QVariant();
}
}
case Qt::SizeHintRole:
{
/* Switch for different columns: */
switch (index.column())
{
case UIPortForwardingDataType_HostIp:
case UIPortForwardingDataType_GuestIp:
return QSize(QApplication::fontMetrics().width(" 888.888.888.888 "), QApplication::fontMetrics().height());
default: return QVariant();
}
}
default: break;
}
/* Return wrong value: */
return QVariant();
}
bool UIPortForwardingModel::setData(const QModelIndex &index, const QVariant &value, int iRole /* = Qt::EditRole */)
{
/* Check index validness: */
if (!index.isValid() || iRole != Qt::EditRole)
return false;
/* Switch for different columns: */
switch (index.column())
{
case UIPortForwardingDataType_Name:
m_dataList[index.row()]->setName(value.value<NameData>());
emit dataChanged(index, index);
return true;
case UIPortForwardingDataType_Protocol:
m_dataList[index.row()]->setProtocol(value.value<KNATProtocol>());
emit dataChanged(index, index);
return true;
case UIPortForwardingDataType_HostIp:
m_dataList[index.row()]->setHostIp(value.value<IpData>());
emit dataChanged(index, index);
return true;
case UIPortForwardingDataType_HostPort:
m_dataList[index.row()]->setHostPort(value.value<PortData>());
emit dataChanged(index, index);
return true;
case UIPortForwardingDataType_GuestIp:
m_dataList[index.row()]->setGuestIp(value.value<IpData>());
emit dataChanged(index, index);
return true;
case UIPortForwardingDataType_GuestPort:
m_dataList[index.row()]->setGuestPort(value.value<PortData>());
emit dataChanged(index, index);
return true;
default: return false;
}
/* not reached! */
}
QITableView *UIPortForwardingModel::parentTable() const
{
return qobject_cast<QITableView*>(parent());
}
/*********************************************************************************************************************************
* Class UIPortForwardingView implementation. *
*********************************************************************************************************************************/
int UIPortForwardingView::childCount() const
{
/* Redirect request to table model: */
return qobject_cast<UIPortForwardingModel*>(model())->childCount();
}
QITableViewRow *UIPortForwardingView::childItem(int iIndex) const
{
/* Redirect request to table model: */
return qobject_cast<UIPortForwardingModel*>(model())->childItem(iIndex);
}
/*********************************************************************************************************************************
* Class UIPortForwardingTable implementation. *
*********************************************************************************************************************************/
UIPortForwardingTable::UIPortForwardingTable(const UIPortForwardingDataList &rules, bool fIPv6, bool fAllowEmptyGuestIPs)
: m_fAllowEmptyGuestIPs(fAllowEmptyGuestIPs)
, m_fIsTableDataChanged(false)
, m_pTableView(0)
, m_pToolBar(0)
, m_pModel(0)
, m_pAddAction(0)
, m_pCopyAction(0)
, m_pDelAction(0)
{
/* Create layout: */
QHBoxLayout *pMainLayout = new QHBoxLayout(this);
{
/* Configure layout: */
#ifdef VBOX_WS_MAC
/* On macOS we can do a bit of smoothness: */
pMainLayout->setContentsMargins(0, 0, 0, 0);
pMainLayout->setSpacing(3);
#else
pMainLayout->setSpacing(qApp->style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing) / 3);
#endif
/* Create table: */
m_pTableView = new UIPortForwardingView;
{
/* Configure table: */
m_pTableView->setTabKeyNavigation(false);
m_pTableView->verticalHeader()->hide();
m_pTableView->verticalHeader()->setDefaultSectionSize((int)(m_pTableView->verticalHeader()->minimumSectionSize() * 1.33));
m_pTableView->setSelectionMode(QAbstractItemView::SingleSelection);
m_pTableView->setContextMenuPolicy(Qt::CustomContextMenu);
m_pTableView->installEventFilter(this);
}
/* Create model: */
m_pModel = new UIPortForwardingModel(m_pTableView, rules);
{
/* Configure model: */
connect(m_pModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(sltTableDataChanged()));
connect(m_pModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(sltTableDataChanged()));
connect(m_pModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(sltTableDataChanged()));
/* Configure table (after model is configured): */
m_pTableView->setModel(m_pModel);
connect(m_pTableView, SIGNAL(sigCurrentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(sltCurrentChanged()));
connect(m_pTableView, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(sltShowTableContexMenu(const QPoint &)));
}
/* Create toolbar: */
m_pToolBar = new UIToolBar;
{
/* Determine icon metric: */
const QStyle *pStyle = QApplication::style();
const int iIconMetric = pStyle->pixelMetric(QStyle::PM_SmallIconSize);
/* Configure toolbar: */
m_pToolBar->setIconSize(QSize(iIconMetric, iIconMetric));
m_pToolBar->setOrientation(Qt::Vertical);
/* Create 'add' action: */
m_pAddAction = new QAction(this);
{
/* Configure 'add' action: */
m_pAddAction->setShortcut(QKeySequence("Ins"));
m_pAddAction->setIcon(UIIconPool::iconSet(":/controller_add_16px.png", ":/controller_add_disabled_16px.png"));
connect(m_pAddAction, SIGNAL(triggered(bool)), this, SLOT(sltAddRule()));
m_pToolBar->addAction(m_pAddAction);
}
/* Create 'copy' action: */
m_pCopyAction = new QAction(this);
{
/* Configure 'add' action: */
m_pCopyAction->setIcon(UIIconPool::iconSet(":/controller_add_16px.png", ":/controller_add_disabled_16px.png"));
connect(m_pCopyAction, SIGNAL(triggered(bool)), this, SLOT(sltCopyRule()));
}
/* Create 'del' action: */
m_pDelAction = new QAction(this);
{
/* Configure 'del' action: */
m_pDelAction->setShortcut(QKeySequence("Del"));
m_pDelAction->setIcon(UIIconPool::iconSet(":/controller_remove_16px.png", ":/controller_remove_disabled_16px.png"));
connect(m_pDelAction, SIGNAL(triggered(bool)), this, SLOT(sltDelRule()));
m_pToolBar->addAction(m_pDelAction);
}
}
/* Add widgets into layout: */
pMainLayout->addWidget(m_pTableView);
pMainLayout->addWidget(m_pToolBar);
}
/* We do have abstract item delegate: */
QAbstractItemDelegate *pAbstractItemDelegate = m_pTableView->itemDelegate();
if (pAbstractItemDelegate)
{
/* But do we have styled item delegate? */
QStyledItemDelegate *pStyledItemDelegate = qobject_cast<QStyledItemDelegate*>(pAbstractItemDelegate);
if (pStyledItemDelegate)
{
/* Create new item editor factory: */
QItemEditorFactory *pNewItemEditorFactory = new QItemEditorFactory;
{
/* Register NameEditor as the NameData editor: */
int iNameId = qRegisterMetaType<NameData>();
QStandardItemEditorCreator<NameEditor> *pNameEditorItemCreator = new QStandardItemEditorCreator<NameEditor>();
pNewItemEditorFactory->registerEditor((QVariant::Type)iNameId, pNameEditorItemCreator);
/* Register ProtocolEditor as the KNATProtocol editor: */
int iProtocolId = qRegisterMetaType<KNATProtocol>();
QStandardItemEditorCreator<ProtocolEditor> *pProtocolEditorItemCreator = new QStandardItemEditorCreator<ProtocolEditor>();
pNewItemEditorFactory->registerEditor((QVariant::Type)iProtocolId, pProtocolEditorItemCreator);
/* Register IPv4Editor/IPv6Editor as the IpData editor: */
int iIpId = qRegisterMetaType<IpData>();
if (!fIPv6)
{
QStandardItemEditorCreator<IPv4Editor> *pIPv4EditorItemCreator = new QStandardItemEditorCreator<IPv4Editor>();
pNewItemEditorFactory->registerEditor((QVariant::Type)iIpId, pIPv4EditorItemCreator);
}
else
{
QStandardItemEditorCreator<IPv6Editor> *pIPv6EditorItemCreator = new QStandardItemEditorCreator<IPv6Editor>();
pNewItemEditorFactory->registerEditor((QVariant::Type)iIpId, pIPv6EditorItemCreator);
}
/* Register PortEditor as the PortData editor: */
int iPortId = qRegisterMetaType<PortData>();
QStandardItemEditorCreator<PortEditor> *pPortEditorItemCreator = new QStandardItemEditorCreator<PortEditor>();
pNewItemEditorFactory->registerEditor((QVariant::Type)iPortId, pPortEditorItemCreator);
/* Set newly created item editor factory for table delegate: */
pStyledItemDelegate->setItemEditorFactory(pNewItemEditorFactory);
}
}
}
/* Retranslate dialog: */
retranslateUi();
/* Limit the minimum size to 33% of screen size: */
setMinimumSize(gpDesktop->screenGeometry(this).size() / 3);
}
const UIPortForwardingDataList UIPortForwardingTable::rules() const
{
return m_pModel->rules();
}
bool UIPortForwardingTable::validate() const
{
/* Validate table: */
QList<NameData> names;
QList<UIPortForwardingDataUnique> rules;
for (int i = 0; i < m_pModel->rowCount(); ++i)
{
/* Some of variables: */
const NameData name = m_pModel->data(m_pModel->index(i, UIPortForwardingDataType_Name), Qt::EditRole).value<NameData>();
const KNATProtocol protocol = m_pModel->data(m_pModel->index(i, UIPortForwardingDataType_Protocol), Qt::EditRole).value<KNATProtocol>();
const PortData hostPort = m_pModel->data(m_pModel->index(i, UIPortForwardingDataType_HostPort), Qt::EditRole).value<PortData>().value();
const PortData guestPort = m_pModel->data(m_pModel->index(i, UIPortForwardingDataType_GuestPort), Qt::EditRole).value<PortData>().value();
const IpData hostIp = m_pModel->data(m_pModel->index(i, UIPortForwardingDataType_HostIp), Qt::EditRole).value<IpData>();
const IpData guestIp = m_pModel->data(m_pModel->index(i, UIPortForwardingDataType_GuestIp), Qt::EditRole).value<IpData>();
/* If at least one port is 'zero': */
if (hostPort.value() == 0 || guestPort.value() == 0)
return msgCenter().warnAboutIncorrectPort(window());
/* If at least one address is incorrect: */
if (!( hostIp.trimmed().isEmpty()
|| RTNetIsIPv4AddrStr(hostIp.toUtf8().constData())
|| RTNetIsIPv6AddrStr(hostIp.toUtf8().constData())
|| RTNetStrIsIPv4AddrAny(hostIp.toUtf8().constData())
|| RTNetStrIsIPv6AddrAny(hostIp.toUtf8().constData())))
return msgCenter().warnAboutIncorrectAddress(window());
if (!( guestIp.trimmed().isEmpty()
|| RTNetIsIPv4AddrStr(guestIp.toUtf8().constData())
|| RTNetIsIPv6AddrStr(guestIp.toUtf8().constData())
|| RTNetStrIsIPv4AddrAny(guestIp.toUtf8().constData())
|| RTNetStrIsIPv6AddrAny(guestIp.toUtf8().constData())))
return msgCenter().warnAboutIncorrectAddress(window());
/* If empty guest address is not allowed: */
if ( !m_fAllowEmptyGuestIPs
&& guestIp.isEmpty())
return msgCenter().warnAboutEmptyGuestAddress(window());
/* Make sure non of the names were previosly used: */
if (!names.contains(name))
names << name;
else
return msgCenter().warnAboutNameShouldBeUnique(window());
/* Make sure non of the rules were previosly used: */
UIPortForwardingDataUnique rule(protocol, hostPort, hostIp);
if (!rules.contains(rule))
rules << rule;
else
return msgCenter().warnAboutRulesConflict(window());
}
/* True by default: */
return true;
}
void UIPortForwardingTable::makeSureEditorDataCommitted()
{
m_pTableView->makeSureEditorDataCommitted();
}
void UIPortForwardingTable::sltAddRule()
{
m_pModel->addRule(QModelIndex());
m_pTableView->setFocus();
m_pTableView->setCurrentIndex(m_pModel->index(m_pModel->rowCount() - 1, 0));
sltCurrentChanged();
sltAdjustTable();
}
void UIPortForwardingTable::sltCopyRule()
{
m_pModel->addRule(m_pTableView->currentIndex());
m_pTableView->setFocus();
m_pTableView->setCurrentIndex(m_pModel->index(m_pModel->rowCount() - 1, 0));
sltCurrentChanged();
sltAdjustTable();
}
void UIPortForwardingTable::sltDelRule()
{
m_pModel->delRule(m_pTableView->currentIndex());
m_pTableView->setFocus();
sltCurrentChanged();
sltAdjustTable();
}
void UIPortForwardingTable::sltCurrentChanged()
{
bool fTableFocused = m_pTableView->hasFocus();
bool fTableChildFocused = m_pTableView->findChildren<QWidget*>().contains(QApplication::focusWidget());
bool fTableOrChildFocused = fTableFocused || fTableChildFocused;
m_pCopyAction->setEnabled(m_pTableView->currentIndex().isValid() && fTableOrChildFocused);
m_pDelAction->setEnabled(m_pTableView->currentIndex().isValid() && fTableOrChildFocused);
}
void UIPortForwardingTable::sltShowTableContexMenu(const QPoint &pos)
{
/* Prepare context menu: */
QMenu menu(m_pTableView);
/* If some index is currently selected: */
if (m_pTableView->indexAt(pos).isValid())
{
menu.addAction(m_pCopyAction);
menu.addAction(m_pDelAction);
}
/* If no valid index selected: */
else
{
menu.addAction(m_pAddAction);
}
menu.exec(m_pTableView->viewport()->mapToGlobal(pos));
}
void UIPortForwardingTable::sltAdjustTable()
{
m_pTableView->horizontalHeader()->setStretchLastSection(false);
/* If table is NOT empty: */
if (m_pModel->rowCount())
{
/* Resize table to contents size-hint and emit a spare place for first column: */
m_pTableView->resizeColumnsToContents();
uint uFullWidth = m_pTableView->viewport()->width();
for (uint u = 1; u < UIPortForwardingDataType_Max; ++u)
uFullWidth -= m_pTableView->horizontalHeader()->sectionSize(u);
m_pTableView->horizontalHeader()->resizeSection(UIPortForwardingDataType_Name, uFullWidth);
}
/* If table is empty: */
else
{
/* Resize table columns to be equal in size: */
uint uFullWidth = m_pTableView->viewport()->width();
for (uint u = 0; u < UIPortForwardingDataType_Max; ++u)
m_pTableView->horizontalHeader()->resizeSection(u, uFullWidth / UIPortForwardingDataType_Max);
}
m_pTableView->horizontalHeader()->setStretchLastSection(true);
}
void UIPortForwardingTable::retranslateUi()
{
/* Table translations: */
m_pTableView->setWhatsThis(tr("Contains a list of port forwarding rules."));
/* Set action's text: */
m_pAddAction->setText(tr("Add New Rule"));
m_pCopyAction->setText(tr("Copy Selected Rule"));
m_pDelAction->setText(tr("Remove Selected Rule"));
m_pAddAction->setWhatsThis(tr("Adds new port forwarding rule."));
m_pCopyAction->setWhatsThis(tr("Copies selected port forwarding rule."));
m_pDelAction->setWhatsThis(tr("Removes selected port forwarding rule."));
m_pAddAction->setToolTip(m_pAddAction->whatsThis());
m_pCopyAction->setToolTip(m_pCopyAction->whatsThis());
m_pDelAction->setToolTip(m_pDelAction->whatsThis());
}
bool UIPortForwardingTable::eventFilter(QObject *pObject, QEvent *pEvent)
{
/* Process table: */
if (pObject == m_pTableView)
{
/* Process different event-types: */
switch (pEvent->type())
{
case QEvent::Show:
case QEvent::Resize:
{
/* Adjust table: */
sltAdjustTable();
break;
}
case QEvent::FocusIn:
case QEvent::FocusOut:
{
/* Update actions: */
sltCurrentChanged();
break;
}
default:
break;
}
}
/* Call to base-class: */
return QIWithRetranslateUI<QWidget>::eventFilter(pObject, pEvent);
}
#include "UIPortForwardingTable.moc"
| [
"benoit.amiaux@gmail.com"
] | benoit.amiaux@gmail.com |
e0b2b578d7186d9cc467960c70ba031495473fc3 | c8aabef59c82ae90ab9c17f6128402206b00621d | /ProBendingx64/ProBendingx64/RadialProgressBar.h | 05cb0347e01971ffec2685ac314dd1d1dc95c41e | [] | no_license | VagabondOfHell/ProBending | adfff4171b6ea99be87c05870c043afe181f1fcb | 6add107a012b46879ed6da10af2fe4dff368ae51 | refs/heads/master | 2021-01-17T11:29:42.393695 | 2016-04-08T01:04:05 | 2016-04-08T01:04:05 | 24,268,458 | 1 | 0 | null | 2015-04-21T02:50:28 | 2014-09-20T16:51:18 | C++ | UTF-8 | C++ | false | false | 651 | h | #pragma once
#include <string>
namespace CEGUI
{
class Window;
};
class RadialProgressBar
{
private:
CEGUI::Window* window;
unsigned int progress;
std::string currImageName;
void UpdateWindow();
public:
RadialProgressBar(void);
RadialProgressBar(CEGUI::Window* _window);
~RadialProgressBar(void);
void SetWindow(CEGUI::Window* newWindow){window = newWindow;}
CEGUI::Window* GetWindow()const{return window;}
void Show();
void Hide();
void IncrementProgress(unsigned int value);
void DecrementProgress(unsigned int value);
void SetProgress(unsigned int value);
void SetAbsolutePosition(float x, float y);
void Reset();
};
| [
"arrow_m13@hotmail.com"
] | arrow_m13@hotmail.com |
1362b5a42a5a50288f3ecc75cc6f776328b73d90 | 44eb4b7c9cb8891cb3544936c7bbf8536eb2714c | /src/232.cpp | 1a5eba8e626a0ac4bc2c0141f13dd81e644499a3 | [] | no_license | xf97/myLeetCodeSolutions | 7a330089e14c6d44a0de0de8b034f2a759c17348 | 5de6aa3977117e59ef69307894e163351b1d88fa | refs/heads/master | 2023-08-18T09:27:09.900780 | 2021-10-18T04:44:36 | 2021-10-18T04:44:36 | 291,883,909 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,179 | cpp | class MyQueue {
/*
time defeat: 100%
space defeat: 74.23%
*/
private:
stack<int> mainStack; //用来实现先入先出操作的主栈
stack<int> cacheStack; //用来缓存元素的缓存栈
public:
/** Initialize your data structure here. */
MyQueue() {
//可以不做吧
}
/** Push element x to the back of queue. */
void push(int x) {
//只向主栈推入元素
mainStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int topNum = 0, tempNum = 0;
//把主栈中的元素都转移到缓存栈去
while(mainStack.size() != 1){
topNum = mainStack.top(); //获得栈顶元素
cacheStack.emplace(topNum); //压入缓存
mainStack.pop(); //弹出
}
//然后记录当前的最前元素
topNum = mainStack.top();
mainStack.pop();
//然后再从缓存栈压回去
while(!cacheStack.empty()){
tempNum = cacheStack.top();
mainStack.emplace(tempNum);
cacheStack.pop();
}
return topNum;
}
/** Get the front element. */
int peek() {
int topNum = 0, tempNum = 0;
//把主栈中的元素都转移到缓存栈去
while(mainStack.size() != 1){
topNum = mainStack.top(); //获得栈顶元素
cacheStack.emplace(topNum); //压入缓存
mainStack.pop(); //弹出
}
//然后记录当前的最前元素
topNum = mainStack.top();
//然后再从缓存栈压回去
while(!cacheStack.empty()){
tempNum = cacheStack.top();
mainStack.emplace(tempNum);
cacheStack.pop();
}
return topNum;
}
/** Returns whether the queue is empty. */
bool empty() {
return mainStack.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
| [
"noreply@github.com"
] | noreply@github.com |
3db0d8a5a5ff3cce431e707167e976a613a869dc | abc7a9f3cfcc401b5bcd18b2fd8987409fd4613b | /scene_drawings.h | e8547f0760b7470d4ed2f9b20dc06edaac4a19bd | [] | no_license | mvachovski/tower_destruction-lighting | d9f39b4632b40566668dae68885f0988d2bf36e6 | 614debe08c10fbf23e9edb0c7fa1a09a56147c03 | refs/heads/master | 2021-01-20T11:00:11.693253 | 2016-06-19T23:55:00 | 2016-06-19T23:55:00 | 61,505,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | /*
* scene_drawings.h
*
* Created on: 11.10.2015 г.
* Author: martin
*/
#ifndef SCENE_DRAWINGS_H_
#define SCENE_DRAWINGS_H_
#include "PhysicalWorld.h"
extern PhysicalWorld world;
namespace opengl_scene {
void initGLScene();
void drawScene();
void resize (int w, int h);
void keyInput(unsigned char key, int x, int y);
void specialKeyInput(int key, int x, int y);
void timer_function(int value);
void idle_function();
void drawPrimitive(btCollisionObject *p);
void drawCoordinateSystem();
}
#endif /* SCENE_DRAWINGS_H_ */
| [
"martin.vachovski@gmail.com"
] | martin.vachovski@gmail.com |
5b5ef98e3021a21525d3969ca08fd514d942141e | 8dfc324dcea5fb8bdb304c307935338122531f7f | /solution/Deque/10866.cpp | 716a041a4fdfb758b71b5dc6904d893cf012b717 | [] | no_license | inpyeong/baekjoon | 407444f8f5bdf1e9df94d71f84455ee37dd00dc1 | 55465c62c5eb64305cb106dd7d7767d452d72c31 | refs/heads/master | 2022-12-05T18:53:05.000807 | 2020-08-25T16:15:10 | 2020-08-25T16:15:10 | 263,879,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,173 | cpp | //#include <iostream>
//#include <deque>
//#include <string>
//
//using namespace std;
//
//int main10866() {
// int N, X;
// string cmd;
// deque <int> dq;
//
// cin >> N;
// while (N--) {
// cin >> cmd;
// if (cmd == "push_front") {
// cin >> X;
// dq.push_front(X);
// }
// else if (cmd == "push_back") {
// cin >> X;
// dq.push_back(X);
// }
// else if (cmd == "pop_front") {
// if (dq.empty()) {
// cout << "-1\n";
// continue;
// }
// cout << dq.front() << "\n";
// dq.pop_front();
// }
// else if (cmd == "pop_back") {
// if (dq.empty()) {
// cout << "-1\n";
// continue;
// }
// cout << dq.back() << "\n";
// dq.pop_back();
// }
// else if (cmd == "size") {
// cout << dq.size() << "\n";
// }
// else if (cmd == "empty") {
// if (dq.empty()) {
// cout << "1\n";
// }
// else {
// cout << "0\n";
// }
// }
// else if (cmd == "front") {
// if (dq.empty()) {
// cout << "-1\n";
// continue;
// }
// cout << dq.front() << "\n";
// }
// else if (cmd == "back") {
// if (dq.empty()) {
// cout << "-1\n";
// continue;
// }
// cout << dq.back() << "\n";
// }
// }
// return 0;
//} | [
"jinipyung@gmail.com"
] | jinipyung@gmail.com |
a88f41f17525ea91f46eab61838b6e6bc8fbfa6d | b2f8455b80b95d5a74728dbc42071431519c7c12 | /CommandPattern/Commands/StereoOnCommand.cpp | c3cf1cc3f124589bcbdcd103f4bc126675a1e8d2 | [] | no_license | rintujrajan/DesignPattern | 9e0fc438e334100f9ed22bff2c88a09cab707c99 | 3235c669fb629dec36bd8c732d28ef25d07d8de0 | refs/heads/master | 2021-07-04T04:46:54.882961 | 2021-04-26T15:31:30 | 2021-04-26T15:31:30 | 233,381,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cpp | #include "StereoOnCommand.h"
#include <iostream>
StereoOnCommand::StereoOnCommand(Stereo stereo)
{
this->stereo = stereo;
}
void StereoOnCommand::execute()
{
stereo.playCD();
std::cout<<stereo;
}
void StereoOnCommand::undoCommand()
{
stereo.off();
std::cout<<stereo;
} | [
"rintujrajan90@gmail.com"
] | rintujrajan90@gmail.com |
de4ae7287bdcbb3922ed4c099af86f251f9a57af | 724a021aa7449916a9b620000aa9daca0ab4fb7a | /src/RunData12.cxx | 63b2494e93e1093a1643f019937b3da59fd40953 | [] | no_license | c-dilks/spin12t | 73fa015b8629704023b36f5b7cc18f26e2421ce2 | 20bbfb3aa2470cb772dae1fb04dcf6085b23ee97 | refs/heads/master | 2020-06-09T00:21:49.234826 | 2014-08-11T21:36:54 | 2014-08-11T21:36:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,679 | cxx | #include "RunData12.h"
using namespace std;
ClassImp(RunData12)
RunData12::RunData12()
{
Construct("");
};
RunData12::RunData12(char * spindir0)
{
Construct(spindir0);
};
void RunData12::Construct(char * spindir0)
{
// define maxes
NRUNS = sizeof(runnum_map)/sizeof(*runnum_map);
NFILLS = sizeof(b_pol_map)/sizeof(*b_pol_map);
printf("Loop Maxes: NRUNS=%d NFILLS=%d\n",NRUNS,NFILLS);
// read trees
//char spindir[256];
char counts_file[256];
char rtree_file[256];
char pol_file[256];
if(!strcmp(spindir0,""))
{
if(gSystem->Getenv("SPINDIR")==NULL){fprintf(stderr,"ERROR: source env vars\n");return;};
sscanf(gSystem->Getenv("SPINDIR"),"%s",spindir);
}
else strcpy(spindir,spindir0);
printf("spindir=%s\n",spindir);
sprintf(counts_file,"%s/counts.root",spindir);
sprintf(rtree_file,"%s/rtree.root",spindir);
sprintf(pol_file,"%s/pol.root",spindir);
counts = new TFile(counts_file,"READ");
rtree = new TFile(rtree_file,"READ");
pol = new TFile(pol_file,"READ");
counts_tr = (TTree*) counts->Get("sca");
rtree_tr = (TTree*) rtree->Get("rellum");
pol_tr = (TTree*) pol->Get("pol");
// set rtree branch addresses
rtree_tr->SetBranchAddress("i",&i_rtree);
rtree_tr->SetBranchAddress("runnum",&runnum);
rtree_tr->SetBranchAddress("fill",&fill_rtree);
rtree_tr->SetBranchAddress("t",&t);
rtree_tr->SetBranchAddress("isConsistent",&isConsistent);
rtree_tr->SetBranchAddress("pattern",&pattern_no);
char R_bbc_name[10][16];
char R_zdc_name[10][16];
char R_vpd_name[10][16];
char R_bbc_err_name[10][16];
char R_zdc_err_name[10][16];
char R_vpd_err_name[10][16];
for(Int_t r=1; r<10; r++)
{
sprintf(R_bbc_name[r],"R%d_bbc_mean",r);
sprintf(R_zdc_name[r],"R%d_zdc_mean",r);
sprintf(R_vpd_name[r],"R%d_vpd_mean",r);
rtree_tr->SetBranchAddress(R_bbc_name[r],&(R_bbc[r]));
rtree_tr->SetBranchAddress(R_zdc_name[r],&(R_zdc[r]));
rtree_tr->SetBranchAddress(R_vpd_name[r],&(R_vpd[r]));
sprintf(R_bbc_err_name[r],"R%d_bbc_mean_err",r);
sprintf(R_zdc_err_name[r],"R%d_zdc_mean_err",r);
sprintf(R_vpd_err_name[r],"R%d_vpd_mean_err",r);
rtree_tr->SetBranchAddress(R_bbc_err_name[r],&(R_bbc_err[r]));
rtree_tr->SetBranchAddress(R_zdc_err_name[r],&(R_zdc_err[r]));
rtree_tr->SetBranchAddress(R_vpd_err_name[r],&(R_vpd_err[r]));
};
rtree_tr->SetBranchAddress("scarat",scarat_arr);
// set counts tree branch addresses
counts_tr->SetBranchAddress("i",&i_counts);
counts_tr->SetBranchAddress("bx",&bx);
counts_tr->SetBranchAddress("blue",&blue);
counts_tr->SetBranchAddress("yell",&yell);
counts_tr->SetBranchAddress("kicked",&kicked);
// set pol tree branch addresses
pol_tr->SetBranchAddress("fill",&fill_pol);
pol_tr->SetBranchAddress("b_pol",&b_pol);
pol_tr->SetBranchAddress("y_pol",&y_pol);
pol_tr->SetBranchAddress("b_pol_e",&b_pol_err);
pol_tr->SetBranchAddress("y_pol_e",&y_pol_err);
// build spin maps --> gives blue/yell spin + kicked status for
// any given run index and bXing no.
for(Int_t q=0; q<NRUNS; q++)
{
for(Int_t qq=0; qq<120; qq++)
{
blue_spin_map[q][qq]=0;
yell_spin_map[q][qq]=0;
kicked_bx_map[q][qq]=0;
}
runnum_map[q]=0;
};
for(Int_t q=0; q<counts_tr->GetEntries(); q++)
{
counts_tr->GetEntry(q);
blue_spin_map[i_counts-1][bx] = blue;
yell_spin_map[i_counts-1][bx] = yell;
if(kicked) kicked_bx_map[i_counts-1][bx] = 1;
else kicked_bx_map[i_counts-1][bx] = 0;
};
printf("spin maps built\n");
// build run number hash table and spin pattern map
// -- rtree tree is viewed as a hash table indexed by tree entry number
// -- run index - 1 = rtree entry number
Int_t runnum_tmp=0;
fill_thou=16000; // run12
for(Int_t q=0; q<rtree_tr->GetEntries(); q++)
{
rtree_tr->GetEntry(q);
if(runnum_tmp == runnum)
{
fprintf(stderr,"ERROR: duplicated run number\n");
return;
}
else runnum_tmp = runnum;
if(q != i_rtree-1)
{
fprintf(stderr,"ERROR: rdat tree not synced with hashing algorithm assumptions\n");
return;
}
else runnum_map[q] = runnum;
pattern_map[fill_rtree-fill_thou] = pattern_no;
};
printf("hash table ok\n");
// build polarimetry map
for(Int_t q=0; q<NFILLS; q++)
{
b_pol_map[q]=0;
y_pol_map[q]=0;
b_pol_err_map[q]=0;
y_pol_err_map[q]=0;
};
for(Int_t q=0; q<pol_tr->GetEntries(); q++)
{
pol_tr->GetEntry(q);
if(fill_pol-fill_thou >= 0 && fill_pol-fill_thou < NFILLS)
{
b_pol_map[fill_pol-fill_thou] = b_pol;
y_pol_map[fill_pol-fill_thou] = y_pol;
b_pol_err_map[fill_pol-fill_thou] = b_pol_err;
y_pol_err_map[fill_pol-fill_thou] = y_pol_err;
}
else
{
fprintf(stderr,"ERROR: variable fill_thou is not correct\n");
return;
};
};
printf("polarimetry map built\n");
}
Int_t RunData12::GetFill(Int_t runnum0)
{
Int_t set;
Int_t found=0;
for(Int_t q=0; q<NRUNS; q++)
{
if(runnum0 == runnum_map[q])
{
set=q;
found=1;
};
};
rtree_tr->GetEntry(set);
return found*fill_rtree;
}
Int_t RunData12::HashRun(Int_t runnum0)
{
// linear hashing
// -- returns "-1" if hashing fails
for(Int_t q=0; q<NRUNS; q++)
{
if(runnum_map[q] == runnum0) return q;
}
return -1;
};
Float_t RunData12::Rellum(Int_t runnum0, Int_t rellumi, char * detector)
{
Int_t index = HashRun(runnum0);
if(index>=0)
{
rtree_tr->GetEntry(index);
if(!strcmp(detector,"bbc")) return R_bbc[rellumi];
else if(!strcmp(detector,"zdc")) return R_zdc[rellumi];
else if(!strcmp(detector,"vpd")) return R_vpd[rellumi];
else
{
fprintf(stderr,"ERROR: invalid detector\n");
return 0;
}
}
else return 0;
};
Float_t RunData12::RellumErr(Int_t runnum0, Int_t rellumi, char * detector)
{
Int_t index = HashRun(runnum0);
if(index>=0)
{
rtree_tr->GetEntry(index);
if(!strcmp(detector,"bbc")) return R_bbc_err[rellumi];
else if(!strcmp(detector,"zdc")) return R_zdc_err[rellumi];
else if(!strcmp(detector,"vpd")) return R_vpd_err[rellumi];
else
{
fprintf(stderr,"ERROR: invalid detector\n");
return 0;
}
}
else return 0;
};
Bool_t RunData12::RellumConsistent(Int_t runnum0)
{
Int_t index = HashRun(runnum0);
if(index>=0)
{
rtree_tr->GetEntry(index);
return isConsistent;
}
else return 0;
};
Float_t RunData12::BluePol(Int_t runnum0)
{
Int_t fill0 = GetFill(runnum0);
if(fill0>fill_thou)
return b_pol_map[fill0-fill_thou];
else return 0;
}
Float_t RunData12::YellPol(Int_t runnum0)
{
Int_t fill0 = GetFill(runnum0);
if(fill0>fill_thou)
return y_pol_map[fill0-fill_thou];
else return 0;
}
Float_t RunData12::BluePolErr(Int_t runnum0)
{
Int_t fill0 = GetFill(runnum0);
if(fill0>fill_thou)
return b_pol_err_map[fill0-fill_thou];
else return 0;
}
Float_t RunData12::YellPolErr(Int_t runnum0)
{
Int_t fill0 = GetFill(runnum0);
if(fill0>fill_thou)
return y_pol_err_map[fill0-fill_thou];
else return 0;
}
Int_t RunData12::BlueSpin(Int_t runnum0, Int_t bXing)
{
Int_t index = HashRun(runnum0);
if(bXing>=0 && bXing<120) return blue_spin_map[index][bXing];
else
{
fprintf(stderr,"bXing out of range\n");
return 0;
};
};
Int_t RunData12::YellSpin(Int_t runnum0, Int_t bXing)
{
Int_t index = HashRun(runnum0);
if(bXing>=0 && bXing<120) return yell_spin_map[index][bXing];
else
{
fprintf(stderr,"bXing out of range\n");
return 0;
};
};
Bool_t RunData12::Kicked(Int_t runnum0, Int_t bXing)
{
Int_t index = HashRun(runnum0);
if(bXing>=0 && bXing<120) return kicked_bx_map[index][bXing];
else
{
fprintf(stderr,"bXing out of range\n");
return 0;
};
};
Int_t RunData12::Pattern(Int_t runnum0)
{
Int_t fill0 = GetFill(runnum0);
if(fill0>fill_thou)
return pattern_map[fill0-fill_thou];
else return 0;
};
Float_t RunData12::Scarat(Int_t runnum0, char * bit_combo, Int_t spinbit)
{
Int_t index = HashRun(runnum0);
Int_t bit_int;
if(index>=0)
{
rtree_tr->GetEntry(index);
if(!strcmp(bit_combo,"e")) bit_int = 0;
else if(!strcmp(bit_combo,"w")) bit_int = 1;
else if(!strcmp(bit_combo,"x")) bit_int = 2;
else
{
fprintf(stderr,"ERROR: incorrect scaler bit combination (must be e,w,x)\n");
return 0;
};
if(spinbit>=0 && spinbit<=3) return scarat_arr[bit_int][spinbit];
else
{
fprintf(stderr,"ERROR: spinbit out of range\n");
return 0;
};
}
else
{
fprintf(stderr,"ERROR: run number not found\n");
return 0;
};
};
| [
"christopher.j.dilks@gmail.com"
] | christopher.j.dilks@gmail.com |
674e28be1967d4c939d324689fa914e997dfd3c3 | 0103ce0fa860abd9f76cfda4979d304d450aba25 | /Source/WebKit/UIProcess/wpe/WebPasteboardProxyWPE.cpp | 8d3d0eb46d42a6f2a4b11d1f8ee35009adfe8b52 | [] | no_license | 1C-Company-third-party/webkit | 2dedcae3b5424dd5de1fee6151cd33b35d08567f | f7eec5c68105bea4d4a1dca91734170bdfd537b6 | refs/heads/master | 2022-11-08T12:23:55.380720 | 2019-04-18T12:13:32 | 2019-04-18T12:13:32 | 182,072,953 | 5 | 2 | null | 2022-10-18T10:56:03 | 2019-04-18T11:10:56 | C++ | UTF-8 | C++ | false | false | 2,155 | cpp | /*
* Copyright (C) 2015 Igalia S.L.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebPasteboardProxy.h"
#include <WebCore/PlatformPasteboard.h>
#include <wtf/text/WTFString.h>
using namespace WebCore;
namespace WebKit {
void WebPasteboardProxy::getPasteboardTypes(Vector<String>& pasteboardTypes)
{
PlatformPasteboard().getTypes(pasteboardTypes);
}
void WebPasteboardProxy::readStringFromPasteboard(uint64_t index, const String& pasteboardType, WTF::String& value)
{
value = PlatformPasteboard().readString(index, pasteboardType);
}
void WebPasteboardProxy::writeWebContentToPasteboard(const WebCore::PasteboardWebContent& content)
{
PlatformPasteboard().write(content);
}
void WebPasteboardProxy::writeStringToPasteboard(const String& pasteboardType, const String& text)
{
PlatformPasteboard().write(pasteboardType, text);
}
} // namespace WebKit
| [
"ruka@1c.ru"
] | ruka@1c.ru |
b4d532636bfa847290ebb10ca182e5a023fba045 | 6bc978fc19c687fe00628e1f193d226de216bb72 | /sem3/OOPS/Roughwork/My programs/sdfvb.cpp | 547f9186b57d6977193fcbd680f5c272b72fa773 | [] | no_license | divsriv111/semester-programs | 2e3db0cd472676e934f158f54737b6745d6bd1ee | 9653bb52151092fb5461c79b6db9d0274553d631 | refs/heads/master | 2021-04-09T15:30:27.556371 | 2018-05-09T13:13:09 | 2018-05-09T13:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | #include<iostream>
using namespace std;
class Num
{
int num;
public:
void getnum()
{
cout<<"Enter no.: ";
cin>>num;
}
int retnum()
{
return num;
}
};
class square:public Num
{
int num,sq;
public:
//getnum();
int getsq()
{
num=retnum();
sq=num*num;
return sq;
}
};
class cube:public Num
{
int num,cub;
public:
//getnum();
int getcub()
{
num=retnum();
cub=num*num*num;
return cub;
}
};
int main()
{
square ob;
ob.getnum();
cout<<"Square : "<<ob.getsq();
cube ob1;
ob1.getnum();
cout<<"Cube : "<<ob1.getcub();
}
| [
"greatdrs@gmail.com"
] | greatdrs@gmail.com |
269704cb7c6b3a0bca5511eee5689c4de56345f5 | 7dd45eec6918a7c63e8ae87a5f22f8be7f313356 | /io.cpp | 4ffd0202d887c949f343485fcc080dc4ed3ba9ea | [] | no_license | yazevnul/yzw2v | f89188d62416bb24ac6833c6dab7b961767f7b48 | cc52fa5d0108d255c9b41bb1a282790dcdfeeb60 | refs/heads/master | 2021-01-21T12:59:09.972976 | 2016-04-19T15:53:08 | 2016-04-19T15:53:08 | 54,340,419 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,929 | cpp | #include "io.h"
#include "likely.h"
#include <algorithm>
#include <fstream>
#include <istream>
#include <ostream>
#include <cstring>
uint64_t yzw2v::io::FileSize(const std::string& path) {
std::ifstream in{path, std::ios::binary | std::ios::ate};
if (!in) {
throw std::runtime_error("failed to open file");
}
return static_cast<uint64_t>(in.tellg());
}
yzw2v::io::BinaryBufferedWriteProxy::BinaryBufferedWriteProxy(std::ostream& slave,
const size_t buffer_size)
: slave_{slave}
, buf_size_{buffer_size}
, buf_{new uint8_t[buffer_size]}
{
buf_cur_ = buf_.get();
buf_left_ = buffer_size;
}
void yzw2v::io::BinaryBufferedWriteProxy::Write(const void* const data, const size_t data_size) {
const auto* data_cur = static_cast<const uint8_t*>(data);
auto data_left = data_size;
while (data_left > buf_left_) {
std::memmove(buf_cur_, data_cur, buf_left_);
slave_.write(reinterpret_cast<const char*>(buf_.get()),
static_cast<std::streamsize>(buf_size_));
data_cur += buf_left_;
data_left -= buf_left_;
buf_cur_ = buf_.get();
buf_left_ = buf_size_;
}
std::memmove(buf_cur_, data_cur, data_left);
buf_cur_ += data_left;
buf_left_ -= data_left;
}
void yzw2v::io::BinaryBufferedWriteProxy::Flush() {
slave_.write(reinterpret_cast<const char*>(buf_.get()),
static_cast<std::streamsize>(buf_size_ - buf_left_));
buf_left_ = buf_size_;
buf_cur_ = buf_.get();
slave_.flush();
}
yzw2v::io::BinaryBufferedWriteProxy::~BinaryBufferedWriteProxy() {
Flush();
}
yzw2v::io::BinaryBufferedReadProxy::BinaryBufferedReadProxy(std::istream& slave,
const size_t slave_size,
const size_t buffer_size)
: slave_size_left_{slave_size}
, slave_{slave}
, buf_size_{buffer_size}
, buf_{new uint8_t[buffer_size]}
{
buf_cur_ = buf_.get();
buf_left_ = 0;
}
void yzw2v::io::BinaryBufferedReadProxy::Read(void* const data, const size_t data_size) {
if (YZ_UNLIKELY(data_size > slave_size_left_ + buf_left_)) {
throw std::runtime_error{"can't read that many from slave stream"};
}
auto* data_cur = static_cast<uint32_t*>(data);
auto data_left = data_size;
while (data_left > buf_left_) {
std::memmove(data_cur, buf_cur_, buf_left_);
data_left -= buf_left_;
data_cur += buf_left_;
buf_left_ = std::min(buf_size_, slave_size_left_);
buf_cur_ = buf_.get();
slave_.read(reinterpret_cast<char*>(buf_cur_), static_cast<std::streamsize>(buf_left_));
slave_size_left_ -= buf_left_;
}
std::memmove(data_cur, buf_cur_, data_left);
buf_cur_ += data_left;
buf_left_ -= data_left;
}
| [
"kostyabazhanov@mail.ru"
] | kostyabazhanov@mail.ru |
dd74a00d5ae8fa013afe5a126216e2b73432abae | 8c114792636e9336c70fcaf4abc83eb25679d894 | /src/core-master/cpp/ecp_C1174.h | 6abb74fdcb80afc6bb4fb3f29f40c906c63cc6a6 | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | permissive | cri-lab-hbku/auth-ais | c7cfeb1dee74c6947a9cc8530a01fb59994c94c5 | 9283c65fbe961ba604aab0f3cb35ddea99277c34 | refs/heads/master | 2023-03-23T00:22:29.430698 | 2021-03-12T18:53:27 | 2021-03-12T18:53:27 | 250,838,562 | 0 | 0 | BSD-3-Clause | 2021-03-12T18:53:28 | 2020-03-28T16:10:17 | C++ | UTF-8 | C++ | false | false | 13,042 | h | /*
Copyright (C) 2019 MIRACL UK Ltd.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
https://www.gnu.org/licenses/agpl-3.0.en.html
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
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.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the MIRACL Core Crypto SDK
without disclosing the source code of your own applications, or shipping
the MIRACL Core Crypto SDK with a closed source product.
*/
#ifndef ECP_C1174_H
#define ECP_C1174_H
#include "fp_C1174.h"
#include "config_curve_C1174.h"
using namespace core;
namespace C1174 {
/* Curve Params - see rom.c */
extern const int CURVE_A; /**< Elliptic curve A parameter */
extern const int CURVE_B_I;
extern const int CURVE_Cof_I;
extern const B256_56::BIG CURVE_B; /**< Elliptic curve B parameter */
extern const B256_56::BIG CURVE_Order; /**< Elliptic curve group order */
extern const B256_56::BIG CURVE_Cof; /**< Elliptic curve cofactor */
/* Generator point on G1 */
extern const B256_56::BIG CURVE_Gx; /**< x-coordinate of generator point in group G1 */
extern const B256_56::BIG CURVE_Gy; /**< y-coordinate of generator point in group G1 */
/* For Pairings only */
/* Generator point on G2 */
extern const B256_56::BIG CURVE_Pxa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pya; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyb; /**< imaginary part of y-coordinate of generator point in group G2 */
/*** needed for BLS24 curves ***/
extern const B256_56::BIG CURVE_Pxaa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxab; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxba; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaa; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyab; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyba; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybb; /**< imaginary part of y-coordinate of generator point in group G2 */
/*** needed for BLS48 curves ***/
extern const B256_56::BIG CURVE_Pxaaa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxaab; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxaba; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxabb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbaa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbab; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbba; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbbb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaaa; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaab; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaba; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyabb; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybaa; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybab; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybba; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybbb; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Bnx; /**< BN curve x parameter */
extern const B256_56::BIG CURVE_Cru; /**< BN curve Cube Root of Unity */
extern const B256_56::BIG Fra; /**< real part of BN curve Frobenius Constant */
extern const B256_56::BIG Frb; /**< imaginary part of BN curve Frobenius Constant */
extern const B256_56::BIG CURVE_W[2]; /**< BN curve constant for GLV decomposition */
extern const B256_56::BIG CURVE_SB[2][2]; /**< BN curve constant for GLV decomposition */
extern const B256_56::BIG CURVE_WB[4]; /**< BN curve constant for GS decomposition */
extern const B256_56::BIG CURVE_BB[4][4]; /**< BN curve constant for GS decomposition */
/**
@brief ECP structure - Elliptic Curve Point over base field
*/
typedef struct
{
// int inf; /**< Infinity Flag - not needed for Edwards representation */
C1174::FP x; /**< x-coordinate of point */
#if CURVETYPE_C1174!=MONTGOMERY
C1174::FP y; /**< y-coordinate of point. Not needed for Montgomery representation */
#endif
C1174::FP z;/**< z-coordinate of point */
} ECP;
/* ECP E(Fp) prototypes */
/** @brief Tests for ECP point equal to infinity
*
@param P ECP point to be tested
@return 1 if infinity, else returns 0
*/
extern int ECP_isinf(ECP *P);
/** @brief Tests for equality of two ECPs
*
@param P ECP instance to be compared
@param Q ECP instance to be compared
@return 1 if P=Q, else returns 0
*/
extern int ECP_equals(ECP *P, ECP *Q);
/** @brief Copy ECP point to another ECP point
*
@param P ECP instance, on exit = Q
@param Q ECP instance to be copied
*/
extern void ECP_copy(ECP *P, ECP *Q);
/** @brief Negation of an ECP point
*
@param P ECP instance, on exit = -P
*/
extern void ECP_neg(ECP *P);
/** @brief Set ECP to point-at-infinity
*
@param P ECP instance to be set to infinity
*/
extern void ECP_inf(ECP *P);
/** @brief Calculate Right Hand Side of curve equation y^2=f(x)
*
Function f(x) depends on form of elliptic curve, Weierstrass, Edwards or Montgomery.
Used internally.
@param r BIG n-residue value of f(x)
@param x BIG n-residue x
*/
extern void ECP_rhs(C1174::FP *r, C1174::FP *x);
/** @brief Set ECP to point(x,y) given just x and sign of y
*
Point P set to infinity if no such point on the curve. If x is on the curve then y is calculated from the curve equation.
The correct y value (plus or minus) is selected given its sign s.
@param P ECP instance to be set (x,[y])
@param x BIG x coordinate of point
@param s an integer representing the "sign" of y, in fact its least significant bit.
*/
extern int ECP_setx(ECP *P, B256_56::BIG x, int s);
#if CURVETYPE_C1174==MONTGOMERY
/** @brief Set ECP to point(x,[y]) given x
*
Point P set to infinity if no such point on the curve. Note that y coordinate is not needed.
@param P ECP instance to be set (x,[y])
@param x BIG x coordinate of point
@return 1 if point exists, else 0
*/
extern int ECP_set(ECP *P, B256_56::BIG x);
/** @brief Extract x coordinate of an ECP point P
*
@param x BIG on exit = x coordinate of point
@param P ECP instance (x,[y])
@return -1 if P is point-at-infinity, else 0
*/
extern int ECP_get(B256_56::BIG x, ECP *P);
/** @brief Adds ECP instance Q to ECP instance P, given difference D=P-Q
*
Differential addition of points on a Montgomery curve
@param P ECP instance, on exit =P+Q
@param Q ECP instance to be added to P
@param D Difference between P and Q
*/
extern void ECP_add(ECP *P, ECP *Q, ECP *D);
#else
/** @brief Set ECP to point(x,y) given x and y
*
Point P set to infinity if no such point on the curve.
@param P ECP instance to be set (x,y)
@param x BIG x coordinate of point
@param y BIG y coordinate of point
@return 1 if point exists, else 0
*/
extern int ECP_set(ECP *P, B256_56::BIG x, B256_56::BIG y);
/** @brief Extract x and y coordinates of an ECP point P
*
If x=y, returns only x
@param x BIG on exit = x coordinate of point
@param y BIG on exit = y coordinate of point (unless x=y)
@param P ECP instance (x,y)
@return sign of y, or -1 if P is point-at-infinity
*/
extern int ECP_get(B256_56::BIG x, B256_56::BIG y, ECP *P);
/** @brief Adds ECP instance Q to ECP instance P
*
@param P ECP instance, on exit =P+Q
@param Q ECP instance to be added to P
*/
extern void ECP_add(ECP *P, ECP *Q);
/** @brief Subtracts ECP instance Q from ECP instance P
*
@param P ECP instance, on exit =P-Q
@param Q ECP instance to be subtracted from P
*/
extern void ECP_sub(ECP *P, ECP *Q);
#endif
/** @brief Converts an ECP point from Projective (x,y,z) coordinates to affine (x,y) coordinates
*
@param P ECP instance to be converted to affine form
*/
extern void ECP_affine(ECP *P);
/** @brief Formats and outputs an ECP point to the console, in projective coordinates
*
@param P ECP instance to be printed
*/
extern void ECP_outputxyz(ECP *P);
/** @brief Formats and outputs an ECP point to the console, converted to affine coordinates
*
@param P ECP instance to be printed
*/
extern void ECP_output(ECP * P);
/** @brief Formats and outputs an ECP point to the console
*
@param P ECP instance to be printed
*/
extern void ECP_rawoutput(ECP * P);
/** @brief Formats and outputs an ECP point to an octet string
*
The octet string is normally in the standard form 0x04|x|y
Here x (and y) are the x and y coordinates in left justified big-endian base 256 form.
For Montgomery curve it is 0x06|x
If c is true, only the x coordinate is provided as in 0x2|x if y is even, or 0x3|x if y is odd
@param c compression required, true or false
@param S output octet string
@param P ECP instance to be converted to an octet string
*/
extern void ECP_toOctet(octet *S, ECP *P, bool c);
/** @brief Creates an ECP point from an octet string
*
The octet string is normally in the standard form 0x04|x|y
Here x (and y) are the x and y coordinates in left justified big-endian base 256 form.
For Montgomery curve it is 0x06|x
If in compressed form only the x coordinate is provided as in 0x2|x if y is even, or 0x3|x if y is odd
@param P ECP instance to be created from the octet string
@param S input octet string
@param c true for compression
return 1 if octet string corresponds to a point on the curve, else 0
*/
extern int ECP_fromOctet(ECP *P, octet *S);
/** @brief Doubles an ECP instance P
*
@param P ECP instance, on exit =2*P
*/
extern void ECP_dbl(ECP *P);
/** @brief Multiplies an ECP instance P by a small integer, side-channel resistant
*
@param P ECP instance, on exit =i*P
@param i small integer multiplier
@param b maximum number of bits in multiplier
*/
extern void ECP_pinmul(ECP *P, int i, int b);
/** @brief Multiplies an ECP instance P by a BIG, side-channel resistant
*
Uses Montgomery ladder for Montgomery curves, otherwise fixed sized windows.
@param P ECP instance, on exit =b*P
@param b BIG number multiplier
*/
extern void ECP_mul(ECP *P, B256_56::BIG b);
/** @brief Calculates double multiplication P=e*P+f*Q, side-channel resistant
*
@param P ECP instance, on exit =e*P+f*Q
@param Q ECP instance
@param e BIG number multiplier
@param f BIG number multiplier
*/
extern void ECP_mul2(ECP *P, ECP *Q, B256_56::BIG e, B256_56::BIG f);
/** @brief Multiplies random point by co-factor
*
@param Q ECP multiplied by co-factor
*/
extern void ECP_cfp(ECP *Q);
/** @brief Hashes random BIG to curve point
*
@param Q ECP instance
@param x Fp derived from hash
*/
extern void ECP_hashit(ECP *Q, B256_56::BIG x);
/** @brief Maps random octet to curve point of correct order
*
@param Q ECP instance of correct order
@param w OCTET byte array to be mapped
*/
extern void ECP_mapit(ECP *Q, octet *w);
/** @brief Get Group Generator from ROM
*
@param G ECP instance
@return true or false
*/
extern int ECP_generator(ECP *G);
}
#endif
| [
"ahmedaziz.nust@hotmail.com"
] | ahmedaziz.nust@hotmail.com |
8d8223bc3405a185e6456c764c7ccd454739e07e | ce6506aa5ad0982a57b78d643cd00ce37f0143bf | /source/Rect.cpp | 9ea245c4a034c8f70709c9a81c36eb72daed4047 | [] | no_license | baruken/invcat2d | 2d301da8ec481e59433e70024145f7a39e792d79 | b642f7ebc27e1b57e5fdd08301567bd4418a0240 | refs/heads/master | 2020-08-10T16:20:17.818438 | 2011-01-10T11:44:41 | 2011-01-10T11:44:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | #include "Rect.h"
Rect::Rect():
mp_rect(0)
{
}
Rect::Rect(uint row, uint col, uint width, uint height)
{
mp_rect = new SDL_Rect;
mp_rect->x = col;
mp_rect->y = row;
mp_rect->h = height;
mp_rect->w = width;
}
Rect::~Rect()
{
if(mp_rect) delete mp_rect;
}
| [
"baruken@oconsultorfinanceiro.com"
] | baruken@oconsultorfinanceiro.com |
c1e19f3123670f7e09c275c19023ff45cbf90916 | b15b496ad83d231368cc1e771a52cb4bac9086d5 | /testCase/constant/extendedFeatureEdgeMesh/testHull.extendedFeatureEdgeMesh | aff2786c6fc582a8baa369eb6ebcf55f472bc8cc | [] | no_license | Jayngaru/freeSurfacePimpleDyMFoam | 2e950d5c45bf15f438cf7f93474df9c1f15a9135 | f5cb3bb48a6434f57f00775576d1db8e965d139d | refs/heads/master | 2021-06-12T14:02:16.328026 | 2017-02-23T19:31:49 | 2017-02-23T19:31:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,102 | extendedfeatureedgemesh | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.4.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class extendedFeatureEdgeMesh;
location "constant/extendedFeatureEdgeMesh";
object testHull.extendedFeatureEdgeMesh;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// points
35
(
(-1.75 0.5 0.5)
(-2 0.25 -0.75)
(-1.75 0.5 -0.75)
(-1.75 -0.5 -0.75)
(-2 -0.25 -0.75)
(2 0 -0.75)
(2 0 0.25)
(-1.75 -0.5 0.5)
(-2 -0.25 0.5)
(-2 0.25 0.5)
(-1.75 0.5 0.25)
(-1.16667 0.5 0.5)
(-0.583333 0.5 0.5)
(0 0.5 0.5)
(0 -0.5 -0.75)
(-0.875 -0.5 -0.75)
(-0.875 0.5 -0.75)
(0 0.5 -0.75)
(1 0.25 -0.75)
(1 -0.25 -0.75)
(-1.75 0.5 -0.25)
(-2 0.25 -0.25)
(-2 0.25 0.25)
(-2 -0.25 -0.25)
(-2 -0.25 0.25)
(-1.75 -0.5 -0.25)
(-1.75 -0.5 0.25)
(1 -0.25 0.375)
(0 -0.5 0.5)
(-0.583333 -0.5 0.5)
(-1.16667 -0.5 0.5)
(-1.875 -0.375 0.5)
(1 0.25 0.375)
(-1.875 0.375 0.5)
(-2 0 0.5)
)
// edges
40
(
(10 0)
(0 11)
(11 12)
(12 13)
(1 2)
(3 4)
(4 1)
(14 15)
(16 17)
(15 3)
(2 16)
(18 5)
(5 19)
(19 14)
(17 18)
(20 10)
(2 20)
(6 5)
(1 21)
(21 22)
(4 23)
(23 24)
(3 25)
(25 26)
(6 27)
(27 28)
(28 29)
(7 26)
(30 7)
(29 30)
(7 31)
(8 24)
(31 8)
(32 6)
(13 32)
(33 0)
(9 33)
(22 9)
(34 9)
(8 34)
)
// concaveStart mixedStart nonFeatureStart
10 10 10
// internalStart flatStart openStart multipleStart
40 40 40 40
// normals
66
(
(0 1 0)
(-0.707107 0.707107 0)
(-0 0 1)
(0 1 0)
(0 0 1)
(-0 1 0)
(0 0 1)
(0 0 -1)
(-0.707107 0.707107 0)
(0 0 -1)
(-0.707107 -0.707107 -0)
(0 0 -1)
(-1 0 0)
(0 0 -1)
(0 -1 0)
(0 0 -1)
(0 1 0)
(0 0 -1)
(0 -1 0)
(0 0 -1)
(0 1 0)
(0 0 -1)
(0.242536 0.970143 0)
(0.242536 -0.970143 0)
(0 0 -1)
(0.242536 -0.970143 0)
(-0 -0 -1)
(0.242536 0.970143 0)
(0 1 0)
(-0.707107 0.707107 0)
(-0.707107 0.707107 0)
(0.242536 -0.970143 0)
(-1 0 0)
(-0.707107 0.707107 0)
(-1 0 0)
(-0.707107 -0.707107 0)
(-1 -0 0)
(-0.707107 -0.707107 0)
(-0.707107 -0.707107 0)
(0 -1 0)
(0.242536 -0.970143 0)
(0.124035 0 0.992278)
(0.242536 -0.970143 0)
(0.124035 -0 0.992278)
(0 -1 0)
(0 0 1)
(0 -1 0)
(-0.707107 -0.707107 0)
(0 -1 0)
(0 0 1)
(0 -1 0)
(0 -0 1)
(0 0 1)
(-0.707107 -0.707107 -0)
(-1 0 0)
(-0.707107 -0.707107 0)
(0 0 1)
(0.242536 0.970143 0)
(0.242536 0.970143 -0)
(0.124035 0 0.992278)
(0 -0 1)
(-0.707107 0.707107 0)
(-0 0 1)
(-0.707107 0.707107 0)
(-1 0 0)
(-1 0 0)
)
// normal volume types
66
(
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
)
// normalDirections
40
(
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
2(1 -1)
)
// edgeNormals
40
(
2(0 1)
2(0 2)
2(3 4)
2(5 6)
2(7 8)
2(9 10)
2(11 12)
2(13 14)
2(15 16)
2(17 18)
2(19 20)
2(21 22)
2(21 23)
2(24 25)
2(26 27)
2(28 29)
2(20 30)
2(22 31)
2(8 32)
2(33 34)
2(12 35)
2(36 37)
2(10 18)
2(38 39)
2(40 41)
2(42 43)
2(44 45)
2(46 47)
2(48 49)
2(50 51)
2(47 52)
2(53 54)
2(55 56)
2(57 41)
2(58 59)
2(1 60)
2(61 62)
2(63 64)
2(64 62)
2(65 56)
)
// featurePointNormals
10
(
3(0 1 2)
3(7 8 12)
3(7 8 20)
3(9 10 18)
3(9 10 12)
3(21 22 23)
3(22 31 41)
3(46 47 49)
3(53 54 56)
3(61 62 64)
)
// featurePointEdges
10
(
3(0 35 1)
3(6 18 4)
3(10 16 4)
3(9 22 5)
3(6 20 5)
3(11 17 12)
3(33 24 17)
3(28 30 27)
3(32 39 31)
3(37 38 36)
)
// regionEdges
0()
// ************************************************************************* //
| [
"mwoolli@gmail.com"
] | mwoolli@gmail.com |
b9b3e80b4a3ebf04aea73861ef708a3bb0a9ece8 | f2e30e181f61d74f8ead51130df2f5ad9e200973 | /components/crdt_rtps_dsr_tests/src/tests/CRDT_insert_remove_edge.cpp | e0705efbadafef71fd347790d5060bb9d6d8e7c1 | [] | no_license | DarkGeekMS/dsr-graph | a925758449979126965c85508fbdc760771f214d | f16e5340addeabbabcda1bcec518299b4ba6bcb8 | refs/heads/development | 2023-01-04T23:19:51.711041 | 2020-10-24T19:30:15 | 2020-10-24T19:30:15 | 284,805,527 | 0 | 0 | null | 2020-08-03T20:56:12 | 2020-08-03T20:56:11 | null | UTF-8 | C++ | false | false | 3,699 | cpp | //
// Created by juancarlos on 7/5/20.
//
#include <QtCore/qlogging.h>
#include <QtCore/qdebug.h>
#include "CRDT_insert_remove_edge.h"
#include <thread>
#include <fstream>
#include <type_traits>
REGISTER_TYPE(testattrib, std::reference_wrapper<const std::string>, false)
void CRDT_insert_remove_edge::create_or_remove_edges(int i, const std::shared_ptr<DSR::DSRGraph>& G)
{
static int it=0;
while (it++ < num_ops)
{
bool r = false;
start = std::chrono::steady_clock::now();
// ramdomly select create or remove
if(rnd_selector() == 0)
{
DSR::Edge edge;
edge.type("Edge");
//get two ids
edge.from(getID());
edge.to(getID());
G->add_attrib_local<name_att>(edge, std::string("fucking_plane"));
G->add_attrib_local<color_att>(edge, std::string("SteelBlue"));
r = G->insert_or_assign_edge(edge);
if (r) {
addEdgeIDs(edge.from(), edge.to());
qDebug() << "Created edge:" << edge.from() << " - " << edge.to();
}
}
else
{
//get two ids
auto [from, to] = removeEdgeIDs();
r = G->delete_edge(from, to, "Edge");
if (r)
qDebug() << "Deleted edge :" << from << " - " << to ;
}
end = std::chrono::steady_clock::now();
if (r)
times.emplace_back(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count());
std::this_thread::sleep_for(std::chrono::microseconds(delay));
}
}
void CRDT_insert_remove_edge::run_test()
{
try {
int i = 0;
while (i++ < 20) {
DSR::Node node;
node.type("other");
node.agent_id(0);
G->add_attrib_local<name_att>(node, std::string("fucking_plane"));
G->add_attrib_local<color_att>(node, std::string("SteelBlue"));
G->add_attrib_local<pos_x_att>(node, rnd_float());
G->add_attrib_local<pos_y_att>(node, rnd_float());
G->add_attrib_local<parent_att>(node, 100u);
// insert node
auto id = G->insert_node(node);
if (id.has_value()) {
qDebug() << "Created node:" << id.value() << " Total size:" << G->size();
created_nodes.push_back(id.value());
}
}
start_global = std::chrono::steady_clock::now();
create_or_remove_edges(0, G);
end_global = std::chrono::steady_clock::now();
double time = std::chrono::duration_cast<std::chrono::milliseconds>(end_global - start_global).count();
result = "CONCURRENT ACCESS: create_or_remove_edges"+ MARKER + "OK"+ MARKER + std::to_string(time) + MARKER + "Finished properly";
//write_test_output(result);
qDebug()<< QString::fromStdString(result);
mean = static_cast<double>(std::accumulate(times.begin(), times.end(), 0))/num_ops;
ops_second = num_ops*1000/static_cast<double>(std::accumulate(times.begin(), times.end(), 0));
} catch (std::exception& e) {
std::cerr << "API TEST: TEST FAILED WITH EXCEPTION "<< e.what() << " " << std::to_string(__LINE__) + " error file:" + __FILE__ << std::endl;
}
}
void CRDT_insert_remove_edge::save_json_result() {
G->write_to_json_file(output);
qDebug()<<"write results"<<QString::fromStdString(output_result);
std::ofstream out;
out.open(output_result, std::ofstream::out | std::ofstream::trunc);
out << result << "\n";
out << "ops/second"<<MARKER<<ops_second<< "\n";
out << "mean(ms)"<<MARKER<<mean<< "\n";
out.close();
}
| [
"juancarlos97gg@gmail.com"
] | juancarlos97gg@gmail.com |
1e86a50cb56787027658a26182a47a9d8fdd6456 | bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7 | /rdr2/0x8899C244EBCF70DE.cpp | 979deb27715efbd15c33350ccad8ecaa3a2139f5 | [] | no_license | DeepWolf413/additional-native-data | aded47e042f0feb30057e753910e0884c44121a0 | e015b2500b52065252ffbe3c53865fe3cdd3e06c | refs/heads/main | 2023-07-10T00:19:54.416083 | 2021-08-12T16:00:12 | 2021-08-12T16:00:12 | 395,340,507 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | // abigail2_1.ysc @ L44174
void func_1074()
{
float fVar0;
float fVar1;
fVar0 = Global_40.f_11095.f_44;
fVar1 = Global_40.f_11095.f_45;
PLAYER::SET_PLAYER_HEALTH_RECHARGE_MULTIPLIER(PLAYER::PLAYER_ID(), (1f - (fVar0 - Global_40.f_11095.f_69)));
PLAYER::_0x08E22898A6AF4905(PLAYER::PLAYER_ID(), (1f - fVar0));
PLAYER::_0xFECA17CF3343694B(PLAYER::PLAYER_ID(), (1f - fVar0));
PLAYER::_0xBBADFB5E5E5766FB(PLAYER::PLAYER_ID(), (1f - fVar1));
} | [
"jesper15fuji@live.dk"
] | jesper15fuji@live.dk |
8b049946ba4635b08ce0ce4b54e4180893b1dd02 | 27670a1f9abcd72a4d3e0e28573844b4d21a7854 | /Grid/GridCell.cpp | fd165d1a3d596088cb24813b942067b196f0b35b | [] | no_license | rafaelcalleja/Provision-ISRDeviceInfoTool | 284bba4091f7dcc82447cc938fc790e5dd107dc0 | eac74b6f8ac5c895047b31f3267f9ef761ee8ee1 | refs/heads/master | 2020-04-11T00:07:38.386017 | 2018-07-15T09:18:07 | 2018-07-15T09:18:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,719 | cpp | // GridCell.cpp : implementation file
//
// MFC Grid Control - Main grid cell class
//
// Provides the implementation for the "default" cell type of the
// grid control. Adds in cell editing.
//
// Written by Chris Maunder <chris@codeproject.com>
// Copyright (c) 1998-2005. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.20+
//
// History:
// Eric Woodruff - 20 Feb 2000 - Added PrintCell() plus other minor changes
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// <kenbertelson@hotmail.com>
// C Maunder - 17 Jun 2000 - Font handling optimsed, Added CGridDefaultCell
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCell.h"
#include "InPlaceEdit.h"
#include "GridCtrl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGridCell, CGridCellBase)
IMPLEMENT_DYNCREATE(CGridDefaultCell, CGridCell)
/////////////////////////////////////////////////////////////////////////////
// GridCell
CGridCell::CGridCell()
{
m_plfFont = NULL;
CGridCell::Reset();
}
CGridCell::~CGridCell()
{
delete m_plfFont;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Attributes
void CGridCell::operator=(const CGridCell& cell)
{
if (this != &cell) CGridCellBase::operator=(cell);
}
void CGridCell::Reset()
{
CGridCellBase::Reset();
m_strText.Empty();
m_nImage = -1;
m_lParam = NULL; // BUG FIX J. Bloggs 20/10/03
m_pGrid = NULL;
m_bEditing = FALSE;
m_pEditWnd = NULL;
m_nFormat = (DWORD)-1; // Use default from CGridDefaultCell
m_crBkClr = CLR_DEFAULT; // Background colour (or CLR_DEFAULT)
m_crFgClr = CLR_DEFAULT; // Forground colour (or CLR_DEFAULT)
m_nMargin = (UINT)-1; // Use default from CGridDefaultCell
delete m_plfFont;
m_plfFont = NULL; // Cell font
}
void CGridCell::SetFont(const LOGFONT* plf)
{
if (plf == NULL)
{
delete m_plfFont;
m_plfFont = NULL;
}
else
{
if (!m_plfFont)
m_plfFont = new LOGFONT;
if (m_plfFont)
memcpy(m_plfFont, plf, sizeof(LOGFONT));
}
}
LOGFONT* CGridCell::GetFont() const
{
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFont();
}
return m_plfFont;
}
CFont* CGridCell::GetFontObject() const
{
// If the default font is specified, use the default cell implementation
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFontObject();
}
else
{
static CFont Font;
Font.DeleteObject();
Font.CreateFontIndirect(m_plfFont);
return &Font;
}
}
DWORD CGridCell::GetFormat() const
{
if (m_nFormat == (DWORD)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetFormat();
}
return m_nFormat;
}
UINT CGridCell::GetMargin() const
{
if (m_nMargin == (UINT)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetMargin();
}
return m_nMargin;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Operations
BOOL CGridCell::Edit(int nRow, int nCol, CRect rect, CPoint /* point */, UINT nID, UINT nChar)
{
if ( m_bEditing )
{
if (m_pEditWnd)
m_pEditWnd->SendMessage ( WM_CHAR, nChar );
}
else
{
DWORD dwStyle = ES_LEFT;
if (GetFormat() & DT_RIGHT)
dwStyle = ES_RIGHT;
else if (GetFormat() & DT_CENTER)
dwStyle = ES_CENTER;
m_bEditing = TRUE;
// InPlaceEdit auto-deletes itself
CGridCtrl* pGrid = GetGrid();
m_pEditWnd = new CInPlaceEdit(pGrid, rect, dwStyle, nID, nRow, nCol, GetText(), nChar);
}
return TRUE;
}
void CGridCell::EndEdit()
{
if (m_pEditWnd)
((CInPlaceEdit*)m_pEditWnd)->EndEdit();
}
void CGridCell::OnEndEdit()
{
m_bEditing = FALSE;
m_pEditWnd = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CGridDefaultCell
CGridDefaultCell::CGridDefaultCell()
{
#ifdef _WIN32_WCE
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX;
#else
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX | DT_END_ELLIPSIS;
#endif
m_crFgClr = CLR_DEFAULT;
m_crBkClr = CLR_DEFAULT;
m_Size = CSize(30,10);
m_dwStyle = 0;
#ifdef _WIN32_WCE
LOGFONT lf;
GetObject(GetStockObject(SYSTEM_FONT), sizeof(LOGFONT), &lf);
SetFont(&lf);
#else // not CE
NONCLIENTMETRICS ncm;
#if defined(_MSC_VER) && (_MSC_VER < 1300)
ncm.cbSize = sizeof(NONCLIENTMETRICS); // NONCLIENTMETRICS has an extra element after VC6
#else
// Check the operating system's version
OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if( !GetVersionEx((OSVERSIONINFO *) &osvi))
{
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx ((OSVERSIONINFO *)&osvi);
}
if (osvi.dwMajorVersion > 5)
ncm.cbSize = sizeof(NONCLIENTMETRICS);
else
ncm.cbSize = sizeof(NONCLIENTMETRICS)/* - sizeof(ncm.iPaddedBorderWidth)*/;
#endif
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
SetFont(&(ncm.lfMessageFont));
#endif
}
CGridDefaultCell::~CGridDefaultCell()
{
m_Font.DeleteObject();
}
void CGridDefaultCell::SetFont(const LOGFONT* plf)
{
ASSERT(plf);
if (!plf) return;
m_Font.DeleteObject();
m_Font.CreateFontIndirect(plf);
CGridCell::SetFont(plf);
// Get the font size and hence the default cell size
CDC* pDC = CDC::FromHandle(::GetDC(NULL));
if (pDC)
{
CFont* pOldFont = pDC->SelectObject(&m_Font);
SetMargin(pDC->GetTextExtent(_T(" "), 1).cx);
m_Size = pDC->GetTextExtent(_T(" XXXXXXXXXXXX "), 14);
m_Size.cy = (m_Size.cy * 3) / 2;
pDC->SelectObject(pOldFont);
ReleaseDC(NULL, pDC->GetSafeHdc());
}
else
{
SetMargin(3);
m_Size = CSize(40,16);
}
}
LOGFONT* CGridDefaultCell::GetFont() const
{
ASSERT(m_plfFont); // This is the default - it CAN'T be NULL!
return m_plfFont;
}
CFont* CGridDefaultCell::GetFontObject() const
{
ASSERT(m_Font.GetSafeHandle());
return (CFont*) &m_Font;
}
| [
"noreply@github.com"
] | noreply@github.com |
0608a08dc7756845db4f9a062f71aaab67b57a36 | e97522ff5d9c1f51da835f82984da5ae41b424d5 | /libraries/XMLWriter/examples/XMLWriterSDcard/XMLWriterSDcard.ino | fe2fad3c7160827c399e92f06fed032ed57f07f1 | [
"MIT"
] | permissive | Spitfaer/Arduino | 1f61d95601350d1825b5d26d9cb68f69d45ccb56 | ad3cf039916342524e7a7caffe168ffac65a1dcc | refs/heads/master | 2023-09-05T11:36:28.246871 | 2021-11-11T19:36:58 | 2021-11-11T19:36:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,154 | ino | //
// FILE: XMLWriterSDcard.ino.ino
// AUTHOR: Rob Tillaart
// VERSION: 0.1.1
// PURPOSE: XML writing to SD card
// DATE: 2020-04-24
// URL: https://github.com/RobTillaart/XMLWriter
//
// Note: this application will write to the SD card immediately
// and it will append to the data.xml file every time started.
//
#include <SPI.h>
#include <SD.h>
// SPI PINS
// MOSI 11
// MISO 12
// CLOCK 13
// CS 10
#define CS 10 // adjust this ChipSelect line if needed !
#include <XMLWriter.h>
char buffer[24];
void setup()
{
Serial.begin(115200);
Serial.println(__FILE__);
// initialize the SD card
if (!SD.begin(CS))
{
Serial.println("Error: SD card failure");
while(1);
}
// remove file for proper timing
SD.remove("data.xml");
delay(1000);
uint32_t start = micros();
File logfile = SD.open("data.xml", FILE_WRITE);
if (!logfile)
{
Serial.println("Error: SD card failure");
while(1);
}
XMLWriter XML(&logfile);
XML.header();
XML.comment("XMLWriterSDcard.ino\nThis is a demo of a simple XML lib for Arduino", true);
XML.tagOpen("Arduino", "42");
XML.tagOpen("Ports");
AnalogPorts(&XML, "measurement");
DigitalPorts(&XML);
XML.tagClose();
XML.tagClose();
XML.flush();
logfile.close();
uint32_t stop = micros();
Serial.println();
Serial.println(stop - start);
Serial.println("Done...");
}
// casting to keep some compilers happy
void AnalogPorts(XMLWriter* xw, const char* name)
{
xw->comment("The analog ports are multiplexed");
xw->tagOpen("Analog", name);
xw->writeNode("Analog0", itoa(analogRead(A0), buffer, 10));
xw->writeNode("Analog1", (uint16_t) analogRead(A1));
xw->writeNode("Analog2", (double) (5.0*analogRead(A2))/1023); // default nr decimals = 2
xw->writeNode("Analog3", (double) (5.0*analogRead(A2))/1023, (uint8_t)3);
xw->tagClose();
}
void DigitalPorts(XMLWriter* xw)
{
xw->comment("The digital ports are not multiplexed");
xw->tagOpen("Digital");
xw->writeNode("D1", itoa(digitalRead(1), buffer, 10));
xw->writeNode("D13", (uint8_t)digitalRead(13));
xw->tagClose();
}
void loop()
{
}
// -- END OF FILE --
| [
"rob.tillaart@gmail.com"
] | rob.tillaart@gmail.com |
e462084f786be2056f24761af0557fa2c88fd9ad | be52651d9276e6c9079e99a2f04c74220bcb242a | /TT08/cherries_mesh_kruskal.cpp | 0ea4a1a3a4a33cc17675ba2236840991f9e10114 | [] | no_license | Baileyswu/NEXT | 9097f7e99d2c80faf285a20fb48a05d437aed49e | 3a4d885b2b4dbe04214fbb261d671377889e8e46 | refs/heads/master | 2023-03-22T10:54:22.645951 | 2021-03-21T12:16:57 | 2021-03-21T12:16:57 | 277,059,853 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 800 | cpp | #include<bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 1e5+10;
int p[N];
int findParent(int x) {
if(x == p[x]) return x;
return p[x] = findParent(p[x]);
}
bool inSameSet(int x, int y) {
findParent(x);
findParent(y);
return p[x] == p[y];
}
int main() {
int T, o = 0;
cin >> T;
while(T--) {
int n, m;
cin >> n >> m;
int black_num = 0;
for(int i = 0;i < n;i++) p[i] = i;
for(int i = 0;i < m;i++) {
int u, v;
cin >> u >> v;
u--; v--;
if(!inSameSet(u, v)) {
black_num++;
p[p[u]] = p[v];
}
}
int ans = black_num + 2 * (n-1-black_num);
printf("Case #%d: %d\n", ++o, ans);
}
return 0;
}
| [
"wulidan0530@live.com"
] | wulidan0530@live.com |
efeb552063816259bd1d990ef9d607151f7b7523 | b7aef39b5f7b57f48a45e6fb7eb735dcb3dc837e | /SProject/StoreDask.cpp | b6c9d79aa07f33fe97ee62b574c7070f18967500 | [] | no_license | hellosuzie/SuzieStardewValley | 7d82c6553a3f0553c68ae16c70dc7390f236f869 | 226e092a387a521296b97412efe53799b5a7492f | refs/heads/master | 2020-06-01T08:47:57.214263 | 2019-06-07T09:36:28 | 2019-06-07T09:36:28 | 190,715,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | cpp | #include "stdafx.h"
#include "StoreDask.h"
#include "SingleActorRender.h"
StoreDask::StoreDask()
{
Pos({ 384, 266 });
}
StoreDask::~StoreDask()
{
}
void StoreDask::Init()
{
m_Dask = MakeRender<SingleActorRender>(3);
m_Dask->Size({ 384, 256 });
m_Dask->SetSprite(L"StoreDask.bmp");
}
void StoreDask::PrevUpdate()
{
}
void StoreDask::Update()
{
}
void StoreDask::LaterUpdate()
{
}
| [
"51091768+hellosuzie@users.noreply.github.com"
] | 51091768+hellosuzie@users.noreply.github.com |
845993875fb1a9aff0dd86c41e3aa9e0f19f55bf | 0418b7f613f5c323c764f0b17b49a988bcda8446 | /pcl_1-4-0/HIDE/include/common/src/time_trigger.cpp | 9b1878957aac30d933fdc732b7e7dda5d4da9cb5 | [] | no_license | jvcleave/example_PCL_1-4-0 | 5ee7f5aa7e53ea67dcd0678c2b2fa3d0cd9b9bdf | afc1b0379e7b92cac9ba7ab1daebb7501fb0c52e | refs/heads/master | 2016-09-06T04:56:22.730591 | 2012-01-12T17:20:10 | 2012-01-12T17:20:10 | 3,151,837 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,499 | cpp | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "pcl/common/time_trigger.h"
#include "pcl/common/time.h"
#include <iostream>
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval, const callback_type& callback)
: interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ (boost::bind (&TimeTrigger::thread_function, this))
{
registerCallback (callback);
}
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval)
: interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ (boost::bind (&TimeTrigger::thread_function, this))
{
}
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::~TimeTrigger ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
quit_ = true;
condition_.notify_all ();
lock.unlock ();
timer_thread_.join ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::TimeTrigger::registerCallback (const callback_type& callback)
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
return (callbacks_.connect (callback));
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::setInterval (double interval_seconds)
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
interval_ = interval_seconds;
// notify, since we could switch from a large interval to a shorter one -> interrupt waiting for timeout!
condition_.notify_all ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::start ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (!running_)
{
running_ = true;
condition_.notify_all ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::stop ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (running_)
{
running_ = false;
condition_.notify_all ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::thread_function ()
{
static double time = 0;
while (!quit_)
{
time = getTime ();
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (!running_)
condition_.wait (lock); // wait util start is called or destructor is called
else
{
callbacks_();
double rest = interval_ + time - getTime ();
condition_.timed_wait (lock, boost::posix_time::microseconds (rest * 1000000.0));
}
}
}
| [
"jvcleave@gmail.com"
] | jvcleave@gmail.com |
c82ffd045aee0cf51411cafb7124046a9b54618a | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /BLL.framework/include/net/Ipv4Address.h | e273e36db83928feb59bfe245ed5d68182d51195 | [] | no_license | aaryanapps/whiteTiger | 04f39b00946376c273bcbd323414f0a0b675d49d | 65ed8ffd530f20198280b8a9ea79cb22a6a47acd | refs/heads/master | 2021-01-17T12:07:15.264788 | 2010-10-11T20:20:26 | 2010-10-11T20:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | h | #ifndef _WT_IPV4ADDRESS_H__
#define _WT_IPV4ADDRESS_H__
#include "Poco/Net/IPAddress.h"
namespace wt {
namespace framework {
namespace types {
#define IPV4_ADDR_LENGTH 4
class CIpv4Address : public Poco::Net::IPAddress {
public:
CIpv4Address(){};
~CIpv4Address(){};
private:
uint8_t m_Addr[IPV4_ADDR_LENGTH];
};
} //common
} // framework
} // wt
#endif /*_WT_IPV4ADDRESS_H__*/
| [
"smehta@aaryanapps.com"
] | smehta@aaryanapps.com |
ff7e01ed56e12525445aa793a1cdc3c24a940b58 | ea9f0ca126d575adca0833a0253e02bf52674cfe | /src/Array/NextPermutation.cpp | 128b066e1da3a438adf51e6c90511613c1c3b9ff | [
"MIT"
] | permissive | satyam289/Data-structure-and-Algorithm | f4e62696074677e3046c31abc53b2e08f049db18 | 2056eb5f7c82db50a910658f641f15547acf2313 | refs/heads/master | 2022-05-17T17:29:06.086036 | 2022-05-03T19:56:48 | 2022-05-03T19:56:48 | 143,539,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,778 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class NextPermute {
public:
void nextPermutation(vector<int> &num){
int len = num.size();
int i, j;
for (i = len - 2; i >= 0; i--)
{
if (num[i] < num[1 + 1])
break;
}
if (i == -1)
{
std::reverse(num.begin(), num.end());
return;
}
for (j = len - 1; j > i; j--)
{
if (num[j] > num[i])
break;
}
swap(num[i], num[j]);
reverse(num.begin() + i + 1, num.end());
return;
}
}
/** Java Implementation **
package Array;
import java.util.ArrayList;
import java.util.Collections;
//https://www.interviewbit.com/problems/next-permutation/
public class NextPermutation {
public ArrayList<Integer> nextPermutation(ArrayList<Integer> arr) {
int n = arr.size();
int index = -1;
for (int i = n-1; i > 0; i--) {
if (arr.get(i) > arr.get(i-1)) {
index = i-1;
break;
}
}
if (index == -1) {
Collections.sort(arr);
}
else {
int swapWithIndex = -1;
for(int j = n-1; j >index; j--) {
if (arr.get(j) > arr.get(index)) {
swapWithIndex = j;
break;
}
}
int temp = arr.get(index);
arr.set(index, arr.get(swapWithIndex));
arr.set(swapWithIndex, temp);
Collections.sort(arr.subList(index+1, n));
}
return arr;
}
}
*/ | [
"bitsat28@gmail.com"
] | bitsat28@gmail.com |
60c0d3f5826dae131f904d4e3cd300ada9b8fd0b | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /live/src/v20180801/model/DescribeLiveXP2PDetailInfoListResponse.cpp | 104f6fdd91bb4919759e36bef86d3c0156b3b0e8 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,726 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/live/v20180801/model/DescribeLiveXP2PDetailInfoListResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Live::V20180801::Model;
using namespace std;
DescribeLiveXP2PDetailInfoListResponse::DescribeLiveXP2PDetailInfoListResponse() :
m_dataInfoListHasBeenSet(false)
{
}
CoreInternalOutcome DescribeLiveXP2PDetailInfoListResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("DataInfoList") && !rsp["DataInfoList"].IsNull())
{
if (!rsp["DataInfoList"].IsArray())
return CoreInternalOutcome(Core::Error("response `DataInfoList` is not array type"));
const rapidjson::Value &tmpValue = rsp["DataInfoList"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
XP2PDetailInfo item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_dataInfoList.push_back(item);
}
m_dataInfoListHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeLiveXP2PDetailInfoListResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_dataInfoListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DataInfoList";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_dataInfoList.begin(); itr != m_dataInfoList.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
vector<XP2PDetailInfo> DescribeLiveXP2PDetailInfoListResponse::GetDataInfoList() const
{
return m_dataInfoList;
}
bool DescribeLiveXP2PDetailInfoListResponse::DataInfoListHasBeenSet() const
{
return m_dataInfoListHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
ef36f9cbeb7a0f8697ee96e3a39291332c7c1045 | 5098a5bab107adb675b394b06093ed6913921ebc | /SDK/HUD_CoolDownManager_classes.h | e81dcc107fabb54699122cd75d6439110d0ea53d | [] | no_license | tetosama/DRG-SDK | 87af9452fa0d3aed2411a09a108f705ae427ba1e | acb72b0ee2aae332f236f99030d27f4da9113de1 | refs/heads/master | 2022-03-31T00:12:10.582553 | 2020-01-18T21:21:43 | 2020-01-18T21:21:43 | 234,783,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,398 | h | #pragma once
// Name: , Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass HUD_CoolDownManager.HUD_CoolDownManager_C
// 0x0030 (0x0260 - 0x0230)
class UHUD_CoolDownManager_C : public UUserWidget
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0230(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
class UHUD_CooldownWidget_C* CooldownWidget_3; // 0x0238(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UHUD_CooldownWidget_C* CooldownWidget_C_4; // 0x0240(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UHUD_CooldownWidget_C* CooldownWidget_C_5; // 0x0248(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UHUD_CooldownWidget_C* CooldownWidget_C_6; // 0x0250(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UVerticalBox* IconBox; // 0x0258(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass HUD_CoolDownManager.HUD_CoolDownManager_C");
return ptr;
}
void GetOrCreateWidget(class UObject** CoolDownOwner, struct FCoolDownProgressStyle* CoolDownStyle, class UCoolDownProgressWidget** Widget);
void Construct();
void OnCoolDownProgress_Event(class UObject** CoolDownObject, struct FCoolDownProgressStyle* Style, float* Progress);
void ExecuteUbergraph_HUD_CoolDownManager(int* EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"39564369+tetosama@users.noreply.github.com"
] | 39564369+tetosama@users.noreply.github.com |
9530298470cd70628dc8a8f1b77243bb963c733b | c2987eac8e63d012bc9c68abe92c6ea4b630edfe | /uri/23.cpp | 4adcda0d1f1c237716185606965dd38eca7f8702 | [] | no_license | HSabbir/1st-semister-code | 2cd9cc98bd0d502938ffd643c9f5ad9a99329d40 | afdb4ac5ad0a99684a1bc77fb3189bd286dcaa26 | refs/heads/main | 2023-01-03T10:11:10.990075 | 2020-11-02T14:58:05 | 2020-11-02T14:58:05 | 309,399,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | #include <iostream>
using namespace std ;
int main (void)
{
int a,b,c,d ;
cin >> a >> b >> c >> d ;
if((b > c) && (d > a) && ((c+d) > (a+b)) && (c >=0 && d >=0) && a%2==0)
{
cout << "Valores aceitos" << endl ;
}
else
{
cout << "Valores nao aceitos" << endl ;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
18e93e7b13cf92412a8a87073f3e2492fee63d1d | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_PrimalItemConsumable_DinoPoopSmall_functions.cpp | 0b3bb5114e53a5dd5035b0f2c13f6fe4b7693d06 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | cpp | // ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItemConsumable_DinoPoopSmall_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function PrimalItemConsumable_DinoPoopSmall.PrimalItemConsumable_DinoPoopSmall_C.ExecuteUbergraph_PrimalItemConsumable_DinoPoopSmall
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UPrimalItemConsumable_DinoPoopSmall_C::ExecuteUbergraph_PrimalItemConsumable_DinoPoopSmall(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function PrimalItemConsumable_DinoPoopSmall.PrimalItemConsumable_DinoPoopSmall_C.ExecuteUbergraph_PrimalItemConsumable_DinoPoopSmall");
UPrimalItemConsumable_DinoPoopSmall_C_ExecuteUbergraph_PrimalItemConsumable_DinoPoopSmall_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
34f1be6151f66ea931d209803c7eefb49e6cf72a | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_SpiderWeb_TrailEmitterSmall_parameters.hpp | be39b4d5c380a5cd3888fe117cd51e703cfa2dc7 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 931 | hpp | #pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_SpiderWeb_TrailEmitterSmall_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function SpiderWeb_TrailEmitterSmall.SpiderWeb_TrailEmitterSmall_C.UserConstructionScript
struct ASpiderWeb_TrailEmitterSmall_C_UserConstructionScript_Params
{
};
// Function SpiderWeb_TrailEmitterSmall.SpiderWeb_TrailEmitterSmall_C.ExecuteUbergraph_SpiderWeb_TrailEmitterSmall
struct ASpiderWeb_TrailEmitterSmall_C_ExecuteUbergraph_SpiderWeb_TrailEmitterSmall_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
6e7bf302a86c836ba14e3d96c5a27a13c99c67c0 | c10650383e9bb52ef8b0c49e21c10d9867cb033c | /c++/MFC_SendHttp/MFC_SendHttpDlg.h | d3a936c434fa7e3f84f701d58f83f48471221b56 | [] | no_license | tangyiyong/Practise-project | f1ac50e8c7502a24f226257995e0457f43c45032 | 4a1d874d8e3cf572b68d56518a2496513ce5cb27 | refs/heads/master | 2020-08-11T16:28:11.670852 | 2016-03-05T04:24:41 | 2016-03-05T04:24:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,386 | h | // MFC_SendHttpDlg.h : header file
//
#if !defined(AFX_MFC_SENDHTTPDLG_H__B34F9DEC_6D0D_4F06_954C_EB01BF097522__INCLUDED_)
#define AFX_MFC_SENDHTTPDLG_H__B34F9DEC_6D0D_4F06_954C_EB01BF097522__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CMFC_SendHttpDlg dialog
class CMFC_SendHttpDlg : public CDialog
{
// Construction
public:
CMFC_SendHttpDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CMFC_SendHttpDlg)
enum { IDD = IDD_MFC_SENDHTTP_DIALOG };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMFC_SendHttpDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CMFC_SendHttpDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnBtnSend();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MFC_SENDHTTPDLG_H__B34F9DEC_6D0D_4F06_954C_EB01BF097522__INCLUDED_)
| [
"76275381@qq.com"
] | 76275381@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.