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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f06236f9ab600ddc9b0fa309b408b0cd2460cff9 | 3db48713c39b90d5967615e3d1c874d88055ba70 | /tests/std/tests/P0355R7_calendars_and_time_zones_zoned_time/test.cpp | 6bd031a5e225c27119fa7a50c09ef10066460ea6 | [
"Apache-2.0",
"LLVM-exception",
"LicenseRef-scancode-object-form-exception-to-mit",
"LicenseRef-scancode-unicode",
"MIT",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-cla",
"... | permissive | microsoft/STL | 4b1a6a625402e04b857e8dfc3c22efd9bc798f01 | 6c69a73911b33892919ec628c0ea5bbf0caf8a6a | refs/heads/main | 2023-09-04T08:50:17.559497 | 2023-08-31T16:49:43 | 2023-08-31T16:49:43 | 204,593,825 | 9,862 | 1,629 | NOASSERTION | 2023-09-14T21:57:47 | 2019-08-27T01:31:18 | C++ | UTF-8 | C++ | false | false | 14,539 | cpp | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <cassert>
#include <chrono>
#include <string_view>
#include <type_traits>
#include <timezone_data.hpp>
using namespace std;
using namespace std::chrono;
using ZT = zoned_traits<const time_zone*>;
struct time_zone_info {
time_zone_info(string_view _name_, const time_zone* _tz_, seconds _sys_) : name(_name_), tz(_tz_), sys(_sys_) {}
string_view name;
const time_zone* tz;
sys_seconds sys;
local_seconds local{tz->to_local(sys)};
zoned_time<seconds> zone{tz, sys};
};
void zonedtime_constructor_test() {
const time_zone_info utc{"Etc/UTC", ZT::default_zone(), seconds{42}};
const time_zone_info syd{Sydney::Tz_name, ZT::locate_zone(Sydney::Tz_name), seconds{20}};
// ensure local conversions are valid
assert(utc.tz->get_info(utc.local).result == local_info::unique);
assert(syd.tz->get_info(syd.local).result == local_info::unique);
{
// defaulted copy
zoned_time<seconds> zone{syd.zone};
assert(zone.get_time_zone() == syd.tz);
assert(zone.get_sys_time() == syd.sys);
}
{
// (1) zoned_time();
zoned_time<seconds> zone{};
assert(zone.get_time_zone() == utc.tz);
assert(zone.get_sys_time() == sys_seconds{});
}
{
// (2) zoned_time(const sys_time<Duration>& st);
zoned_time<seconds> zone{sys_seconds{seconds{1}}};
assert(zone.get_time_zone() == utc.tz);
assert(zone.get_sys_time() == sys_seconds{seconds{1}});
}
{
// (3) explicit zoned_time(TimeZonePtr z);
zoned_time<seconds> zone{&*syd.tz};
assert(zone.get_time_zone() == syd.tz);
assert(zone.get_sys_time() == sys_seconds{});
// (4) explicit zoned_time(string_view name);
assert(zoned_time<seconds>{syd.name} == zone);
}
{
// (5) template<class Duration2>
// zoned_time(const zoned_time<Duration2, TimeZonePtr>& y);
zoned_time<hours> zone_hours{syd.name, sys_time<hours>{hours{1}}};
assert(zone_hours.get_time_zone() == syd.tz);
assert(zone_hours.get_sys_time() == sys_time<seconds>{hours{1}});
}
{
// (6) zoned_time(TimeZonePtr z, const sys_time<Duration>& st);
zoned_time<seconds> zone{&*syd.tz, syd.sys};
assert(zone.get_time_zone() == syd.tz);
assert(zone.get_sys_time() == syd.sys);
// (7) zoned_time(string_view name, const sys_time<Duration>& st);
assert((zoned_time<seconds>{syd.name, syd.sys}) == zone);
}
{
// (8) zoned_time(TimeZonePtr z, const local_time<Duration>& tp);
zoned_time<seconds> zone{&*syd.tz, syd.local};
assert(zone.get_time_zone() == syd.tz);
assert(zone.get_sys_time() == syd.sys);
// (9) zoned_time(string_view name, const local_time<Duration>& st);
assert((zoned_time<seconds>{syd.name, syd.local}) == zone);
}
{
// (10) zoned_time(TimeZonePtr z, const local_time<Duration>& tp, choose c);
zoned_time<seconds> zone{&*syd.tz, syd.local, choose::earliest};
assert(zone.get_time_zone() == syd.tz);
assert(zone.get_sys_time() == syd.sys);
// (11) zoned_time(string_view name, const local_time<Duration>& tp, choose c);
assert((zoned_time<seconds>{syd.name, syd.local, choose::earliest}) == zone);
}
{
// (12) template<class Duration2, class TimeZonePtr2>
// zoned_time(TimeZonePtr z, const zoned_time<Duration2, TimeZonePtr2>& y);
zoned_time<seconds> z1{&*utc.tz, syd.zone};
zoned_time<seconds> z2{&*syd.tz, utc.zone};
assert(z1.get_time_zone() == utc.tz);
assert(z1.get_sys_time() == syd.sys);
assert(z2.get_time_zone() == syd.tz);
assert(z2.get_sys_time() == utc.sys);
// (13) template<class Duration2, class TimeZonePtr2>
// zoned_time(TimeZonePtr z, const zoned_time<Duration2, TimeZonePtr2>& y, choose);
assert((zoned_time<seconds>{&*utc.tz, syd.zone, choose::earliest}) == z1);
assert((zoned_time<seconds>{&*syd.tz, utc.zone, choose::earliest}) == z2);
// (14) template<class Duration2, class TimeZonePtr2>
// zoned_time(string_view name, const zoned_time<Duration2, TimeZonePtr2>& y);
assert((zoned_time<seconds>{utc.name, syd.zone}) == z1);
assert((zoned_time<seconds>{syd.name, utc.zone}) == z2);
// (15) template<class Duration2, class TimeZonePtr2>
// zoned_time(string_view name, const zoned_time<Duration2, TimeZonePtr2>& y, choose);
assert((zoned_time<seconds>{utc.name, syd.zone, choose::earliest}) == z1);
assert((zoned_time<seconds>{syd.name, utc.zone, choose::earliest}) == z2);
// when (_Duration2 != _Duration)
zoned_time<hours> zone_hours{&*syd.tz, sys_time<hours>{hours{1}}};
zoned_time<seconds> zone{&*utc.tz, zone_hours};
assert(zone.get_time_zone() == utc.tz);
assert(zone.get_sys_time() == sys_time<seconds>{hours{1}});
assert((zoned_time<seconds>{&*utc.tz, zone_hours, choose::earliest}) == zone);
assert((zoned_time<seconds>{utc.name, zone_hours}) == zone);
assert((zoned_time<seconds>{utc.name, zone_hours, choose::earliest}) == zone);
}
}
void zonedtime_operator_test() {
const auto utc_tz = ZT::default_zone();
const zoned_time<seconds> utc_zone{};
assert(utc_zone.get_time_zone() == utc_tz);
assert(utc_zone.get_sys_time() == sys_seconds{});
assert(utc_zone.get_local_time() == local_seconds{});
const auto syd_tz = ZT::locate_zone(Sydney::Tz_name);
const auto transition = Sydney::Day_1;
const auto sys = transition.begin();
const auto local = syd_tz->to_local(transition.begin());
assert(syd_tz->get_info(local).result == local_info::unique);
zoned_time<seconds> zone{ZT::locate_zone(Sydney::Tz_name), sys};
assert(zone.get_time_zone() == syd_tz);
assert(zone.get_sys_time() == sys);
assert(zone.get_local_time() == local);
assert(zone.get_info().begin == sys);
// set time to be == epoch
zone = sys_seconds{};
assert(zone.get_time_zone() == syd_tz);
assert(zone.get_sys_time() == sys_seconds{});
assert(zone.get_local_time() == syd_tz->to_local(sys_seconds{}));
assert(zone.get_info().begin != sys);
// reset sys_time to transition.begin() via local_time
zone = local;
assert(zone.get_time_zone() == syd_tz);
assert(zone.get_sys_time() == sys);
assert(zone.get_local_time() == local);
assert(zone.get_info().begin == sys);
}
void zonedtime_exception_tests() {
const auto syd_tz = ZT::locate_zone(Sydney::Tz_name);
const auto ambiguous_local = syd_tz->to_local(Sydney::Standard_begin_2020 - minutes{1});
assert(syd_tz->get_info(ambiguous_local).result == local_info::ambiguous);
// unsafe constructors
try {
(void) zoned_time<seconds>{ZT::locate_zone(Sydney::Tz_name), ambiguous_local};
assert(false);
} catch (nonexistent_local_time&) {
} catch (ambiguous_local_time&) {
}
try {
(void) zoned_time<seconds>{Sydney::Tz_name, ambiguous_local};
assert(false);
} catch (nonexistent_local_time&) {
} catch (ambiguous_local_time&) {
}
// safe constructors
try {
(void) zoned_time<seconds>{ZT::locate_zone(Sydney::Tz_name), ambiguous_local, choose::earliest};
(void) zoned_time<seconds>{Sydney::Tz_name, ambiguous_local, choose::earliest};
} catch (nonexistent_local_time&) {
assert(false);
} catch (ambiguous_local_time&) {
assert(false);
}
// unsafe operator
try {
zoned_time<seconds> zone{Sydney::Tz_name};
zone = ambiguous_local;
(void) zone;
assert(false);
} catch (nonexistent_local_time&) {
} catch (ambiguous_local_time&) {
}
}
struct Always_zero {
[[nodiscard]] string_view name() const noexcept {
return "Zero";
}
template <class Duration>
[[nodiscard]] sys_info get_info(const sys_time<Duration>&) const {
return {};
}
template <class Duration>
[[nodiscard]] local_info get_info(const local_time<Duration>&) const {
return {};
}
template <class Duration>
[[nodiscard]] sys_time<common_type_t<Duration, seconds>> to_sys(const local_time<Duration>&) const {
return sys_time<common_type_t<Duration, seconds>>{};
}
template <class Duration>
[[nodiscard]] sys_time<common_type_t<Duration, seconds>> to_sys(const local_time<Duration>&, const choose) const {
return sys_time<common_type_t<Duration, seconds>>{};
}
template <class Duration>
[[nodiscard]] local_time<common_type_t<Duration, seconds>> to_local(const sys_time<Duration>&) const {
return local_time<common_type_t<Duration, seconds>>{};
}
};
struct Has_default : Always_zero {};
struct Has_locate : Always_zero {};
Always_zero zero_zone{};
Has_default has_default_zone{};
Has_locate has_locate_zone{};
template <>
struct zoned_traits<const Has_default*> {
[[nodiscard]] static const Has_default* default_zone() {
return &has_default_zone;
}
// missing string_view parameter...
[[nodiscard]] static const Has_locate* locate_zone() {
return &has_locate_zone;
}
};
template <>
struct zoned_traits<const Has_locate*> {
[[nodiscard]] static const Has_locate* locate_zone(string_view) {
return &has_locate_zone;
}
};
void zonedtime_traits_test() {
// operation using timezone should always result in zero
using Always_zero_ptr = const Always_zero*;
zoned_time<seconds, Always_zero_ptr> zone{&zero_zone, sys_seconds{seconds{1}}};
assert(zone.get_time_zone() == &zero_zone);
assert(zone.get_sys_time() == sys_seconds{seconds{1}});
assert(sys_seconds{zone} == sys_seconds{seconds{1}});
assert(zone.get_local_time() == local_seconds{});
assert(local_seconds{zone} == local_seconds{});
assert(zone.get_info().begin == sys_seconds{});
zone = sys_seconds{seconds{2}};
assert(zone.get_sys_time() == sys_seconds{seconds{2}});
assert(sys_seconds{zone} == sys_seconds{seconds{2}});
assert(zone.get_local_time() == local_seconds{});
assert(local_seconds{zone} == local_seconds{});
assert(zone.get_info().begin == sys_seconds{});
zone = local_seconds{seconds{3}};
assert(zone.get_sys_time() == sys_seconds{}); // zero because timezone is used to compute sys_seconds
assert(sys_seconds{zone} == sys_seconds{});
assert(zone.get_local_time() == local_seconds{});
assert(local_seconds{zone} == local_seconds{});
assert(zone.get_info().begin == sys_seconds{});
}
template <class TimeZonePtr, class Duration, bool Has_locate_zone, bool Result>
constexpr void assert_constructible_durations() {
using Zoned_seconds = zoned_time<seconds, TimeZonePtr>;
using Zoned_duration = zoned_time<Duration, TimeZonePtr>;
static_assert(is_constructible_v<Zoned_seconds, Zoned_duration&> == Result);
static_assert(is_constructible_v<Zoned_seconds, TimeZonePtr, Zoned_duration&> == Result);
static_assert(is_constructible_v<Zoned_seconds, string_view, Zoned_duration&> == (Result && Has_locate_zone));
static_assert(is_constructible_v<Zoned_seconds, TimeZonePtr, Zoned_duration&> == Result);
static_assert(is_constructible_v<Zoned_seconds, string_view, Zoned_duration&> == (Result && Has_locate_zone));
}
template <class TimeZonePtr, bool Has_default_zone, bool Has_locate_zone>
constexpr void assert_constructible() {
using Zoned = zoned_time<seconds, TimeZonePtr>;
using Zoned_no_locate = zoned_time<seconds, const Always_zero*>;
static_assert(is_constructible_v<Zoned> == Has_default_zone);
static_assert(is_constructible_v<Zoned, const sys_time<seconds>&> == Has_default_zone);
static_assert(is_constructible_v<Zoned, TimeZonePtr> == true);
static_assert(is_constructible_v<Zoned, string_view> == Has_locate_zone);
static_assert(is_constructible_v<Zoned, const Zoned&> == true);
static_assert(is_constructible_v<Zoned, TimeZonePtr, const sys_time<seconds>&> == true);
static_assert(is_constructible_v<Zoned, string_view, const sys_time<seconds>&> == Has_locate_zone);
static_assert(is_constructible_v<Zoned, TimeZonePtr, const local_time<seconds>&> == true);
static_assert(is_constructible_v<Zoned, string_view, const local_time<seconds>&> == Has_locate_zone);
static_assert(is_constructible_v<Zoned, TimeZonePtr, const local_time<seconds>&, choose> == true);
static_assert(is_constructible_v<Zoned, string_view, const local_time<seconds>&, choose> == Has_locate_zone);
static_assert(is_constructible_v<Zoned, TimeZonePtr, const Zoned_no_locate&> == true);
static_assert(is_constructible_v<Zoned, string_view, const Zoned_no_locate&> == Has_locate_zone);
static_assert(is_constructible_v<Zoned, TimeZonePtr, const Zoned_no_locate&, choose> == true);
static_assert(is_constructible_v<Zoned, string_view, const Zoned_no_locate&, choose> == Has_locate_zone);
// when (_Duration2 != _Duration)
assert_constructible_durations<TimeZonePtr, seconds, Has_locate_zone, true>();
static_assert(is_convertible_v<sys_time<hours>, sys_time<seconds>> == true);
assert_constructible_durations<TimeZonePtr, hours, Has_locate_zone, true>();
static_assert(is_convertible_v<sys_time<milliseconds>, sys_time<seconds>> == false);
assert_constructible_durations<TimeZonePtr, milliseconds, Has_locate_zone, false>();
}
constexpr void zonedtime_constraints_test() {
assert_constructible<const time_zone*, true, true>();
assert_constructible<const Always_zero*, false, false>();
assert_constructible<const Has_default*, true, false>();
assert_constructible<const Has_locate*, false, true>();
}
void test() {
zonedtime_constructor_test();
zonedtime_operator_test();
zonedtime_exception_tests();
zonedtime_traits_test();
zonedtime_constraints_test();
}
int main() {
run_tz_test([] { test(); });
}
| [
"noreply@github.com"
] | noreply@github.com |
e4baf0331c0304058b4a5884109fd326ddbedc1e | 02939456221adc9b316534567be8e05d13337c8d | /ArrayOfInts.cpp | f342e47e224e6a375bcd70a2dbe654d92f2eba81 | [] | no_license | braza501/algorithms_course | b20cb0cdf164353125812a44745bad52d32cb668 | d825f91eb5521bb6151c956e82dce2cfd34306e7 | refs/heads/master | 2021-01-22T21:37:57.975569 | 2017-03-19T05:43:44 | 2017-03-19T05:43:44 | 85,453,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,212 | cpp | // dynamic array
#include <cassert>
#include <iostream>
#include "ArrayOfInts.h"
CArray::CArray() {
maxCapacity = 18;
size = 0;
buffer = new int[maxCapacity];
}
CArray::~CArray() {
if (buffer != nullptr) {
delete[]buffer;
}
}
int CArray::Size() const {
return size;
}
int CArray::BufferSize() const {
return maxCapacity;
}
bool CArray::IsEmpty() const {
return size == 0;
}
int *CArray::GetPtr() {
if (size == 0) {
return nullptr;
}
return buffer;
}
const int *CArray::GetPtr() const {
if (size == 0) {
return nullptr;
}
return buffer;
}
int &CArray::operator[](int index) {
assert(index >= 0 && index < size);
return buffer[index];
}
const int &CArray::operator[](int index) const {
assert(index >= 0 && index < size);
return buffer[index];
}
const int &CArray::Last() const {
if (IsEmpty()) {
throw "emtpy array!";
}
return buffer[size - 1];
}
int &CArray::Last() {
if (IsEmpty()) {
throw "emtpy array!";
}
return buffer[size - 1];
}
// First element
const int &CArray::First() const {
if (IsEmpty()) {
throw "emtpy array!";
}
return buffer[0];
}
int &CArray::First() {
if (IsEmpty()) {
throw "emtpy array!";
}
return buffer[0];
}
void CArray::Add(const int &anElem) {
if(size == maxCapacity){
Grow(2*size);
}
buffer[size++] = anElem;
}
void CArray::Add(const int &anElem, int count) {
if(size == maxCapacity){
Grow(2*(size + count));
}
for (int i = 0; i < count; i++) {
buffer[size++] = anElem;
}
}
void CArray::Add(const CArray &ar) {
if(size == maxCapacity){
Grow(2*(size + ar.Size()));
}
for (int i = 0; i < ar.Size(); i++) {
buffer[size++] = ar[i];
}
}
bool CArray::IsValidIndex(int index) const {
return (index >= 0 && index < size);
}
void CArray::InsertAt(const int &what, int location) {
InsertAt(what, location, 1);
}
void CArray::InsertAt(const int &what, int location, int count) {
if (size + count > maxCapacity) {
Grow(2*(size + count));
}
for (int i = size + count - 1; i > location + count - 1; i--) {
buffer[i] = buffer[i - count];
}
for (int i = location; i < location + count; i++) {
buffer[i] = what;
}
size += count;
}
void CArray::InsertAt(const CArray &what, int location) {
if (size + what.Size() > maxCapacity) {
Grow(2*(size + what.Size()));
}
for (int i = size + what.Size() - 1; i > location + what.Size() - 1; i--) {
buffer[i] = buffer[i - what.Size()];
}
int j = 0;
for (int i = location; i < location + what.Size(); i++) {
buffer[i] = what[j++];
}
size += what.Size();
}
void CArray::DeleteLast() {
assert(!IsEmpty());
size--;
buffer[size] = int();
}
void CArray::DeleteAll() {
for (int i = 0; i < size; i++) {
buffer[i] = int();
}
size = 0;
}
void CArray::FreeBuffer() {
if (buffer == nullptr)
return;
delete[] buffer;
buffer = nullptr;
size = 0;
maxCapacity = 0;
}
void CArray::CopyTo(CArray &dest) const {
dest.FreeBuffer();
dest.SetBufferSize(maxCapacity);
dest.SetSize(size);
for (int i = 0; i < size; i++) {
dest[i] = buffer[i];
}
}
void CArray::MoveTo(CArray &dest) {
if (size + dest.Size() > dest.BufferSize()) {
dest.SetBufferSize(size + dest.Size());
}
int old_size = dest.Size();
dest.SetSize(size + dest.Size());
int j = 0;
for (int i = old_size; i < dest.Size(); i++) {
dest[i] = buffer[j++];
}
}
int CArray::Find(const int &what, int startPos) const {
for (int i = startPos; i < size; i++) {
if (buffer[i] == what) {
return i;
}
}
return -1;
}
void CArray::DeleteAt(int location, int num) {
assert(IsValidIndex(location));
assert(location + num <= size);
for (int i = location; i < size - num; i++) {
buffer[i] = buffer[i + num];
}
for (int i = size - num; i < size; i++) {
buffer[i] = int();
}
size -= num;
}
bool CArray::Has(const int &what) const {
for (int i = 0; i < size; i++) {
if (buffer[i] == what) {
return true;
}
}
return false;
}
void CArray::SetBufferSize(int nElements) {
assert(nElements > maxCapacity);
int *new_buffer = new int[nElements];
for (int i = 0; i < size; i++) {
new_buffer[i] = buffer[i];
}
if (buffer != nullptr) {
delete[]buffer;
}
buffer = new_buffer;
maxCapacity = nElements;
}
// Increases buffer size according to grow politics
void CArray::Grow(int newSize) {
SetBufferSize(newSize);
}
// Replace element at index. Old element is deleted with destructor
// New element copied with copy constructor
void CArray::ReplaceAt(const int &newElem, int location) {
assert(IsValidIndex(location));
buffer[location] = newElem;
}
void CArray::SetSize(int newSize) {
assert(newSize <= maxCapacity);
if (newSize > size) {
size += newSize;
} else {
for (int i = size; i > size - newSize; i--) {
buffer[i] = int();
}
size -= newSize;
}
}
int main() {
CArray array;
CArray arrayB;
arrayB.Add(-4);
arrayB.Add(-3);
arrayB.Add(-2);
array.Add(3);
array.Add(4);
array.Add(6);
array.Add(7);
array.Add(8);
array.Add(1);
array.Add(23, 2);
array.Add(arrayB);
for (int i = 0; i < array.Size(); i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
std::cout << "add two copies of 77 to 6th position" << std::endl;
array.InsertAt(77, 6, 2);
for (int i = 0; i < array.Size(); i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
std::cout << "add copy of 101 to 0th position" << std::endl;
array.InsertAt(101, 0);
for (int i = 0; i < array.Size(); i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
std::cout << "replace elem in the 7th position with 333 " << std::endl;
array.ReplaceAt(333, 7);
for (int i = 0; i < array.Size(); i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
std::cout << "Size and capacity of the array: " << std::endl;
std::cout << array.Size() << " ";
std::cout << array.BufferSize() << std::endl;;
array.DeleteLast();
std::cout << "Remove the last element " << std::endl;
for (int i = 0; i < array.Size(); i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
std::cout << "The first element : " << array.First() << std::endl;
array.CopyTo(arrayB);
std::cout << "First element of the array " << array.First() << std::endl;
std::cout << "Content of A was copied to ArrayB : " << std::endl;
for (int i = 0; i < arrayB.Size(); i++) {
std::cout << arrayB[i] << " ";
}
std::cout << std::endl;
std::cout << "Size and capacity of the arrayB: " << std::endl;
std::cout << arrayB.Size() << " ";
std::cout << arrayB.BufferSize() << std::endl;
std::cout << std::endl;
std::cout << "position of 333 : " << array.Find(333) << " " << std::boolalpha << array.Has(333) << std::endl;
std::cout << std::endl;
array.DeleteAll();
arrayB.MoveTo(array);
for (int i = 0; i < array.Size(); i++) {
std::cout << array[i] << " ";
}
array.DeleteAt(5, 7);
std::cout << std::endl;
for (int i = 0; i < array.Size(); i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
std::cout << std::boolalpha << array.IsValidIndex(4) << std::endl;
std::cout << std::boolalpha << array.IsValidIndex(120) << std::endl;
CArray arrayC;
for(int i =0; i< 16; i++){
arrayC.Add(i);
}
std::cout << std::endl;
for (int i = 0; i < arrayC.Size(); i++) {
std::cout << arrayC[i] << " ";
}
arrayC.InsertAt(77,3,20);
std::cout << std::endl;
for (int i = 0; i < arrayC.Size(); i++) {
std::cout << arrayC[i] << " ";
}
return 0;
}
| [
"tenrakyshka@gmail.com"
] | tenrakyshka@gmail.com |
9d26fb430ea15a7fa407c4a1ea7bcc9636d6cf92 | 45ab5256040b5160b97c6786accb8a60dd4fa0bf | /src/Video/LowLevelRenderer/OpenGL/OpenGLVertexDescription.hpp | 5f9b0923caa516e41d68d2793dd1c4263e9d3905 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | Chainsawkitten/HymnToBeauty | 9e5cb541661a9bdb8e8ee791df8e1f5bd9a790e4 | c3d869482f031a792c1c54c0f78d4cda47c6da09 | refs/heads/main | 2023-07-27T12:40:27.342516 | 2023-06-23T13:15:05 | 2023-06-23T14:08:14 | 33,508,463 | 11 | 4 | MIT | 2023-06-23T14:08:15 | 2015-04-06T22:09:26 | C++ | UTF-8 | C++ | false | false | 1,682 | hpp | #pragma once
#include "../Interface/VertexDescription.hpp"
#include <glad/glad.h>
#include <vector>
namespace Video {
/// OpenGL implementation of VertexDescription.
class OpenGLVertexDescription : public VertexDescription {
public:
/// Describes an OpenGL attribute in a vertex array object.
struct OpenGLAttribute {
/// The location of the attribute in the vertex shader.
GLuint location;
/// The type of each component in the attribute.
GLenum type;
/// The number of components in the attribute.
GLint size;
/// Whether the values should be normalized when accessed.
GLboolean normalized;
/// The offset to the first component in the buffer.
uintptr_t offset;
};
/// Create new OpenGL vertex description.
/**
* @param attributeCount The number of vertex attributes.
* @param attributes The array of attributes.
* @param indexBuffer Whether to use an index buffer.
*/
OpenGLVertexDescription(unsigned int attributeCount, const VertexDescription::Attribute* attributes, bool indexBuffer);
/// Destructor.
~OpenGLVertexDescription() final;
/// Get the stride between vertices.
/**
* @return The stride between vertices in bytes.
*/
unsigned int GetStride() const;
/// Get the attributes.
/**
* @return Descriptions of the attributes in the vertex buffer(s).
*/
const std::vector<OpenGLAttribute>& GetAttributes() const;
private:
OpenGLVertexDescription(const OpenGLVertexDescription& other) = delete;
unsigned int stride;
std::vector<OpenGLAttribute> attributes;
};
}
| [
"catscratchesp@gmail.com"
] | catscratchesp@gmail.com |
8953a3cab682b267aa111b12c331fe411184eb95 | efed4309ce0078e270c0e1f7a84d544901c0be44 | /TankZoneGame/Source/TankZoneGame/Private/AimingComponent.cpp | b0d04752e3b469a9553f2043955518592a698967 | [
"Apache-2.0"
] | permissive | Jakoban2411/TankZone | 6cad995a3a7e6eb6b11ef8c39f8ad707d8f1ec6f | d6d78f21494255bf9509fe81a076a68fd867b3d9 | refs/heads/master | 2020-03-17T01:30:05.794870 | 2018-09-01T17:58:06 | 2018-09-01T17:58:06 | 127,923,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,085 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "AimingComponent.h"
#include"TankTurretComponent.h"
#include"BarrelComponent.h"
#include "Runtime/Engine/Classes/Kismet/GameplayStatics.h"
#include "Runtime/Engine/Classes/Components/StaticMeshComponent.h"
#include "Runtime/Engine/Classes/GameFramework/Actor.h"
#include"Projectile.h"
#include"Runtime/Engine/Classes/Engine/World.h"
// Sets default values for this component's properties
UAimingComponent::UAimingComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
void UAimingComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction * ThisTickFunction)
{
if (Ammo<= 0)
{
FiringStatus = EAimStatus::NOAMMO;
}
else
if ((FPlatformTime::Seconds() - LastLaunchTime) < ReloadTime)
FiringStatus = EAimStatus::RELOADING;
else
{
if (isBarrelMoving())
{
FiringStatus = EAimStatus::AIMING;
}
else
{
FiringStatus = EAimStatus::LOCKED;
}
}
}
void UAimingComponent::BeginPlay()
{
Super::BeginPlay();
LastLaunchTime = FPlatformTime::Seconds();
}
bool UAimingComponent::isBarrelMoving()
{
FVector TankAim = TankBarrel->GetForwardVector();
if (TankAim.Equals(AimedAt, .01))
{
return false;
}
else
return true;
}
void UAimingComponent::AimingLog(FVector AimLocation)
{
if (!TankBarrel)
{
return;
}
FVector LaunchVelocity;
FVector StartLocation = TankBarrel->GetSocketLocation(FName("Projectile"));
if (UGameplayStatics::SuggestProjectileVelocity(this, LaunchVelocity, StartLocation, AimLocation, LaunchSpeed, false, 0.f, 0.f, ESuggestProjVelocityTraceOption::DoNotTrace))
{
AimedAt = LaunchVelocity.GetSafeNormal();
MoveAimTo(AimedAt);
}
}
void UAimingComponent::Initialise(UBarrelComponent* Barrel, UTankTurretComponent * Turret)
{
TankBarrel = Barrel;
TankTurret = Turret;
}
void UAimingComponent::MoveAimTo(FVector AimTurretto)
{
FRotator AimRotator = AimTurretto.Rotation();
FRotator CurrentRotation = TankBarrel->GetForwardVector().Rotation();
FRotator DeltaRotation =AimRotator - CurrentRotation;
if (DeltaRotation.Yaw > 180||DeltaRotation.Yaw <- 180)
DeltaRotation.Yaw = -(DeltaRotation.Yaw - 180);
TankTurret->AimTurret(DeltaRotation.Yaw);
TankBarrel->Elevate(DeltaRotation.Pitch);
}
void UAimingComponent::Fire()
{
if (!ensure(TankBarrel))
{
return;
}
if (Ammo != 0)
{
if (FiringStatus != EAimStatus::RELOADING)
{
AProjectile* LaunchedProjectile = GetWorld()->SpawnActor<AProjectile>(Projectile, TankBarrel->GetSocketLocation(FName("Projectile")), TankBarrel->GetSocketRotation(FName("Projectile")));
if (LaunchedProjectile)
{
Ammo--;
LaunchedProjectile->LaunchProjectile(LaunchSpeed);
LastLaunchTime = FPlatformTime::Seconds();
}
}
}
}
EAimStatus UAimingComponent::CurrentAimStatus()
{
return FiringStatus;
}
int UAimingComponent::AmmoCount()
{
return Ammo;
}
| [
"30558121+Jakoban2411@users.noreply.github.com"
] | 30558121+Jakoban2411@users.noreply.github.com |
61f75093b30d12794a307465dcb243ab08feba42 | 8b8de1a0d51244d2976f06b2dd92dbe0cf896e18 | /src/cage/listener.hpp | 2192deef6691db2232a9aab13388255d38cc1635 | [
"BSL-1.0"
] | permissive | pancpp/cage | 5b8310ce19124259ac8395dd1341bcb45025740b | 3a4eb5e3b6d40e6dee8e61bf984c83bf336e5999 | refs/heads/main | 2022-12-29T12:19:40.750907 | 2020-10-07T18:18:54 | 2020-10-07T18:18:54 | 301,317,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | hpp | /**
* COPYRIGHT (C) 2020 Leyuan Pan ALL RIGHTS RESERVED.
*
* @brief TCP listener.
* @author Leyuan Pan
* @date Oct 04, 2020
*/
#ifndef CAGE_LISTENER_HPP_
#define CAGE_LISTENER_HPP_
#include <memory>
#include "cage/beast.hpp"
#include "cage/boost.hpp"
#include "cage/controller.hpp"
namespace cage {
class Listener : public std::enable_shared_from_this<Listener> {
public:
using ControllerPtr = Controller::SelfPtr;
public:
~Listener() = default;
explicit Listener(asio::io_context &ioc, tcp::endpoint ep,
ControllerPtr p_controller);
void Run();
private:
void DoAccept();
void OnAccept(beast::error_code ec, tcp::socket socket);
private:
asio::io_context &ioc_;
tcp::acceptor acceptor_;
ControllerPtr p_controller_;
};
} // namespace cage
#endif // CAGE_LISTENER_HPP_
| [
"leyuanpan@gmail.com"
] | leyuanpan@gmail.com |
4ebc90ef18318efb64c72b552a52b398d9d76547 | 3154e396406521d7c25ad3e8752e6eda710729c3 | /Position.hpp | 1a7dd28047a86787d63c93d4802fa0957579aa4b | [] | no_license | PetrJanousek/Chess | a1a1d80e8a0aec28ab6842d8700d45ce0f373c51 | f1364d5848e970aa9b1186ada8b5832e54f69373 | refs/heads/master | 2021-06-30T18:16:43.777977 | 2020-12-29T13:03:41 | 2020-12-29T13:03:41 | 198,819,060 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | hpp | //
// Position.hpp
// Chess
//
// Created by Petr Janousek on 05/05/2019.
// Copyright © 2019 Petr Janousek. All rights reserved.
//
#ifndef Position_hpp
#define Position_hpp
#include <iostream>
#include <utility>
#include <memory>
#include <algorithm>
/** Represents the single position on the 2D board */
class Position
{
public:
Position();
/** constructor for Position
@param[in] height The height of the Position on board.
@param[in] width The width of the Position on board.
*/
Position(int height, int width) : height(height), width(width) {};
int height;
int width;
/** Overloaded operator + that adds two positions. */
Position operator + (const Position & pos) const;
/** Overloaded operator == that checks the 2 positions and returns if true they are the same. */
bool operator == (const Position & pos) const;
/** Overloaded operator < that checks if one of the positions is smaller than the second one */
bool operator < (const Position & pos) const;
};
#endif /* Position_hpp */
| [
"noreply@github.com"
] | noreply@github.com |
552b60574bfe0938fe169fd91f778fc682d5b00d | 8dd161563cd3149ca1f8cb7618f767a6dd4105e1 | /src/easybang/resize_and_convert/resize_and_colorcvt.cpp | 246ce365bcde4bc0b913a12f743ada03cb082e1e | [
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | Qthovan/Cambricon_easydk | de5452753cda796bc693dab95da1667d69c1587a | e696bda55c32d5b569afbd0b3869198b9ec9160e | refs/heads/main | 2023-08-14T09:56:38.996582 | 2021-09-14T08:51:53 | 2021-09-14T08:51:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,919 | cpp | /*************************************************************************
* Copyright (C) [2019] by Cambricon, Inc. 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
*
* 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 "easybang/resize_and_colorcvt.h"
#include <algorithm>
#include <deque>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "cxxutil/log.h"
#include "device/mlu_context.h"
#include "internal/mlu_task_queue.h"
using std::string;
extern bool PrepareKernelParam(int d_row, int d_col, int color_mode, int data_type, int batchsize,
bool keep_aspect_ratio, KernelParam** param, int dev_type, int padMethod, string* estr);
extern void FreeKernelParam(KernelParam* param);
extern float ResizeAndConvert(void* dst, void** y_plane_addrs, void** uv_plane_addrs, int** src_whs, int** src_rois_mlu,
int* src_rois_cpu, KernelParam* kparam, cnrtFunctionType_t func_type, cnrtDim3_t dim,
cnrtQueue_t queue, int dev_type, string* estr);
namespace edk {
std::ostream& operator<<(std::ostream& os, const MluResizeConvertOp::InputData& data) {
os << "\n\t y plane attr: " << data.planes[0] << "\n"
<< "\t uv plane attr: " << data.planes[1] << "\n"
<< "\t src w: " << data.src_w << "\n"
<< "\t src h: " << data.src_h << "\n"
<< "\t src stride: " << data.src_stride << "\n"
<< "\t crop x: " << data.crop_x << "\n"
<< "\t crop y: " << data.crop_y << "\n"
<< "\t crop w: " << data.crop_w << "\n"
<< "\t crop h: " << data.crop_h;
return os;
}
class MluResizeConvertPrivate {
public:
MluResizeConvertOp::Attr attr_;
cnrtFunctionType_t ftype_ = CNRT_FUNC_TYPE_BLOCK;
MluTaskQueue_t queue_ = nullptr;
KernelParam* kparam_ = nullptr;
std::deque<MluResizeConvertOp::InputData> input_datas_cache_;
void **y_ptrs_cpu_ = nullptr, **uv_ptrs_cpu_ = nullptr;
void **y_ptrs_mlu_ = nullptr, **uv_ptrs_mlu_ = nullptr;
int** src_whs_mlu_ = nullptr;
int* src_whs_mlu_tmp_ = nullptr;
int* src_whs_cpu_ = nullptr;
int** src_rois_mlu_ = nullptr;
int* src_rois_mlu_tmp_ = nullptr;
int* src_rois_cpu_ = nullptr;
std::string estr_;
bool shared_queue_ = false;
bool PrepareTaskQueue();
};
MluResizeConvertOp::MluResizeConvertOp() { d_ptr_ = new MluResizeConvertPrivate; }
MluResizeConvertOp::~MluResizeConvertOp() {
Destroy();
delete d_ptr_;
d_ptr_ = nullptr;
}
const MluResizeConvertOp::Attr& MluResizeConvertOp::GetAttr() { return d_ptr_->attr_; }
MluTaskQueue_t MluResizeConvertOp::GetMluQueue() const { return d_ptr_->queue_; }
void MluResizeConvertOp::SetMluQueue(MluTaskQueue_t queue) {
if (queue) {
d_ptr_->queue_ = queue;
d_ptr_->shared_queue_ = true;
} else {
LOGW(RESIZE_CONVERT) << "SetMluQueue(): param queue is nullptr";
}
}
bool MluResizeConvertOp::IsSharedQueue() const { return d_ptr_->shared_queue_; }
std::string MluResizeConvertOp::GetLastError() const { return d_ptr_->estr_; }
#define CHECK_CNRT_RET(cnrt_ret, _estr, msg, code, ret_value) \
do { \
if (cnrt_ret != CNRT_RET_SUCCESS) { \
_estr = msg; \
{ code } \
return ret_value; \
} \
} while (0)
bool MluResizeConvertOp::Init(const MluResizeConvertOp::Attr& attr) {
d_ptr_->attr_ = attr;
int batchsize = attr.batch_size;
d_ptr_->y_ptrs_cpu_ = new void*[batchsize];
d_ptr_->uv_ptrs_cpu_ = new void*[batchsize];
cnrtRet_t cnret;
cnret = cnrtMalloc(reinterpret_cast<void**>(&d_ptr_->y_ptrs_mlu_), sizeof(void*) * batchsize);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Malloc mlu buffer failed. cnrt error code:" + std::to_string(cnret), {}, false);
cnret = cnrtMalloc(reinterpret_cast<void**>(&d_ptr_->uv_ptrs_mlu_), sizeof(void*) * batchsize);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Malloc mlu buffer failed. cnrt error code:" + std::to_string(cnret), {}, false);
cnret = cnrtMalloc(reinterpret_cast<void**>(&d_ptr_->src_whs_mlu_tmp_), sizeof(int) * batchsize * 2);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Malloc mlu buffer failed. cnrt error code:" + std::to_string(cnret), {}, false);
d_ptr_->src_whs_cpu_ = new int[batchsize * 2];
cnret = cnrtMalloc(reinterpret_cast<void**>(&d_ptr_->src_rois_mlu_tmp_), sizeof(int) * batchsize * 4);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Malloc mlu buffer failed. cnrt error code:" + std::to_string(cnret), {}, false);
d_ptr_->src_rois_cpu_ = new int[batchsize * 4];
cnret = cnrtMalloc(reinterpret_cast<void**>(&d_ptr_->src_whs_mlu_), sizeof(int*) * batchsize);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Malloc mlu buffer failed. cnrt error code:" + std::to_string(cnret), {}, false);
cnret = cnrtMalloc(reinterpret_cast<void**>(&d_ptr_->src_rois_mlu_), sizeof(int*) * batchsize);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Malloc mlu buffer failed. cnrt error code:" + std::to_string(cnret), {}, false);
int** wh_mlu_ptrs_tmp = new int*[batchsize];
int** roi_mlu_ptrs_tmp = new int*[batchsize];
for (int i = 0; i < batchsize; ++i) {
wh_mlu_ptrs_tmp[i] = d_ptr_->src_whs_mlu_tmp_ + 2 * i;
roi_mlu_ptrs_tmp[i] = d_ptr_->src_rois_mlu_tmp_ + 4 * i;
}
cnret = cnrtMemcpy(reinterpret_cast<void*>(d_ptr_->src_whs_mlu_), reinterpret_cast<void*>(wh_mlu_ptrs_tmp),
sizeof(int*) * batchsize, CNRT_MEM_TRANS_DIR_HOST2DEV);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Memcpy h2d failed. cnrt error code:" + std::to_string(cnret), {}, false);
cnret = cnrtMemcpy(reinterpret_cast<void*>(d_ptr_->src_rois_mlu_), reinterpret_cast<void*>(roi_mlu_ptrs_tmp),
sizeof(int*) * batchsize, CNRT_MEM_TRANS_DIR_HOST2DEV);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Memcpy h2d failed. cnrt error code:" + std::to_string(cnret), {}, false);
delete[] wh_mlu_ptrs_tmp;
delete[] roi_mlu_ptrs_tmp;
int core_number = attr.core_number == 0 ? 4 : attr.core_number;
switch (core_number) {
case 1:
case 4:
case 8:
case 16:
break;
default:
d_ptr_->estr_ = "Unsupport core number. Only support 1, 4, 8, 16";
return false;
}
d_ptr_->attr_.core_number = core_number;
// clang-format off
LOGD(RESIZE_CONVERT) << "Init ResizeAndConvert Operator:\n"
<< "\t [batchsize " + std::to_string(d_ptr_->attr_.batch_size) + "], "
<< "[core_number: " + std::to_string(d_ptr_->attr_.core_number) + "],\n"
<< "\t [keep_aspect_ratio " << d_ptr_->attr_.keep_aspect_ratio << "],\n"
<< "\t [core_version " << static_cast<int>(d_ptr_->attr_.core_version) << "],\n"
<< "\t [color_mode " << static_cast<int>(d_ptr_->attr_.color_mode) << "], "
<< "[data_mode " << static_cast<int>(d_ptr_->attr_.data_mode) << "]\n"
<< "\t [pad_method " << d_ptr_->attr_.padMethod << "]\n";
return ::PrepareKernelParam(d_ptr_->attr_.dst_h, d_ptr_->attr_.dst_w,
static_cast<int>(d_ptr_->attr_.color_mode),
static_cast<int>(d_ptr_->attr_.data_mode),
d_ptr_->attr_.batch_size,
d_ptr_->attr_.keep_aspect_ratio, &d_ptr_->kparam_,
static_cast<int>(d_ptr_->attr_.core_version),
d_ptr_->attr_.padMethod, &d_ptr_->estr_);
// clang-format on
}
bool MluResizeConvertPrivate::PrepareTaskQueue() {
queue_ = MluTaskQueue::Create();
shared_queue_ = false;
return true;
}
void MluResizeConvertOp::BatchingUp(const InputData& input_data) {
InputData t;
t.src_w = input_data.src_w;
t.src_h = input_data.src_h;
if (t.src_h % 2) t.src_h--;
t.src_stride = input_data.src_w > input_data.src_stride ? input_data.src_w : input_data.src_stride;
t.crop_x = input_data.crop_x;
t.crop_y = input_data.crop_y;
t.crop_w = input_data.crop_w == 0 ? t.src_w : input_data.crop_w;
t.crop_w = std::min(t.src_w - t.crop_x, t.crop_w);
t.crop_h = input_data.crop_h == 0 ? t.src_h : input_data.crop_h;
t.crop_h = std::min(t.src_h - t.crop_y, t.crop_h);
t.planes[0] = input_data.planes[0];
t.planes[1] = input_data.planes[1];
LOGT(RESIZE_CONVERT) << "Store resize and convert operator input for batching," << t;
d_ptr_->input_datas_cache_.emplace_back(std::move(t));
}
bool MluResizeConvertOp::SyncOneOutput(void* dst) {
if (nullptr == d_ptr_->queue_) {
LOGI(RESIZE_CONVERT) << "MluTaskQueue has not been set, MluResizeConvertOp will create a new one";
if (!d_ptr_->PrepareTaskQueue()) {
return false;
}
}
if (d_ptr_->input_datas_cache_.size() == 0) {
LOGW(RESIZE_CONVERT) << "No data batched , do nothing.";
return false;
}
// while cache count less than batch size, fill with copy to batch size
while (static_cast<int>(d_ptr_->input_datas_cache_.size()) < d_ptr_->attr_.batch_size) {
d_ptr_->input_datas_cache_.push_back(d_ptr_->input_datas_cache_[0]);
}
for (int bi = 0; bi < d_ptr_->attr_.batch_size; ++bi) {
InputData& input_data = d_ptr_->input_datas_cache_.front();
d_ptr_->y_ptrs_cpu_[bi] = input_data.planes[0];
d_ptr_->uv_ptrs_cpu_[bi] = input_data.planes[1];
d_ptr_->src_whs_cpu_[bi * 2 + 0] = input_data.src_stride;
d_ptr_->src_whs_cpu_[bi * 2 + 1] = input_data.src_h;
d_ptr_->src_rois_cpu_[bi * 4 + 0] = input_data.crop_x;
d_ptr_->src_rois_cpu_[bi * 4 + 1] = input_data.crop_y;
d_ptr_->src_rois_cpu_[bi * 4 + 2] = input_data.crop_w;
d_ptr_->src_rois_cpu_[bi * 4 + 3] = input_data.crop_h;
d_ptr_->input_datas_cache_.pop_front();
}
// clang-format off
cnrtRet_t cnret = cnrtMemcpy(reinterpret_cast<void*>(d_ptr_->y_ptrs_mlu_),
reinterpret_cast<void*>(d_ptr_->y_ptrs_cpu_),
sizeof(void*) * d_ptr_->attr_.batch_size,
CNRT_MEM_TRANS_DIR_HOST2DEV);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Memcpy host to device failed. cnrt error code:" + std::to_string(cnret), {},
false);
cnret = cnrtMemcpy(reinterpret_cast<void*>(d_ptr_->uv_ptrs_mlu_),
reinterpret_cast<void*>(d_ptr_->uv_ptrs_cpu_),
sizeof(void*) * d_ptr_->attr_.batch_size,
CNRT_MEM_TRANS_DIR_HOST2DEV);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Memcpy host to device failed. cnrt error code:" + std::to_string(cnret), {},
false);
cnret = cnrtMemcpy(reinterpret_cast<void*>(d_ptr_->src_whs_mlu_tmp_),
reinterpret_cast<void*>(d_ptr_->src_whs_cpu_),
sizeof(int) * 2 * d_ptr_->attr_.batch_size,
CNRT_MEM_TRANS_DIR_HOST2DEV);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Memcpy width and height failed. cnrt error code:" + std::to_string(cnret), {},
false);
cnret = cnrtMemcpy(reinterpret_cast<void*>(d_ptr_->src_rois_mlu_tmp_),
reinterpret_cast<void*>(d_ptr_->src_rois_cpu_),
sizeof(int) * d_ptr_->attr_.batch_size * 4,
CNRT_MEM_TRANS_DIR_HOST2DEV);
CHECK_CNRT_RET(cnret, d_ptr_->estr_, "Memcpy rois failed. cnrt error code:" + std::to_string(cnret), {}, false);
// clang-format on
cnrtDim3_t dim;
dim.x = 4;
dim.y = d_ptr_->attr_.core_number >= 4 ? d_ptr_->attr_.core_number / 4 : 1;
dim.z = 1;
LOGT(RESIZE_CONVERT) << "(SyncOneOutput) Do resize and convert process, dst: " << dst;
// clang-format off
bool ret = -1 != ::ResizeAndConvert(dst, d_ptr_->y_ptrs_mlu_, d_ptr_->uv_ptrs_mlu_,
d_ptr_->src_whs_mlu_, d_ptr_->src_rois_mlu_,
d_ptr_->src_rois_cpu_,
d_ptr_->kparam_, CNRT_FUNC_TYPE_UNION1, dim,
MluTaskQueueProxy::GetCnrtQueue(d_ptr_->queue_),
static_cast<int>(d_ptr_->attr_.core_version),
&d_ptr_->estr_);
// clang-format on
if (!ret) {
LOGE(RESIZE_CONVERT) << "Resize convert failed. Info: ";
LOGE(RESIZE_CONVERT) << "dst w, dst h: " << d_ptr_->attr_.dst_w << " " << d_ptr_->attr_.dst_h;
LOGE(RESIZE_CONVERT) << "keep aspect ratio: " << d_ptr_->attr_.keep_aspect_ratio;
LOGE(RESIZE_CONVERT) << "batchsize: " << d_ptr_->attr_.batch_size;
auto inputs = GetLastBatchInput();
for (const auto& it : inputs) LOGE(RESIZE_CONVERT) << it;
cnrtMemset(dst, 0, size_t(1) * d_ptr_->attr_.batch_size * d_ptr_->attr_.dst_w * d_ptr_->attr_.dst_h * 4);
if (!IsSharedQueue()) {
// queue becomes invalid when an error occurs.
d_ptr_->queue_ = MluTaskQueue::Create();
}
}
return ret;
}
std::vector<MluResizeConvertOp::InputData> MluResizeConvertOp::GetLastBatchInput() const {
std::vector<MluResizeConvertOp::InputData> datas;
for (int bi = 0; bi < d_ptr_->attr_.batch_size; ++bi) {
InputData t;
t.planes[0] = d_ptr_->y_ptrs_cpu_[bi];
t.planes[1] = d_ptr_->uv_ptrs_cpu_[bi];
t.src_w = d_ptr_->src_whs_cpu_[bi * 2 + 0];
t.src_stride = t.src_w;
t.src_h = d_ptr_->src_whs_cpu_[bi * 2 + 1];
t.crop_x = d_ptr_->src_rois_cpu_[bi * 4 + 0];
t.crop_y = d_ptr_->src_rois_cpu_[bi * 4 + 1];
t.crop_w = d_ptr_->src_rois_cpu_[bi * 4 + 2];
t.crop_h = d_ptr_->src_rois_cpu_[bi * 4 + 3];
datas.emplace_back(std::move(t));
}
return datas;
}
void MluResizeConvertOp::Destroy() {
if (d_ptr_->kparam_) {
::FreeKernelParam(d_ptr_->kparam_);
d_ptr_->kparam_ = nullptr;
}
if (d_ptr_->y_ptrs_cpu_) {
delete[] d_ptr_->y_ptrs_cpu_;
d_ptr_->y_ptrs_cpu_ = nullptr;
}
if (d_ptr_->uv_ptrs_cpu_) {
delete[] d_ptr_->uv_ptrs_cpu_;
d_ptr_->uv_ptrs_cpu_ = nullptr;
}
if (d_ptr_->y_ptrs_mlu_) {
cnrtFree(reinterpret_cast<void*>(d_ptr_->y_ptrs_mlu_));
d_ptr_->y_ptrs_mlu_ = nullptr;
}
if (d_ptr_->uv_ptrs_mlu_) {
cnrtFree(reinterpret_cast<void*>(d_ptr_->uv_ptrs_mlu_));
d_ptr_->uv_ptrs_mlu_ = nullptr;
}
if (d_ptr_->src_whs_mlu_) {
cnrtFree(reinterpret_cast<void*>(d_ptr_->src_whs_mlu_));
d_ptr_->src_whs_mlu_ = nullptr;
}
if (d_ptr_->src_whs_mlu_tmp_) {
cnrtFree(d_ptr_->src_whs_mlu_tmp_);
d_ptr_->src_whs_mlu_tmp_ = nullptr;
}
if (d_ptr_->src_whs_cpu_) {
delete[] d_ptr_->src_whs_cpu_;
d_ptr_->src_whs_cpu_ = nullptr;
}
if (d_ptr_->src_rois_mlu_) {
cnrtFree(reinterpret_cast<void*>(d_ptr_->src_rois_mlu_));
d_ptr_->src_rois_mlu_ = nullptr;
}
if (d_ptr_->src_rois_mlu_tmp_) {
cnrtFree(d_ptr_->src_rois_mlu_tmp_);
d_ptr_->src_rois_mlu_tmp_ = nullptr;
}
if (d_ptr_->src_rois_cpu_) {
delete[] d_ptr_->src_rois_cpu_;
d_ptr_->src_rois_cpu_ = nullptr;
}
d_ptr_->input_datas_cache_.clear();
}
} // namespace edk
| [
"zhn6818@163.com"
] | zhn6818@163.com |
8282014af828cbe3b52bfd7700f9244ed2ae00fd | d8b278cdba97d3f4a8deec2d2bda9a51ea84a5f0 | /s03-fizzbuzz.cpp | 04dd3d9df7bd0d0e67374496ec99622e500cf101 | [] | no_license | s25337/Podstawy-Programowania | 1ccae1f7dad40327573d9f79e45b28c5cf8fbcb4 | 25c21d0e66e8ef973c4ca46bec4695dcc270ea25 | refs/heads/master | 2023-08-19T13:46:55.328075 | 2021-10-26T15:11:13 | 2021-10-26T15:11:13 | 415,608,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 262 | cpp | #include <iostream>
#include <string>
int main(int argc, char* argv[])
{
auto const a=std::stoi(argv[1]);
for(int i=1; i<=a; i++){
std::cout<<i<<" ";
if (i%3==0) std::cout<<"Fizz";
if (i%5==0) std::cout<<"Buzz";
std::cout<<"\n";
}
}
| [
"s25337@pjwstk.edu.pl"
] | s25337@pjwstk.edu.pl |
46841d1ce498ece9697c40dd20f0616cd03ca4b3 | 59255ea212337bb849e640e3108f43764c23f87a | /xrtl/gfx/es3/es3_pixel_format.cc | 50c646bb5f483c5da8a1a099f9db03bf172bbe86 | [
"Apache-2.0"
] | permissive | NeoTim/xrtl | 2aea04e0768590cc68c75c57273c9c221bcc621e | 8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe | refs/heads/master | 2021-09-18T19:37:25.148899 | 2018-07-18T17:48:33 | 2018-07-18T17:48:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,617 | cc | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xrtl/gfx/es3/es3_pixel_format.h"
namespace xrtl {
namespace gfx {
namespace es3 {
bool ConvertPixelFormatToTextureParams(PixelFormat pixel_format,
ES3TextureParams* out_texture_params) {
static const ES3TextureParams kTable[] = {
{GL_NONE, GL_NONE, GL_NONE}, // kUndefined
//
{GL_RGBA4, GL_RGBA, GL_UNSIGNED_BYTE}, // kR4G4B4A4UNorm
{GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5}, // kR5G6B5UNorm
{GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1}, // kR5G5B5A1UNorm
//
{GL_R8, GL_RED, GL_UNSIGNED_BYTE}, // kR8UNorm
{GL_R8_SNORM, GL_RED, GL_BYTE}, // kR8SNorm
{GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE}, // kR8UInt
{GL_R8I, GL_RED_INTEGER, GL_BYTE}, // kR8SInt
//
{GL_RG8, GL_RG, GL_UNSIGNED_BYTE}, // kR8G8UNorm
{GL_RG8_SNORM, GL_RG, GL_BYTE}, // kR8G8SNorm
{GL_RG8UI, GL_RG_INTEGER, GL_UNSIGNED_BYTE}, // kR8G8UInt
{GL_RG8I, GL_RG_INTEGER, GL_BYTE}, // kR8G8SInt
//
{GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE}, // kR8G8B8A8UNorm
{GL_RGBA8_SNORM, GL_RGBA, GL_BYTE}, // kR8G8B8A8SNorm
{GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE}, // kR8G8B8A8UInt
{GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE}, // kR8G8B8A8SInt
{GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE}, // kR8G8B8A8Srgb
//
{GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE}, // kB8G8R8A8UNorm
{GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE}, // kB8G8R8A8Srgb
//
{GL_RGB10_A2, GL_RGBA, //
GL_UNSIGNED_INT_2_10_10_10_REV}, // kA2B10G10R10UNorm
{GL_RGB10_A2, GL_RGBA, //
GL_UNSIGNED_INT_2_10_10_10_REV}, // kA2B10G10R10SNorm
{GL_RGB10_A2UI, GL_RGBA_INTEGER, //
GL_UNSIGNED_INT_2_10_10_10_REV}, // kA2B10G10R10UInt
{GL_RGB10_A2UI, GL_RGBA_INTEGER, //
GL_UNSIGNED_INT_2_10_10_10_REV}, // kA2B10G10R10SInt
//
{GL_R16F, GL_RED, GL_HALF_FLOAT}, // kR16UNorm
{GL_R16F, GL_RED, GL_HALF_FLOAT}, // kR16SNorm
{GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT}, // kR16UInt
{GL_R16I, GL_RED_INTEGER, GL_SHORT}, // kR16SInt
{GL_R16F, GL_RED, GL_HALF_FLOAT}, // kR16SFloat
//
{GL_RG16F, GL_RG, GL_HALF_FLOAT}, // kR16G16UNorm
{GL_RG16F, GL_RG, GL_HALF_FLOAT}, // kR16G16SNorm
{GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT}, // kR16G16UInt
{GL_RG16I, GL_RG_INTEGER, GL_SHORT}, // kR16G16SInt
{GL_RG16F, GL_RG, GL_HALF_FLOAT}, // kR16G16SFloat
//
{GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT}, // kR16G16B16A16UNorm
{GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT}, // kR16G16B16A16SNorm
{GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT}, // kR16G16B16A16UInt
{GL_RGBA16I, GL_RGBA_INTEGER, GL_SHORT}, // kR16G16B16A16SInt
{GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT}, // kR16G16B16A16SFloat
//
{GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT}, // kR32UInt
{GL_R32I, GL_RED_INTEGER, GL_INT}, // kR32SInt
{GL_R32F, GL_RED, GL_FLOAT}, // kR32SFloat
//
{GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT}, // kR32G32UInt
{GL_RG32I, GL_RG_INTEGER, GL_INT}, // kR32G32SInt
{GL_RG32F, GL_RG, GL_FLOAT}, // kR32G32SFloat
//
{GL_RGB32UI, GL_RGB_INTEGER, GL_UNSIGNED_INT}, // kR32G32B32UInt
{GL_RGB32I, GL_RGB_INTEGER, GL_INT}, // kR32G32B32SInt
{GL_RGB32F, GL_RGB, GL_FLOAT}, // kR32G32B32SFloat
//
{GL_R32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT}, // kR32G32B32A32UInt
{GL_RGBA32I, GL_RGBA_INTEGER, GL_INT}, // kR32G32B32A32SInt
{GL_RGBA32F, GL_RGBA, GL_FLOAT}, // kR32G32B32A32SFloat
//
{GL_R11F_G11F_B10F, GL_RGB, //
GL_UNSIGNED_INT_10F_11F_11F_REV}, // kB10G11R11UFloat
{GL_RGB9_E5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV}, // kE5B9G9R9UFloat
//
{GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT}, // kD32SFloat
{GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, //
GL_UNSIGNED_INT_24_8}, // kD24UNormS8UInt
{GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, //
GL_FLOAT_32_UNSIGNED_INT_24_8_REV}, // kD32SFloatS8UInt
//
{GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, GL_NONE}, // kBC1RGBAUNorm
{GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV, GL_RGBA, //
GL_NONE}, // kBC1RGBASrgb
{GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, GL_NONE}, // kBC2UNorm
{GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV, GL_RGBA, GL_NONE}, // kBC2Srgb
{GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, GL_NONE}, // kBC3UNorm
{GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV, GL_RGBA, GL_NONE}, // kBC3Srgb
{GL_NONE, GL_NONE, GL_NONE}, // kBC4UNorm
{GL_NONE, GL_NONE, GL_NONE}, // kBC4SNorm
{GL_NONE, GL_NONE, GL_NONE}, // kBC5UNorm
{GL_NONE, GL_NONE, GL_NONE}, // kBC5SNorm
{GL_NONE, GL_NONE, GL_NONE}, // kBC6HUFloat
{GL_NONE, GL_NONE, GL_NONE}, // kBC6HSFloat
{GL_NONE, GL_NONE, GL_NONE}, // kBC7UNorm
{GL_NONE, GL_NONE, GL_NONE}, // kBC7Srgb
//
{GL_COMPRESSED_RGB8_ETC2, GL_RGB, GL_NONE}, // kEtc2R8G8B8UNorm
{GL_COMPRESSED_SRGB8_ETC2, GL_RGB, GL_NONE}, // kEtc2R8G8B8Srgb
{GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_RGBA, //
GL_NONE}, // kEtc2R8G8B8A1UNorm
{GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_RGBA, //
GL_NONE}, // kEtc2R8G8B8A1Srgb
{GL_COMPRESSED_RGBA8_ETC2_EAC, GL_RGBA, GL_NONE}, // kEtc2R8G8B8A8UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, GL_RGBA, //
GL_NONE}, // kEtc2R8G8B8A8Srgb
//
{GL_COMPRESSED_R11_EAC, GL_RED, GL_NONE}, // kEacR11UNorm
{GL_COMPRESSED_SIGNED_R11_EAC, GL_RED, GL_NONE}, // kEacR11SNorm
{GL_COMPRESSED_RG11_EAC, GL_RG, GL_NONE}, // kEacR11G11UNorm
{GL_COMPRESSED_SIGNED_RG11_EAC, GL_RED, GL_NONE}, // kEacR11G11SNorm
//
{GL_COMPRESSED_RGBA_ASTC_4x4, GL_RGBA, GL_NONE}, // kAstc4x4UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4, GL_RGBA, GL_NONE}, // kAstc4x4Srgb
{GL_COMPRESSED_RGBA_ASTC_5x4, GL_RGBA, GL_NONE}, // kAstc5x4UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4, GL_RGBA, GL_NONE}, // kAstc5x4Srgb
{GL_COMPRESSED_RGBA_ASTC_5x5, GL_RGBA, GL_NONE}, // kAstc5x5UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5, GL_RGBA, GL_NONE}, // kAstc5x5Srgb
{GL_COMPRESSED_RGBA_ASTC_6x5, GL_RGBA, GL_NONE}, // kAstc6x5UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5, GL_RGBA, GL_NONE}, // kAstc6x5Srgb
{GL_COMPRESSED_RGBA_ASTC_6x6, GL_RGBA, GL_NONE}, // kAstc6x6UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6, GL_RGBA, GL_NONE}, // kAstc6x6Srgb
{GL_COMPRESSED_RGBA_ASTC_8x5, GL_RGBA, GL_NONE}, // kAstc8x5UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5, GL_RGBA, GL_NONE}, // kAstc8x5Srgb
{GL_COMPRESSED_RGBA_ASTC_8x6, GL_RGBA, GL_NONE}, // kAstc8x6UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6, GL_RGBA, GL_NONE}, // kAstc8x6Srgb
{GL_COMPRESSED_RGBA_ASTC_8x8, GL_RGBA, GL_NONE}, // kAstc8x8UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8, GL_RGBA, GL_NONE}, // kAstc8x8Srgb
{GL_COMPRESSED_RGBA_ASTC_10x5, GL_RGBA, GL_NONE}, // kAstc10x5UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5, GL_RGBA, //
GL_NONE}, // kAstc10x5Srgb
{GL_COMPRESSED_RGBA_ASTC_10x6, GL_RGBA, GL_NONE}, // kAstc10x6UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6, GL_RGBA, //
GL_NONE}, // kAstc10x6Srgb
{GL_COMPRESSED_RGBA_ASTC_10x8, GL_RGBA, GL_NONE}, // kAstc10x8UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8, GL_RGBA, //
GL_NONE}, // kAstc10x8Srgb
{GL_COMPRESSED_RGBA_ASTC_10x10, GL_RGBA, GL_NONE}, // kAstc10x10UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10, GL_RGBA, //
GL_NONE}, // kAstc10x10Srgb
{GL_COMPRESSED_RGBA_ASTC_12x10, GL_RGBA, GL_NONE}, // kAstc12x10UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10, GL_RGBA, //
GL_NONE}, // kAstc12x10Srgb
{GL_COMPRESSED_RGBA_ASTC_12x12, GL_RGBA, GL_NONE}, // kAstc12x12UNorm
{GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12, GL_RGBA, //
GL_NONE}, // kAstc12x12Srgb
};
static const PixelFormatTable<ES3TextureParams, PixelFormats::kUndefined,
PixelFormats::kAstc12x12Srgb>
kLookupTable(kTable);
const auto& texture_params = kLookupTable.Find(pixel_format.unique_id());
if (texture_params.internal_format == GL_NONE) {
return false;
}
*out_texture_params = texture_params;
return true;
}
} // namespace es3
} // namespace gfx
} // namespace xrtl
| [
"ben.vanik@gmail.com"
] | ben.vanik@gmail.com |
4cb26f921e19c00163c31218a36379a2026e15f4 | b1ba2df3017725be0703747da5bc58d1395e9a23 | /C++/programming_fundamentals/operators_n_expr/Question1/main.cpp | d52732a13d96e66b6c2a180a1899d18affce2d01 | [] | no_license | ElijahAhianyo/TLC3_LABS | edf2247d81ea538aecb4c53ebbc5642568e8ffbe | 446529a13a3de64f54c29070dcb7b38b52e0138d | refs/heads/main | 2023-03-02T01:42:42.581954 | 2021-02-04T21:37:47 | 2021-02-04T21:37:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | #include <iostream>
using namespace std;
char getChar() {
static char c;
cin >> c;
return c;
}
int main(void) {
char c;
int limit = 2;
int i = 0;
if (i < limit-1) {
c = getchar();
if (c != '\n')
if ( c != 'A')
cout << c << endl;
}
return 0;
}
| [
"nafiushaibu1@gmail.com"
] | nafiushaibu1@gmail.com |
6489f386d292f110283b0a9f5923e6d962777e69 | 91e4a4f778b00748bd70e0e7e3d608e6b2060f26 | /Stacks n Queues/queuefilesir.h | c5e2adcefea18c16e78db67252fb180b36776898 | [] | no_license | Devansh707/DSA-In-CPP | d0d70f52667cfc7052fcc07bd2eb5dabed5aae8e | 28c4eb0e5fc7157785e21679cefbc479aa265cc4 | refs/heads/main | 2023-07-05T01:22:37.436819 | 2021-08-13T05:17:26 | 2021-08-13T05:17:26 | 395,246,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | h | #include<iostream>
using namespace std;
template <typename T>
class Queue
{
T *data;
int ni;
int fi;
int size;
int capacity;
public:
Queue(int s){
data = new T[s];
this->ni = 0;
this->fi = -1;
this->size = 0;
this->capacity = s;
}
int getsize(){
cout<<"size = ";
return size;
}
bool isempty(){
return size==0;
}
void enqueue(T element){
if(size == capacity){
cout<<"Queue is full"<<endl;
return;
}
data[ni] = element;
ni = (ni + 1) % capacity;
size++;
if(fi == -1){
fi = 0;
}
}
T front(){
if(isempty()){
cout<<"queue is empty"<<endl;
return 0;
}
cout<<"front element = ";
return data[fi];
}
T dequeue(){
if(isempty()){
cout<<"queue is empty"<<endl;
return 0;
}
cout<<"dequeued element = ";
T ans = data[fi];
fi = (fi + 1)% capacity;
size--;
if(size == 0){
fi = -1;
ni = 0;
}
return ans;
}
void display(){
if(isempty()){
cout<<"queue underflow"<<endl;
return;
}
if(ni >= fi){
for(int i=fi;i<=ni;i++){
cout<<data[i]<<endl;
}
}
else{
for(int i=fi;i<capacity;i++){
cout<<data[i]<<endl;
}
for(int i=0;i<=ni;i++){
cout<<data[i]<<endl;
}
}
}
int i(){
cout<<"first index = ";
return fi;
}
int nextind(){
cout<<"next index = ";
return ni;
}
};
| [
"devanshsrivastava707@gmail.com"
] | devanshsrivastava707@gmail.com |
f8c13dc83ac2098ad31bbd91eabee2eb715d1e73 | 71303b7650b9f4065acec961b020eeb7d3f68fcd | /Level Up/Developer/Services/Math/MatrixContainer/MatrixContainer.h | 8aaf7b79f8fe5f79a230d605e5775b118819e212 | [] | no_license | erdnaxela01/LevelUp-Engine | 21990104a68dedf3d28569aabb3c40e2f0e82bb0 | bfbb3d51e11585c71338e0a222183d3c6b52ec1e | refs/heads/master | 2021-01-10T19:43:26.792575 | 2015-06-22T02:19:15 | 2015-06-22T02:19:15 | 34,343,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | h | #ifndef __MATRIXCONTAINER_H
#define __MATRIXCONTAINER_H
#include "../DataTypes.h"
namespace LevelUp
{
/*
abstract class in order to change what matrix it contains
*/
class MatrixContainer
{
public:
MatrixContainer() {};
virtual ~MatrixContainer() {};
//set a float at a specific location
virtual void setFloatAt(int r, int c, LVLfloat f) = 0;
//get the float at a specific location
virtual LVLfloat getFloatAt(int r, int c) = 0;
};
}
#endif | [
"alex._s@hotmail.com"
] | alex._s@hotmail.com |
6860ddad2b4da2f0c712d7fe72ede80238763fe4 | 56a24d7af6e752904b2c329af1adf567fb2e6598 | /src/worker.cpp | e15589b345782b7816b37a9567e79c9f53f1df7e | [
"Apache-2.0"
] | permissive | yinquan529/platform-external-stressapptest | 8bae97f262ff0431ae4abc32fbafcb7256f25f37 | d12d97fbbf24ef78f579f723f25791f94cac4176 | refs/heads/master | 2016-09-06T02:33:43.129658 | 2012-04-08T09:45:21 | 2012-04-08T09:45:21 | 31,217,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105,014 | cpp | // Copyright 2006 Google Inc. 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.
// worker.cc : individual tasks that can be run in combination to
// stress the system
#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/times.h>
// These are necessary, but on by default
// #define __USE_GNU
// #define __USE_LARGEFILE64
#include <fcntl.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <linux/unistd.h> // for gettid
// For size of block device
#include <sys/ioctl.h>
#include <linux/fs.h>
#ifdef HAVE_LIBAIO_H
// For asynchronous I/O
#include <libaio.h>
#endif
#include <sys/syscall.h>
#include <set>
#include <string>
// This file must work with autoconf on its public version,
// so these includes are correct.
#include "error_diag.h" // NOLINT
#include "os.h" // NOLINT
#include "pattern.h" // NOLINT
#include "queue.h" // NOLINT
#include "sat.h" // NOLINT
#include "sattypes.h" // NOLINT
#include "worker.h" // NOLINT
// Syscalls
// Why ubuntu, do you hate gettid so bad?
#if !defined(__NR_gettid)
#define __NR_gettid 224
#endif
#define gettid() syscall(__NR_gettid)
#if !defined(CPU_SETSIZE)
_syscall3(int, sched_getaffinity, pid_t, pid,
unsigned int, len, cpu_set_t*, mask)
_syscall3(int, sched_setaffinity, pid_t, pid,
unsigned int, len, cpu_set_t*, mask)
#endif
#ifdef HAVE_LIBAIO_H
// Linux aio syscalls.
#if !defined(__NR_io_setup)
#error "No aio headers inculded, please install libaio."
#endif
#endif
namespace {
// Get HW core ID from cpuid instruction.
inline int apicid(void) {
int cpu;
#if defined(STRESSAPPTEST_CPU_X86_64) || defined(STRESSAPPTEST_CPU_I686)
__asm __volatile("cpuid" : "=b" (cpu) : "a" (1) : "cx", "dx");
#elif defined(STRESSAPPTEST_CPU_ARMV7A)
#warning "Unsupported CPU type ARMV7A: unable to determine core ID."
cpu = 0;
#else
#warning "Unsupported CPU type: unable to determine core ID."
cpu = 0;
#endif
return (cpu >> 24);
}
// Work around the sad fact that there are two (gnu, xsi) incompatible
// versions of strerror_r floating around google. Awesome.
bool sat_strerror(int err, char *buf, int len) {
buf[0] = 0;
char *errmsg = reinterpret_cast<char*>(strerror_r(err, buf, len));
int retval = reinterpret_cast<int64>(errmsg);
if (retval == 0)
return true;
if (retval == -1)
return false;
if (errmsg != buf) {
strncpy(buf, errmsg, len);
buf[len - 1] = 0;
}
return true;
}
inline uint64 addr_to_tag(void *address) {
return reinterpret_cast<uint64>(address);
}
}
#if !defined(O_DIRECT)
// Sometimes this isn't available.
// Disregard if it's not defined.
#define O_DIRECT 0
#endif
// A struct to hold captured errors, for later reporting.
struct ErrorRecord {
uint64 actual; // This is the actual value read.
uint64 reread; // This is the actual value, reread.
uint64 expected; // This is what it should have been.
uint64 *vaddr; // This is where it was (or wasn't).
char *vbyteaddr; // This is byte specific where the data was (or wasn't).
uint64 paddr; // This is the bus address, if available.
uint64 *tagvaddr; // This holds the tag value if this data was tagged.
uint64 tagpaddr; // This holds the physical address corresponding to the tag.
};
// This is a helper function to create new threads with pthreads.
static void *ThreadSpawnerGeneric(void *ptr) {
WorkerThread *worker = static_cast<WorkerThread*>(ptr);
worker->StartRoutine();
return NULL;
}
void WorkerStatus::Initialize() {
sat_assert(0 == pthread_mutex_init(&num_workers_mutex_, NULL));
sat_assert(0 == pthread_rwlock_init(&status_rwlock_, NULL));
sat_assert(0 == pthread_barrier_init(&pause_barrier_,
num_workers_ + 1));
}
void WorkerStatus::Destroy() {
sat_assert(0 == pthread_mutex_destroy(&num_workers_mutex_));
sat_assert(0 == pthread_rwlock_destroy(&status_rwlock_));
sat_assert(0 == pthread_barrier_destroy(&pause_barrier_));
}
void WorkerStatus::PauseWorkers() {
if (SetStatus(PAUSE) != PAUSE)
WaitOnPauseBarrier();
}
void WorkerStatus::ResumeWorkers() {
if (SetStatus(RUN) == PAUSE)
WaitOnPauseBarrier();
}
void WorkerStatus::StopWorkers() {
if (SetStatus(STOP) == PAUSE)
WaitOnPauseBarrier();
}
bool WorkerStatus::ContinueRunning() {
// This loop is an optimization. We use it to immediately re-check the status
// after resuming from a pause, instead of returning and waiting for the next
// call to this function.
for (;;) {
switch (GetStatus()) {
case RUN:
return true;
case PAUSE:
// Wait for the other workers to call this function so that
// PauseWorkers() can return.
WaitOnPauseBarrier();
// Wait for ResumeWorkers() to be called.
WaitOnPauseBarrier();
break;
case STOP:
return false;
}
}
}
bool WorkerStatus::ContinueRunningNoPause() {
return (GetStatus() != STOP);
}
void WorkerStatus::RemoveSelf() {
// Acquire a read lock on status_rwlock_ while (status_ != PAUSE).
for (;;) {
AcquireStatusReadLock();
if (status_ != PAUSE)
break;
// We need to obey PauseWorkers() just like ContinueRunning() would, so that
// the other threads won't wait on pause_barrier_ forever.
ReleaseStatusLock();
// Wait for the other workers to call this function so that PauseWorkers()
// can return.
WaitOnPauseBarrier();
// Wait for ResumeWorkers() to be called.
WaitOnPauseBarrier();
}
// This lock would be unnecessary if we held a write lock instead of a read
// lock on status_rwlock_, but that would also force all threads calling
// ContinueRunning() to wait on this one. Using a separate lock avoids that.
AcquireNumWorkersLock();
// Decrement num_workers_ and reinitialize pause_barrier_, which we know isn't
// in use because (status != PAUSE).
sat_assert(0 == pthread_barrier_destroy(&pause_barrier_));
sat_assert(0 == pthread_barrier_init(&pause_barrier_, num_workers_));
--num_workers_;
ReleaseNumWorkersLock();
// Release status_rwlock_.
ReleaseStatusLock();
}
// Parent thread class.
WorkerThread::WorkerThread() {
status_ = false;
pages_copied_ = 0;
errorcount_ = 0;
runduration_usec_ = 1;
priority_ = Normal;
worker_status_ = NULL;
thread_spawner_ = &ThreadSpawnerGeneric;
tag_mode_ = false;
}
WorkerThread::~WorkerThread() {}
// Constructors. Just init some default values.
FillThread::FillThread() {
num_pages_to_fill_ = 0;
}
// Initialize file name to empty.
FileThread::FileThread() {
filename_ = "";
devicename_ = "";
pass_ = 0;
page_io_ = true;
crc_page_ = -1;
local_page_ = NULL;
}
// If file thread used bounce buffer in memory, account for the extra
// copy for memory bandwidth calculation.
float FileThread::GetMemoryCopiedData() {
if (!os_->normal_mem())
return GetCopiedData();
else
return 0;
}
// Initialize target hostname to be invalid.
NetworkThread::NetworkThread() {
snprintf(ipaddr_, sizeof(ipaddr_), "Unknown");
sock_ = 0;
}
// Initialize?
NetworkSlaveThread::NetworkSlaveThread() {
}
// Initialize?
NetworkListenThread::NetworkListenThread() {
}
// Init member variables.
void WorkerThread::InitThread(int thread_num_init,
class Sat *sat_init,
class OsLayer *os_init,
class PatternList *patternlist_init,
WorkerStatus *worker_status) {
sat_assert(worker_status);
worker_status->AddWorkers(1);
thread_num_ = thread_num_init;
sat_ = sat_init;
os_ = os_init;
patternlist_ = patternlist_init;
worker_status_ = worker_status;
AvailableCpus(&cpu_mask_);
tag_ = 0xffffffff;
tag_mode_ = sat_->tag_mode();
}
// Use pthreads to prioritize a system thread.
bool WorkerThread::InitPriority() {
// This doesn't affect performance that much, and may not be too safe.
bool ret = BindToCpus(&cpu_mask_);
if (!ret)
logprintf(11, "Log: Bind to %s failed.\n",
cpuset_format(&cpu_mask_).c_str());
logprintf(11, "Log: Thread %d running on apic ID %d mask %s (%s).\n",
thread_num_, apicid(),
CurrentCpusFormat().c_str(),
cpuset_format(&cpu_mask_).c_str());
#if 0
if (priority_ == High) {
sched_param param;
param.sched_priority = 1;
// Set the priority; others are unchanged.
logprintf(0, "Log: Changing priority to SCHED_FIFO %d\n",
param.sched_priority);
if (sched_setscheduler(0, SCHED_FIFO, ¶m)) {
char buf[256];
sat_strerror(errno, buf, sizeof(buf));
logprintf(0, "Process Error: sched_setscheduler "
"failed - error %d %s\n",
errno, buf);
}
}
#endif
return true;
}
// Use pthreads to create a system thread.
int WorkerThread::SpawnThread() {
// Create the new thread.
int result = pthread_create(&thread_, NULL, thread_spawner_, this);
if (result) {
char buf[256];
sat_strerror(result, buf, sizeof(buf));
logprintf(0, "Process Error: pthread_create "
"failed - error %d %s\n", result,
buf);
status_ = false;
return false;
}
// 0 is pthreads success.
return true;
}
// Kill the worker thread with SIGINT.
bool WorkerThread::KillThread() {
return (pthread_kill(thread_, SIGINT) == 0);
}
// Block until thread has exited.
bool WorkerThread::JoinThread() {
int result = pthread_join(thread_, NULL);
if (result) {
logprintf(0, "Process Error: pthread_join failed - error %d\n", result);
status_ = false;
}
// 0 is pthreads success.
return (!result);
}
void WorkerThread::StartRoutine() {
InitPriority();
StartThreadTimer();
Work();
StopThreadTimer();
worker_status_->RemoveSelf();
}
// Thread work loop. Execute until marked finished.
bool WorkerThread::Work() {
do {
logprintf(9, "Log: ...\n");
// Sleep for 1 second.
sat_sleep(1);
} while (IsReadyToRun());
return false;
}
// Returns CPU mask of CPUs available to this process,
// Conceptually, each bit represents a logical CPU, ie:
// mask = 3 (11b): cpu0, 1
// mask = 13 (1101b): cpu0, 2, 3
bool WorkerThread::AvailableCpus(cpu_set_t *cpuset) {
CPU_ZERO(cpuset);
return sched_getaffinity(getppid(), sizeof(*cpuset), cpuset) == 0;
}
// Returns CPU mask of CPUs this thread is bound to,
// Conceptually, each bit represents a logical CPU, ie:
// mask = 3 (11b): cpu0, 1
// mask = 13 (1101b): cpu0, 2, 3
bool WorkerThread::CurrentCpus(cpu_set_t *cpuset) {
CPU_ZERO(cpuset);
return sched_getaffinity(0, sizeof(*cpuset), cpuset) == 0;
}
// Bind worker thread to specified CPU(s)
// Args:
// thread_mask: cpu_set_t representing CPUs, ie
// mask = 1 (01b): cpu0
// mask = 3 (11b): cpu0, 1
// mask = 13 (1101b): cpu0, 2, 3
//
// Returns true on success, false otherwise.
bool WorkerThread::BindToCpus(const cpu_set_t *thread_mask) {
cpu_set_t process_mask;
AvailableCpus(&process_mask);
if (cpuset_isequal(thread_mask, &process_mask))
return true;
logprintf(11, "Log: available CPU mask - %s\n",
cpuset_format(&process_mask).c_str());
if (!cpuset_issubset(thread_mask, &process_mask)) {
// Invalid cpu_mask, ie cpu not allocated to this process or doesn't exist.
logprintf(0, "Log: requested CPUs %s not a subset of available %s\n",
cpuset_format(thread_mask).c_str(),
cpuset_format(&process_mask).c_str());
return false;
}
return (sched_setaffinity(gettid(), sizeof(*thread_mask), thread_mask) == 0);
}
// A worker thread can yield itself to give up CPU until it's scheduled again.
// Returns true on success, false on error.
bool WorkerThread::YieldSelf() {
return (sched_yield() == 0);
}
// Fill this page with its pattern.
bool WorkerThread::FillPage(struct page_entry *pe) {
// Error check arguments.
if (pe == 0) {
logprintf(0, "Process Error: Fill Page entry null\n");
return 0;
}
// Mask is the bitmask of indexes used by the pattern.
// It is the pattern size -1. Size is always a power of 2.
uint64 *memwords = static_cast<uint64*>(pe->addr);
int length = sat_->page_length();
if (tag_mode_) {
// Select tag or data as appropriate.
for (int i = 0; i < length / wordsize_; i++) {
datacast_t data;
if ((i & 0x7) == 0) {
data.l64 = addr_to_tag(&memwords[i]);
} else {
data.l32.l = pe->pattern->pattern(i << 1);
data.l32.h = pe->pattern->pattern((i << 1) + 1);
}
memwords[i] = data.l64;
}
} else {
// Just fill in untagged data directly.
for (int i = 0; i < length / wordsize_; i++) {
datacast_t data;
data.l32.l = pe->pattern->pattern(i << 1);
data.l32.h = pe->pattern->pattern((i << 1) + 1);
memwords[i] = data.l64;
}
}
return 1;
}
// Tell the thread how many pages to fill.
void FillThread::SetFillPages(int64 num_pages_to_fill_init) {
num_pages_to_fill_ = num_pages_to_fill_init;
}
// Fill this page with a random pattern.
bool FillThread::FillPageRandom(struct page_entry *pe) {
// Error check arguments.
if (pe == 0) {
logprintf(0, "Process Error: Fill Page entry null\n");
return 0;
}
if ((patternlist_ == 0) || (patternlist_->Size() == 0)) {
logprintf(0, "Process Error: No data patterns available\n");
return 0;
}
// Choose a random pattern for this block.
pe->pattern = patternlist_->GetRandomPattern();
if (pe->pattern == 0) {
logprintf(0, "Process Error: Null data pattern\n");
return 0;
}
// Actually fill the page.
return FillPage(pe);
}
// Memory fill work loop. Execute until alloted pages filled.
bool FillThread::Work() {
bool result = true;
logprintf(9, "Log: Starting fill thread %d\n", thread_num_);
// We want to fill num_pages_to_fill pages, and
// stop when we've filled that many.
// We also want to capture early break
struct page_entry pe;
int64 loops = 0;
while (IsReadyToRun() && (loops < num_pages_to_fill_)) {
result = result && sat_->GetEmpty(&pe);
if (!result) {
logprintf(0, "Process Error: fill_thread failed to pop pages, "
"bailing\n");
break;
}
// Fill the page with pattern
result = result && FillPageRandom(&pe);
if (!result) break;
// Put the page back on the queue.
result = result && sat_->PutValid(&pe);
if (!result) {
logprintf(0, "Process Error: fill_thread failed to push pages, "
"bailing\n");
break;
}
loops++;
}
// Fill in thread status.
pages_copied_ = loops;
status_ = result;
logprintf(9, "Log: Completed %d: Fill thread. Status %d, %d pages filled\n",
thread_num_, status_, pages_copied_);
return result;
}
// Print error information about a data miscompare.
void WorkerThread::ProcessError(struct ErrorRecord *error,
int priority,
const char *message) {
char dimm_string[256] = "";
int apic_id = apicid();
// Determine if this is a write or read error.
os_->Flush(error->vaddr);
error->reread = *(error->vaddr);
char *good = reinterpret_cast<char*>(&(error->expected));
char *bad = reinterpret_cast<char*>(&(error->actual));
sat_assert(error->expected != error->actual);
unsigned int offset = 0;
for (offset = 0; offset < (sizeof(error->expected) - 1); offset++) {
if (good[offset] != bad[offset])
break;
}
error->vbyteaddr = reinterpret_cast<char*>(error->vaddr) + offset;
// Find physical address if possible.
error->paddr = os_->VirtualToPhysical(error->vbyteaddr);
// Pretty print DIMM mapping if available.
os_->FindDimm(error->paddr, dimm_string, sizeof(dimm_string));
// Report parseable error.
if (priority < 5) {
// Run miscompare error through diagnoser for logging and reporting.
os_->error_diagnoser_->AddMiscompareError(dimm_string,
reinterpret_cast<uint64>
(error->vaddr), 1);
logprintf(priority,
"%s: miscompare on CPU %d(0x%s) at %p(0x%llx:%s): "
"read:0x%016llx, reread:0x%016llx expected:0x%016llx\n",
message,
apic_id,
CurrentCpusFormat().c_str(),
error->vaddr,
error->paddr,
dimm_string,
error->actual,
error->reread,
error->expected);
}
// Overwrite incorrect data with correct data to prevent
// future miscompares when this data is reused.
*(error->vaddr) = error->expected;
os_->Flush(error->vaddr);
}
// Print error information about a data miscompare.
void FileThread::ProcessError(struct ErrorRecord *error,
int priority,
const char *message) {
char dimm_string[256] = "";
// Determine if this is a write or read error.
os_->Flush(error->vaddr);
error->reread = *(error->vaddr);
char *good = reinterpret_cast<char*>(&(error->expected));
char *bad = reinterpret_cast<char*>(&(error->actual));
sat_assert(error->expected != error->actual);
unsigned int offset = 0;
for (offset = 0; offset < (sizeof(error->expected) - 1); offset++) {
if (good[offset] != bad[offset])
break;
}
error->vbyteaddr = reinterpret_cast<char*>(error->vaddr) + offset;
// Find physical address if possible.
error->paddr = os_->VirtualToPhysical(error->vbyteaddr);
// Pretty print DIMM mapping if available.
os_->FindDimm(error->paddr, dimm_string, sizeof(dimm_string));
// If crc_page_ is valid, ie checking content read back from file,
// track src/dst memory addresses. Otherwise catagorize as general
// mememory miscompare for CRC checking everywhere else.
if (crc_page_ != -1) {
int miscompare_byteoffset = static_cast<char*>(error->vbyteaddr) -
static_cast<char*>(page_recs_[crc_page_].dst);
os_->error_diagnoser_->AddHDDMiscompareError(devicename_,
crc_page_,
miscompare_byteoffset,
page_recs_[crc_page_].src,
page_recs_[crc_page_].dst);
} else {
os_->error_diagnoser_->AddMiscompareError(dimm_string,
reinterpret_cast<uint64>
(error->vaddr), 1);
}
logprintf(priority,
"%s: miscompare on %s at %p(0x%llx:%s): read:0x%016llx, "
"reread:0x%016llx expected:0x%016llx\n",
message,
devicename_.c_str(),
error->vaddr,
error->paddr,
dimm_string,
error->actual,
error->reread,
error->expected);
// Overwrite incorrect data with correct data to prevent
// future miscompares when this data is reused.
*(error->vaddr) = error->expected;
os_->Flush(error->vaddr);
}
// Do a word by word result check of a region.
// Print errors on mismatches.
int WorkerThread::CheckRegion(void *addr,
class Pattern *pattern,
int64 length,
int offset,
int64 pattern_offset) {
uint64 *memblock = static_cast<uint64*>(addr);
const int kErrorLimit = 128;
int errors = 0;
int overflowerrors = 0; // Count of overflowed errors.
bool page_error = false;
string errormessage("Hardware Error");
struct ErrorRecord
recorded[kErrorLimit]; // Queued errors for later printing.
// For each word in the data region.
for (int i = 0; i < length / wordsize_; i++) {
uint64 actual = memblock[i];
uint64 expected;
// Determine the value that should be there.
datacast_t data;
int index = 2 * i + pattern_offset;
data.l32.l = pattern->pattern(index);
data.l32.h = pattern->pattern(index + 1);
expected = data.l64;
// Check tags if necessary.
if (tag_mode_ && ((reinterpret_cast<uint64>(&memblock[i]) & 0x3f) == 0)) {
expected = addr_to_tag(&memblock[i]);
}
// If the value is incorrect, save an error record for later printing.
if (actual != expected) {
if (errors < kErrorLimit) {
recorded[errors].actual = actual;
recorded[errors].expected = expected;
recorded[errors].vaddr = &memblock[i];
errors++;
} else {
page_error = true;
// If we have overflowed the error queue, just print the errors now.
logprintf(10, "Log: Error record overflow, too many miscompares!\n");
errormessage = "Page Error";
break;
}
}
}
// Find if this is a whole block corruption.
if (page_error && !tag_mode_) {
int patsize = patternlist_->Size();
for (int pat = 0; pat < patsize; pat++) {
class Pattern *altpattern = patternlist_->GetPattern(pat);
const int kGood = 0;
const int kBad = 1;
const int kGoodAgain = 2;
const int kNoMatch = 3;
int state = kGood;
unsigned int badstart = 0;
unsigned int badend = 0;
// Don't match against ourself!
if (pattern == altpattern)
continue;
for (int i = 0; i < length / wordsize_; i++) {
uint64 actual = memblock[i];
datacast_t expected;
datacast_t possible;
// Determine the value that should be there.
int index = 2 * i + pattern_offset;
expected.l32.l = pattern->pattern(index);
expected.l32.h = pattern->pattern(index + 1);
possible.l32.l = pattern->pattern(index);
possible.l32.h = pattern->pattern(index + 1);
if (state == kGood) {
if (actual == expected.l64) {
continue;
} else if (actual == possible.l64) {
badstart = i;
badend = i;
state = kBad;
continue;
} else {
state = kNoMatch;
break;
}
} else if (state == kBad) {
if (actual == possible.l64) {
badend = i;
continue;
} else if (actual == expected.l64) {
state = kGoodAgain;
continue;
} else {
state = kNoMatch;
break;
}
} else if (state == kGoodAgain) {
if (actual == expected.l64) {
continue;
} else {
state = kNoMatch;
break;
}
}
}
if ((state == kGoodAgain) || (state == kBad)) {
unsigned int blockerrors = badend - badstart + 1;
errormessage = "Block Error";
ProcessError(&recorded[0], 0, errormessage.c_str());
logprintf(0, "Block Error: (%p) pattern %s instead of %s, "
"%d bytes from offset 0x%x to 0x%x\n",
&memblock[badstart],
altpattern->name(), pattern->name(),
blockerrors * wordsize_,
offset + badstart * wordsize_,
offset + badend * wordsize_);
errorcount_ += blockerrors;
return blockerrors;
}
}
}
// Process error queue after all errors have been recorded.
for (int err = 0; err < errors; err++) {
int priority = 5;
if (errorcount_ + err < 30)
priority = 0; // Bump up the priority for the first few errors.
ProcessError(&recorded[err], priority, errormessage.c_str());
}
if (page_error) {
// For each word in the data region.
int error_recount = 0;
for (int i = 0; i < length / wordsize_; i++) {
uint64 actual = memblock[i];
uint64 expected;
datacast_t data;
// Determine the value that should be there.
int index = 2 * i + pattern_offset;
data.l32.l = pattern->pattern(index);
data.l32.h = pattern->pattern(index + 1);
expected = data.l64;
// Check tags if necessary.
if (tag_mode_ && ((reinterpret_cast<uint64>(&memblock[i]) & 0x3f) == 0)) {
expected = addr_to_tag(&memblock[i]);
}
// If the value is incorrect, save an error record for later printing.
if (actual != expected) {
if (error_recount < kErrorLimit) {
// We already reported these.
error_recount++;
} else {
// If we have overflowed the error queue, print the errors now.
struct ErrorRecord er;
er.actual = actual;
er.expected = expected;
er.vaddr = &memblock[i];
// Do the error printout. This will take a long time and
// likely change the machine state.
ProcessError(&er, 12, errormessage.c_str());
overflowerrors++;
}
}
}
}
// Keep track of observed errors.
errorcount_ += errors + overflowerrors;
return errors + overflowerrors;
}
float WorkerThread::GetCopiedData() {
return pages_copied_ * sat_->page_length() / kMegabyte;
}
// Calculate the CRC of a region.
// Result check if the CRC mismatches.
int WorkerThread::CrcCheckPage(struct page_entry *srcpe) {
const int blocksize = 4096;
const int blockwords = blocksize / wordsize_;
int errors = 0;
const AdlerChecksum *expectedcrc = srcpe->pattern->crc();
uint64 *memblock = static_cast<uint64*>(srcpe->addr);
int blocks = sat_->page_length() / blocksize;
for (int currentblock = 0; currentblock < blocks; currentblock++) {
uint64 *memslice = memblock + currentblock * blockwords;
AdlerChecksum crc;
if (tag_mode_) {
AdlerAddrCrcC(memslice, blocksize, &crc, srcpe);
} else {
CalculateAdlerChecksum(memslice, blocksize, &crc);
}
// If the CRC does not match, we'd better look closer.
if (!crc.Equals(*expectedcrc)) {
logprintf(11, "Log: CrcCheckPage Falling through to slow compare, "
"CRC mismatch %s != %s\n",
crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
int errorcount = CheckRegion(memslice,
srcpe->pattern,
blocksize,
currentblock * blocksize, 0);
if (errorcount == 0) {
logprintf(0, "Log: CrcCheckPage CRC mismatch %s != %s, "
"but no miscompares found.\n",
crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
}
errors += errorcount;
}
}
// For odd length transfers, we should never hit this.
int leftovers = sat_->page_length() % blocksize;
if (leftovers) {
uint64 *memslice = memblock + blocks * blockwords;
errors += CheckRegion(memslice,
srcpe->pattern,
leftovers,
blocks * blocksize, 0);
}
return errors;
}
// Print error information about a data miscompare.
void WorkerThread::ProcessTagError(struct ErrorRecord *error,
int priority,
const char *message) {
char dimm_string[256] = "";
char tag_dimm_string[256] = "";
bool read_error = false;
int apic_id = apicid();
// Determine if this is a write or read error.
os_->Flush(error->vaddr);
error->reread = *(error->vaddr);
// Distinguish read and write errors.
if (error->actual != error->reread) {
read_error = true;
}
sat_assert(error->expected != error->actual);
error->vbyteaddr = reinterpret_cast<char*>(error->vaddr);
// Find physical address if possible.
error->paddr = os_->VirtualToPhysical(error->vbyteaddr);
error->tagpaddr = os_->VirtualToPhysical(error->tagvaddr);
// Pretty print DIMM mapping if available.
os_->FindDimm(error->paddr, dimm_string, sizeof(dimm_string));
// Pretty print DIMM mapping if available.
os_->FindDimm(error->tagpaddr, tag_dimm_string, sizeof(tag_dimm_string));
// Report parseable error.
if (priority < 5) {
logprintf(priority,
"%s: Tag from %p(0x%llx:%s) (%s) "
"miscompare on CPU %d(0x%s) at %p(0x%llx:%s): "
"read:0x%016llx, reread:0x%016llx expected:0x%016llx\n",
message,
error->tagvaddr, error->tagpaddr,
tag_dimm_string,
read_error ? "read error" : "write error",
apic_id,
CurrentCpusFormat().c_str(),
error->vaddr,
error->paddr,
dimm_string,
error->actual,
error->reread,
error->expected);
}
errorcount_ += 1;
// Overwrite incorrect data with correct data to prevent
// future miscompares when this data is reused.
*(error->vaddr) = error->expected;
os_->Flush(error->vaddr);
}
// Print out and log a tag error.
bool WorkerThread::ReportTagError(
uint64 *mem64,
uint64 actual,
uint64 tag) {
struct ErrorRecord er;
er.actual = actual;
er.expected = tag;
er.vaddr = mem64;
// Generate vaddr from tag.
er.tagvaddr = reinterpret_cast<uint64*>(actual);
ProcessTagError(&er, 0, "Hardware Error");
return true;
}
// C implementation of Adler memory copy, with memory tagging.
bool WorkerThread::AdlerAddrMemcpyC(uint64 *dstmem64,
uint64 *srcmem64,
unsigned int size_in_bytes,
AdlerChecksum *checksum,
struct page_entry *pe) {
// Use this data wrapper to access memory with 64bit read/write.
datacast_t data;
datacast_t dstdata;
unsigned int count = size_in_bytes / sizeof(data);
if (count > ((1U) << 19)) {
// Size is too large, must be strictly less than 512 KB.
return false;
}
uint64 a1 = 1;
uint64 a2 = 1;
uint64 b1 = 0;
uint64 b2 = 0;
class Pattern *pattern = pe->pattern;
unsigned int i = 0;
while (i < count) {
// Process 64 bits at a time.
if ((i & 0x7) == 0) {
data.l64 = srcmem64[i];
dstdata.l64 = dstmem64[i];
uint64 src_tag = addr_to_tag(&srcmem64[i]);
uint64 dst_tag = addr_to_tag(&dstmem64[i]);
// Detect if tags have been corrupted.
if (data.l64 != src_tag)
ReportTagError(&srcmem64[i], data.l64, src_tag);
if (dstdata.l64 != dst_tag)
ReportTagError(&dstmem64[i], dstdata.l64, dst_tag);
data.l32.l = pattern->pattern(i << 1);
data.l32.h = pattern->pattern((i << 1) + 1);
a1 = a1 + data.l32.l;
b1 = b1 + a1;
a1 = a1 + data.l32.h;
b1 = b1 + a1;
data.l64 = dst_tag;
dstmem64[i] = data.l64;
} else {
data.l64 = srcmem64[i];
a1 = a1 + data.l32.l;
b1 = b1 + a1;
a1 = a1 + data.l32.h;
b1 = b1 + a1;
dstmem64[i] = data.l64;
}
i++;
data.l64 = srcmem64[i];
a2 = a2 + data.l32.l;
b2 = b2 + a2;
a2 = a2 + data.l32.h;
b2 = b2 + a2;
dstmem64[i] = data.l64;
i++;
}
checksum->Set(a1, a2, b1, b2);
return true;
}
// x86_64 SSE2 assembly implementation of Adler memory copy, with address
// tagging added as a second step. This is useful for debugging failures
// that only occur when SSE / nontemporal writes are used.
bool WorkerThread::AdlerAddrMemcpyWarm(uint64 *dstmem64,
uint64 *srcmem64,
unsigned int size_in_bytes,
AdlerChecksum *checksum,
struct page_entry *pe) {
// Do ASM copy, ignore checksum.
AdlerChecksum ignored_checksum;
os_->AdlerMemcpyWarm(dstmem64, srcmem64, size_in_bytes, &ignored_checksum);
// Force cache flush.
int length = size_in_bytes / sizeof(*dstmem64);
for (int i = 0; i < length; i += sizeof(*dstmem64)) {
os_->FastFlush(dstmem64 + i);
os_->FastFlush(srcmem64 + i);
}
// Check results.
AdlerAddrCrcC(srcmem64, size_in_bytes, checksum, pe);
// Patch up address tags.
TagAddrC(dstmem64, size_in_bytes);
return true;
}
// Retag pages..
bool WorkerThread::TagAddrC(uint64 *memwords,
unsigned int size_in_bytes) {
// Mask is the bitmask of indexes used by the pattern.
// It is the pattern size -1. Size is always a power of 2.
// Select tag or data as appropriate.
int length = size_in_bytes / wordsize_;
for (int i = 0; i < length; i += 8) {
datacast_t data;
data.l64 = addr_to_tag(&memwords[i]);
memwords[i] = data.l64;
}
return true;
}
// C implementation of Adler memory crc.
bool WorkerThread::AdlerAddrCrcC(uint64 *srcmem64,
unsigned int size_in_bytes,
AdlerChecksum *checksum,
struct page_entry *pe) {
// Use this data wrapper to access memory with 64bit read/write.
datacast_t data;
unsigned int count = size_in_bytes / sizeof(data);
if (count > ((1U) << 19)) {
// Size is too large, must be strictly less than 512 KB.
return false;
}
uint64 a1 = 1;
uint64 a2 = 1;
uint64 b1 = 0;
uint64 b2 = 0;
class Pattern *pattern = pe->pattern;
unsigned int i = 0;
while (i < count) {
// Process 64 bits at a time.
if ((i & 0x7) == 0) {
data.l64 = srcmem64[i];
uint64 src_tag = addr_to_tag(&srcmem64[i]);
// Check that tags match expected.
if (data.l64 != src_tag)
ReportTagError(&srcmem64[i], data.l64, src_tag);
data.l32.l = pattern->pattern(i << 1);
data.l32.h = pattern->pattern((i << 1) + 1);
a1 = a1 + data.l32.l;
b1 = b1 + a1;
a1 = a1 + data.l32.h;
b1 = b1 + a1;
} else {
data.l64 = srcmem64[i];
a1 = a1 + data.l32.l;
b1 = b1 + a1;
a1 = a1 + data.l32.h;
b1 = b1 + a1;
}
i++;
data.l64 = srcmem64[i];
a2 = a2 + data.l32.l;
b2 = b2 + a2;
a2 = a2 + data.l32.h;
b2 = b2 + a2;
i++;
}
checksum->Set(a1, a2, b1, b2);
return true;
}
// Copy a block of memory quickly, while keeping a CRC of the data.
// Result check if the CRC mismatches.
int WorkerThread::CrcCopyPage(struct page_entry *dstpe,
struct page_entry *srcpe) {
int errors = 0;
const int blocksize = 4096;
const int blockwords = blocksize / wordsize_;
int blocks = sat_->page_length() / blocksize;
// Base addresses for memory copy
uint64 *targetmembase = static_cast<uint64*>(dstpe->addr);
uint64 *sourcemembase = static_cast<uint64*>(srcpe->addr);
// Remember the expected CRC
const AdlerChecksum *expectedcrc = srcpe->pattern->crc();
for (int currentblock = 0; currentblock < blocks; currentblock++) {
uint64 *targetmem = targetmembase + currentblock * blockwords;
uint64 *sourcemem = sourcemembase + currentblock * blockwords;
AdlerChecksum crc;
if (tag_mode_) {
AdlerAddrMemcpyC(targetmem, sourcemem, blocksize, &crc, srcpe);
} else {
AdlerMemcpyC(targetmem, sourcemem, blocksize, &crc);
}
// Investigate miscompares.
if (!crc.Equals(*expectedcrc)) {
logprintf(11, "Log: CrcCopyPage Falling through to slow compare, "
"CRC mismatch %s != %s\n", crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
int errorcount = CheckRegion(sourcemem,
srcpe->pattern,
blocksize,
currentblock * blocksize, 0);
if (errorcount == 0) {
logprintf(0, "Log: CrcCopyPage CRC mismatch %s != %s, "
"but no miscompares found. Retrying with fresh data.\n",
crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
if (!tag_mode_) {
// Copy the data originally read from this region back again.
// This data should have any corruption read originally while
// calculating the CRC.
memcpy(sourcemem, targetmem, blocksize);
errorcount = CheckRegion(sourcemem,
srcpe->pattern,
blocksize,
currentblock * blocksize, 0);
if (errorcount == 0) {
int apic_id = apicid();
logprintf(0, "Process Error: CPU %d(0x%s) CrcCopyPage "
"CRC mismatch %s != %s, "
"but no miscompares found on second pass.\n",
apic_id, CurrentCpusFormat().c_str(),
crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
struct ErrorRecord er;
er.actual = sourcemem[0];
er.expected = 0x0;
er.vaddr = sourcemem;
ProcessError(&er, 0, "Hardware Error");
}
}
}
errors += errorcount;
}
}
// For odd length transfers, we should never hit this.
int leftovers = sat_->page_length() % blocksize;
if (leftovers) {
uint64 *targetmem = targetmembase + blocks * blockwords;
uint64 *sourcemem = sourcemembase + blocks * blockwords;
errors += CheckRegion(sourcemem,
srcpe->pattern,
leftovers,
blocks * blocksize, 0);
int leftoverwords = leftovers / wordsize_;
for (int i = 0; i < leftoverwords; i++) {
targetmem[i] = sourcemem[i];
}
}
// Update pattern reference to reflect new contents.
dstpe->pattern = srcpe->pattern;
// Clean clean clean the errors away.
if (errors) {
// TODO(nsanders): Maybe we should patch rather than fill? Filling may
// cause bad data to be propogated across the page.
FillPage(dstpe);
}
return errors;
}
// Invert a block of memory quickly, traversing downwards.
int InvertThread::InvertPageDown(struct page_entry *srcpe) {
const int blocksize = 4096;
const int blockwords = blocksize / wordsize_;
int blocks = sat_->page_length() / blocksize;
// Base addresses for memory copy
unsigned int *sourcemembase = static_cast<unsigned int *>(srcpe->addr);
for (int currentblock = blocks-1; currentblock >= 0; currentblock--) {
unsigned int *sourcemem = sourcemembase + currentblock * blockwords;
for (int i = blockwords - 32; i >= 0; i -= 32) {
for (int index = i + 31; index >= i; --index) {
unsigned int actual = sourcemem[index];
sourcemem[index] = ~actual;
}
OsLayer::FastFlush(&sourcemem[i]);
}
}
return 0;
}
// Invert a block of memory, traversing upwards.
int InvertThread::InvertPageUp(struct page_entry *srcpe) {
const int blocksize = 4096;
const int blockwords = blocksize / wordsize_;
int blocks = sat_->page_length() / blocksize;
// Base addresses for memory copy
unsigned int *sourcemembase = static_cast<unsigned int *>(srcpe->addr);
for (int currentblock = 0; currentblock < blocks; currentblock++) {
unsigned int *sourcemem = sourcemembase + currentblock * blockwords;
for (int i = 0; i < blockwords; i += 32) {
for (int index = i; index <= i + 31; ++index) {
unsigned int actual = sourcemem[index];
sourcemem[index] = ~actual;
}
OsLayer::FastFlush(&sourcemem[i]);
}
}
return 0;
}
// Copy a block of memory quickly, while keeping a CRC of the data.
// Result check if the CRC mismatches. Warm the CPU while running
int WorkerThread::CrcWarmCopyPage(struct page_entry *dstpe,
struct page_entry *srcpe) {
int errors = 0;
const int blocksize = 4096;
const int blockwords = blocksize / wordsize_;
int blocks = sat_->page_length() / blocksize;
// Base addresses for memory copy
uint64 *targetmembase = static_cast<uint64*>(dstpe->addr);
uint64 *sourcemembase = static_cast<uint64*>(srcpe->addr);
// Remember the expected CRC
const AdlerChecksum *expectedcrc = srcpe->pattern->crc();
for (int currentblock = 0; currentblock < blocks; currentblock++) {
uint64 *targetmem = targetmembase + currentblock * blockwords;
uint64 *sourcemem = sourcemembase + currentblock * blockwords;
AdlerChecksum crc;
if (tag_mode_) {
AdlerAddrMemcpyWarm(targetmem, sourcemem, blocksize, &crc, srcpe);
} else {
os_->AdlerMemcpyWarm(targetmem, sourcemem, blocksize, &crc);
}
// Investigate miscompares.
if (!crc.Equals(*expectedcrc)) {
logprintf(11, "Log: CrcWarmCopyPage Falling through to slow compare, "
"CRC mismatch %s != %s\n", crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
int errorcount = CheckRegion(sourcemem,
srcpe->pattern,
blocksize,
currentblock * blocksize, 0);
if (errorcount == 0) {
logprintf(0, "Log: CrcWarmCopyPage CRC mismatch %s != %s, "
"but no miscompares found. Retrying with fresh data.\n",
crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
if (!tag_mode_) {
// Copy the data originally read from this region back again.
// This data should have any corruption read originally while
// calculating the CRC.
memcpy(sourcemem, targetmem, blocksize);
errorcount = CheckRegion(sourcemem,
srcpe->pattern,
blocksize,
currentblock * blocksize, 0);
if (errorcount == 0) {
int apic_id = apicid();
logprintf(0, "Process Error: CPU %d(0x%s) CrciWarmCopyPage "
"CRC mismatch %s != %s, "
"but no miscompares found on second pass.\n",
apic_id, CurrentCpusFormat().c_str(),
crc.ToHexString().c_str(),
expectedcrc->ToHexString().c_str());
struct ErrorRecord er;
er.actual = sourcemem[0];
er.expected = 0x0;
er.vaddr = sourcemem;
ProcessError(&er, 0, "Hardware Error");
}
}
}
errors += errorcount;
}
}
// For odd length transfers, we should never hit this.
int leftovers = sat_->page_length() % blocksize;
if (leftovers) {
uint64 *targetmem = targetmembase + blocks * blockwords;
uint64 *sourcemem = sourcemembase + blocks * blockwords;
errors += CheckRegion(sourcemem,
srcpe->pattern,
leftovers,
blocks * blocksize, 0);
int leftoverwords = leftovers / wordsize_;
for (int i = 0; i < leftoverwords; i++) {
targetmem[i] = sourcemem[i];
}
}
// Update pattern reference to reflect new contents.
dstpe->pattern = srcpe->pattern;
// Clean clean clean the errors away.
if (errors) {
// TODO(nsanders): Maybe we should patch rather than fill? Filling may
// cause bad data to be propogated across the page.
FillPage(dstpe);
}
return errors;
}
// Memory check work loop. Execute until done, then exhaust pages.
bool CheckThread::Work() {
struct page_entry pe;
bool result = true;
int64 loops = 0;
logprintf(9, "Log: Starting Check thread %d\n", thread_num_);
// We want to check all the pages, and
// stop when there aren't any left.
while (true) {
result = result && sat_->GetValid(&pe);
if (!result) {
if (IsReadyToRunNoPause())
logprintf(0, "Process Error: check_thread failed to pop pages, "
"bailing\n");
else
result = true;
break;
}
// Do the result check.
CrcCheckPage(&pe);
// Push pages back on the valid queue if we are still going,
// throw them out otherwise.
if (IsReadyToRunNoPause())
result = result && sat_->PutValid(&pe);
else
result = result && sat_->PutEmpty(&pe);
if (!result) {
logprintf(0, "Process Error: check_thread failed to push pages, "
"bailing\n");
break;
}
loops++;
}
pages_copied_ = loops;
status_ = result;
logprintf(9, "Log: Completed %d: Check thread. Status %d, %d pages checked\n",
thread_num_, status_, pages_copied_);
return result;
}
// Memory copy work loop. Execute until marked done.
bool CopyThread::Work() {
struct page_entry src;
struct page_entry dst;
bool result = true;
int64 loops = 0;
logprintf(9, "Log: Starting copy thread %d: cpu %s, mem %x\n",
thread_num_, cpuset_format(&cpu_mask_).c_str(), tag_);
while (IsReadyToRun()) {
// Pop the needed pages.
result = result && sat_->GetValid(&src, tag_);
result = result && sat_->GetEmpty(&dst, tag_);
if (!result) {
logprintf(0, "Process Error: copy_thread failed to pop pages, "
"bailing\n");
break;
}
// Force errors for unittests.
if (sat_->error_injection()) {
if (loops == 8) {
char *addr = reinterpret_cast<char*>(src.addr);
int offset = random() % sat_->page_length();
addr[offset] = 0xba;
}
}
// We can use memcpy, or CRC check while we copy.
if (sat_->warm()) {
CrcWarmCopyPage(&dst, &src);
} else if (sat_->strict()) {
CrcCopyPage(&dst, &src);
} else {
memcpy(dst.addr, src.addr, sat_->page_length());
dst.pattern = src.pattern;
}
result = result && sat_->PutValid(&dst);
result = result && sat_->PutEmpty(&src);
// Copy worker-threads yield themselves at the end of each copy loop,
// to avoid threads from preempting each other in the middle of the inner
// copy-loop. Cooperations between Copy worker-threads results in less
// unnecessary cache thrashing (which happens when context-switching in the
// middle of the inner copy-loop).
YieldSelf();
if (!result) {
logprintf(0, "Process Error: copy_thread failed to push pages, "
"bailing\n");
break;
}
loops++;
}
pages_copied_ = loops;
status_ = result;
logprintf(9, "Log: Completed %d: Copy thread. Status %d, %d pages copied\n",
thread_num_, status_, pages_copied_);
return result;
}
// Memory invert work loop. Execute until marked done.
bool InvertThread::Work() {
struct page_entry src;
bool result = true;
int64 loops = 0;
logprintf(9, "Log: Starting invert thread %d\n", thread_num_);
while (IsReadyToRun()) {
// Pop the needed pages.
result = result && sat_->GetValid(&src);
if (!result) {
logprintf(0, "Process Error: invert_thread failed to pop pages, "
"bailing\n");
break;
}
if (sat_->strict())
CrcCheckPage(&src);
// For the same reason CopyThread yields itself (see YieldSelf comment
// in CopyThread::Work(), InvertThread yields itself after each invert
// operation to improve cooperation between different worker threads
// stressing the memory/cache.
InvertPageUp(&src);
YieldSelf();
InvertPageDown(&src);
YieldSelf();
InvertPageDown(&src);
YieldSelf();
InvertPageUp(&src);
YieldSelf();
if (sat_->strict())
CrcCheckPage(&src);
result = result && sat_->PutValid(&src);
if (!result) {
logprintf(0, "Process Error: invert_thread failed to push pages, "
"bailing\n");
break;
}
loops++;
}
pages_copied_ = loops * 2;
status_ = result;
logprintf(9, "Log: Completed %d: Copy thread. Status %d, %d pages copied\n",
thread_num_, status_, pages_copied_);
return result;
}
// Set file name to use for File IO.
void FileThread::SetFile(const char *filename_init) {
filename_ = filename_init;
devicename_ = os_->FindFileDevice(filename_);
}
// Open the file for access.
bool FileThread::OpenFile(int *pfile) {
int fd = open(filename_.c_str(),
O_RDWR | O_CREAT | O_SYNC | O_DIRECT,
0644);
if (fd < 0) {
logprintf(0, "Process Error: Failed to create file %s!!\n",
filename_.c_str());
pages_copied_ = 0;
return false;
}
*pfile = fd;
return true;
}
// Close the file.
bool FileThread::CloseFile(int fd) {
close(fd);
return true;
}
// Check sector tagging.
bool FileThread::SectorTagPage(struct page_entry *src, int block) {
int page_length = sat_->page_length();
struct FileThread::SectorTag *tag =
(struct FileThread::SectorTag *)(src->addr);
// Tag each sector.
unsigned char magic = ((0xba + thread_num_) & 0xff);
for (int sec = 0; sec < page_length / 512; sec++) {
tag[sec].magic = magic;
tag[sec].block = block & 0xff;
tag[sec].sector = sec & 0xff;
tag[sec].pass = pass_ & 0xff;
}
return true;
}
bool FileThread::WritePageToFile(int fd, struct page_entry *src) {
int page_length = sat_->page_length();
// Fill the file with our data.
int64 size = write(fd, src->addr, page_length);
if (size != page_length) {
os_->ErrorReport(devicename_.c_str(), "write-error", 1);
errorcount_++;
logprintf(0, "Block Error: file_thread failed to write, "
"bailing\n");
return false;
}
return true;
}
// Write the data to the file.
bool FileThread::WritePages(int fd) {
int strict = sat_->strict();
// Start fresh at beginning of file for each batch of pages.
lseek64(fd, 0, SEEK_SET);
for (int i = 0; i < sat_->disk_pages(); i++) {
struct page_entry src;
if (!GetValidPage(&src))
return false;
// Save expected pattern.
page_recs_[i].pattern = src.pattern;
page_recs_[i].src = src.addr;
// Check data correctness.
if (strict)
CrcCheckPage(&src);
SectorTagPage(&src, i);
bool result = WritePageToFile(fd, &src);
if (!PutEmptyPage(&src))
return false;
if (!result)
return false;
}
return true;
}
// Copy data from file into memory block.
bool FileThread::ReadPageFromFile(int fd, struct page_entry *dst) {
int page_length = sat_->page_length();
// Do the actual read.
int64 size = read(fd, dst->addr, page_length);
if (size != page_length) {
os_->ErrorReport(devicename_.c_str(), "read-error", 1);
logprintf(0, "Block Error: file_thread failed to read, "
"bailing\n");
errorcount_++;
return false;
}
return true;
}
// Check sector tagging.
bool FileThread::SectorValidatePage(const struct PageRec &page,
struct page_entry *dst, int block) {
// Error injection.
static int calls = 0;
calls++;
// Do sector tag compare.
int firstsector = -1;
int lastsector = -1;
bool badsector = false;
int page_length = sat_->page_length();
// Cast data block into an array of tagged sectors.
struct FileThread::SectorTag *tag =
(struct FileThread::SectorTag *)(dst->addr);
sat_assert(sizeof(*tag) == 512);
// Error injection.
if (sat_->error_injection()) {
if (calls == 2) {
for (int badsec = 8; badsec < 17; badsec++)
tag[badsec].pass = 27;
}
if (calls == 18) {
(static_cast<int32*>(dst->addr))[27] = 0xbadda7a;
}
}
// Check each sector for the correct tag we added earlier,
// then revert the tag to the to normal data pattern.
unsigned char magic = ((0xba + thread_num_) & 0xff);
for (int sec = 0; sec < page_length / 512; sec++) {
// Check magic tag.
if ((tag[sec].magic != magic) ||
(tag[sec].block != (block & 0xff)) ||
(tag[sec].sector != (sec & 0xff)) ||
(tag[sec].pass != (pass_ & 0xff))) {
// Offset calculation for tag location.
int offset = sec * sizeof(SectorTag);
if (tag[sec].block != (block & 0xff))
offset += 1 * sizeof(uint8);
else if (tag[sec].sector != (sec & 0xff))
offset += 2 * sizeof(uint8);
else if (tag[sec].pass != (pass_ & 0xff))
offset += 3 * sizeof(uint8);
// Run sector tag error through diagnoser for logging and reporting.
errorcount_ += 1;
os_->error_diagnoser_->AddHDDSectorTagError(devicename_, tag[sec].block,
offset,
tag[sec].sector,
page.src, page.dst);
logprintf(5, "Sector Error: Sector tag @ 0x%x, pass %d/%d. "
"sec %x/%x, block %d/%d, magic %x/%x, File: %s \n",
block * page_length + 512 * sec,
(pass_ & 0xff), (unsigned int)tag[sec].pass,
sec, (unsigned int)tag[sec].sector,
block, (unsigned int)tag[sec].block,
magic, (unsigned int)tag[sec].magic,
filename_.c_str());
// Keep track of first and last bad sector.
if (firstsector == -1)
firstsector = (block * page_length / 512) + sec;
lastsector = (block * page_length / 512) + sec;
badsector = true;
}
// Patch tag back to proper pattern.
unsigned int *addr = (unsigned int *)(&tag[sec]);
*addr = dst->pattern->pattern(512 * sec / sizeof(*addr));
}
// If we found sector errors:
if (badsector == true) {
logprintf(5, "Log: file sector miscompare at offset %x-%x. File: %s\n",
firstsector * 512,
((lastsector + 1) * 512) - 1,
filename_.c_str());
// Either exit immediately, or patch the data up and continue.
if (sat_->stop_on_error()) {
exit(1);
} else {
// Patch up bad pages.
for (int block = (firstsector * 512) / page_length;
block <= (lastsector * 512) / page_length;
block++) {
unsigned int *memblock = static_cast<unsigned int *>(dst->addr);
int length = page_length / wordsize_;
for (int i = 0; i < length; i++) {
memblock[i] = dst->pattern->pattern(i);
}
}
}
}
return true;
}
// Get memory for an incoming data transfer..
bool FileThread::PagePrepare() {
// We can only do direct IO to SAT pages if it is normal mem.
page_io_ = os_->normal_mem();
// Init a local buffer if we need it.
if (!page_io_) {
#ifdef HAVE_POSIX_MEMALIGN
int result = posix_memalign(&local_page_, 512, sat_->page_length());
if (result) {
logprintf(0, "Process Error: disk thread posix_memalign "
"returned %d (fail)\n",
result);
status_ = false;
return false;
}
#else
local_page_ = memalign(512, sat_->page_length());
if (!local_page_) {
logprintf(0, "Process Error: disk thread memalign failed.\n");
status_ = false;
return false;
}
#endif
}
return true;
}
// Remove memory allocated for data transfer.
bool FileThread::PageTeardown() {
// Free a local buffer if we need to.
if (!page_io_) {
free(local_page_);
}
return true;
}
// Get memory for an incoming data transfer..
bool FileThread::GetEmptyPage(struct page_entry *dst) {
if (page_io_) {
if (!sat_->GetEmpty(dst))
return false;
} else {
dst->addr = local_page_;
dst->offset = 0;
dst->pattern = 0;
}
return true;
}
// Get memory for an outgoing data transfer..
bool FileThread::GetValidPage(struct page_entry *src) {
struct page_entry tmp;
if (!sat_->GetValid(&tmp))
return false;
if (page_io_) {
*src = tmp;
return true;
} else {
src->addr = local_page_;
src->offset = 0;
CrcCopyPage(src, &tmp);
if (!sat_->PutValid(&tmp))
return false;
}
return true;
}
// Throw out a used empty page.
bool FileThread::PutEmptyPage(struct page_entry *src) {
if (page_io_) {
if (!sat_->PutEmpty(src))
return false;
}
return true;
}
// Throw out a used, filled page.
bool FileThread::PutValidPage(struct page_entry *src) {
if (page_io_) {
if (!sat_->PutValid(src))
return false;
}
return true;
}
// Copy data from file into memory blocks.
bool FileThread::ReadPages(int fd) {
int page_length = sat_->page_length();
int strict = sat_->strict();
bool result = true;
// Read our data back out of the file, into it's new location.
lseek64(fd, 0, SEEK_SET);
for (int i = 0; i < sat_->disk_pages(); i++) {
struct page_entry dst;
if (!GetEmptyPage(&dst))
return false;
// Retrieve expected pattern.
dst.pattern = page_recs_[i].pattern;
// Update page recordpage record.
page_recs_[i].dst = dst.addr;
// Read from the file into destination page.
if (!ReadPageFromFile(fd, &dst)) {
PutEmptyPage(&dst);
return false;
}
SectorValidatePage(page_recs_[i], &dst, i);
// Ensure that the transfer ended up with correct data.
if (strict) {
// Record page index currently CRC checked.
crc_page_ = i;
int errors = CrcCheckPage(&dst);
if (errors) {
logprintf(5, "Log: file miscompare at block %d, "
"offset %x-%x. File: %s\n",
i, i * page_length, ((i + 1) * page_length) - 1,
filename_.c_str());
result = false;
}
crc_page_ = -1;
errorcount_ += errors;
}
if (!PutValidPage(&dst))
return false;
}
return result;
}
// File IO work loop. Execute until marked done.
bool FileThread::Work() {
bool result = true;
int64 loops = 0;
logprintf(9, "Log: Starting file thread %d, file %s, device %s\n",
thread_num_,
filename_.c_str(),
devicename_.c_str());
if (!PagePrepare()) {
status_ = false;
return false;
}
// Open the data IO file.
int fd = 0;
if (!OpenFile(&fd)) {
status_ = false;
return false;
}
pass_ = 0;
// Load patterns into page records.
page_recs_ = new struct PageRec[sat_->disk_pages()];
for (int i = 0; i < sat_->disk_pages(); i++) {
page_recs_[i].pattern = new struct Pattern();
}
// Loop until done.
while (IsReadyToRun()) {
// Do the file write.
if (!(result = result && WritePages(fd)))
break;
// Do the file read.
if (!(result = result && ReadPages(fd)))
break;
loops++;
pass_ = loops;
}
pages_copied_ = loops * sat_->disk_pages();
// Clean up.
CloseFile(fd);
PageTeardown();
logprintf(9, "Log: Completed %d: file thread status %d, %d pages copied\n",
thread_num_, status_, pages_copied_);
// Failure to read from device indicates hardware,
// rather than procedural SW error.
status_ = true;
return true;
}
bool NetworkThread::IsNetworkStopSet() {
return !IsReadyToRunNoPause();
}
bool NetworkSlaveThread::IsNetworkStopSet() {
// This thread has no completion status.
// It finishes whever there is no more data to be
// passed back.
return true;
}
// Set ip name to use for Network IO.
void NetworkThread::SetIP(const char *ipaddr_init) {
strncpy(ipaddr_, ipaddr_init, 256);
}
// Create a socket.
// Return 0 on error.
bool NetworkThread::CreateSocket(int *psocket) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
logprintf(0, "Process Error: Cannot open socket\n");
pages_copied_ = 0;
status_ = false;
return false;
}
*psocket = sock;
return true;
}
// Close the socket.
bool NetworkThread::CloseSocket(int sock) {
close(sock);
return true;
}
// Initiate the tcp connection.
bool NetworkThread::Connect(int sock) {
struct sockaddr_in dest_addr;
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(kNetworkPort);
memset(&(dest_addr.sin_zero), '\0', sizeof(dest_addr.sin_zero));
// Translate dot notation to u32.
if (inet_aton(ipaddr_, &dest_addr.sin_addr) == 0) {
logprintf(0, "Process Error: Cannot resolve %s\n", ipaddr_);
pages_copied_ = 0;
status_ = false;
return false;
}
if (-1 == connect(sock, reinterpret_cast<struct sockaddr *>(&dest_addr),
sizeof(struct sockaddr))) {
logprintf(0, "Process Error: Cannot connect %s\n", ipaddr_);
pages_copied_ = 0;
status_ = false;
return false;
}
return true;
}
// Initiate the tcp connection.
bool NetworkListenThread::Listen() {
struct sockaddr_in sa;
memset(&(sa.sin_zero), '\0', sizeof(sa.sin_zero));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
sa.sin_port = htons(kNetworkPort);
if (-1 == bind(sock_, (struct sockaddr*)&sa, sizeof(struct sockaddr))) {
char buf[256];
sat_strerror(errno, buf, sizeof(buf));
logprintf(0, "Process Error: Cannot bind socket: %s\n", buf);
pages_copied_ = 0;
status_ = false;
return false;
}
listen(sock_, 3);
return true;
}
// Wait for a connection from a network traffic generation thread.
bool NetworkListenThread::Wait() {
fd_set rfds;
struct timeval tv;
int retval;
// Watch sock_ to see when it has input.
FD_ZERO(&rfds);
FD_SET(sock_, &rfds);
// Wait up to five seconds.
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(sock_ + 1, &rfds, NULL, NULL, &tv);
return (retval > 0);
}
// Wait for a connection from a network traffic generation thread.
bool NetworkListenThread::GetConnection(int *pnewsock) {
struct sockaddr_in sa;
socklen_t size = sizeof(struct sockaddr_in);
int newsock = accept(sock_, reinterpret_cast<struct sockaddr *>(&sa), &size);
if (newsock < 0) {
logprintf(0, "Process Error: Did not receive connection\n");
pages_copied_ = 0;
status_ = false;
return false;
}
*pnewsock = newsock;
return true;
}
// Send a page, return false if a page was not sent.
bool NetworkThread::SendPage(int sock, struct page_entry *src) {
int page_length = sat_->page_length();
char *address = static_cast<char*>(src->addr);
// Send our data over the network.
int size = page_length;
while (size) {
int transferred = send(sock, address + (page_length - size), size, 0);
if ((transferred == 0) || (transferred == -1)) {
if (!IsNetworkStopSet()) {
char buf[256] = "";
sat_strerror(errno, buf, sizeof(buf));
logprintf(0, "Process Error: Thread %d, "
"Network write failed, bailing. (%s)\n",
thread_num_, buf);
status_ = false;
}
return false;
}
size = size - transferred;
}
return true;
}
// Receive a page. Return false if a page was not received.
bool NetworkThread::ReceivePage(int sock, struct page_entry *dst) {
int page_length = sat_->page_length();
char *address = static_cast<char*>(dst->addr);
// Maybe we will get our data back again, maybe not.
int size = page_length;
while (size) {
int transferred = recv(sock, address + (page_length - size), size, 0);
if ((transferred == 0) || (transferred == -1)) {
// Typically network slave thread should exit as network master
// thread stops sending data.
if (IsNetworkStopSet()) {
int err = errno;
if (transferred == 0 && err == 0) {
// Two system setups will not sync exactly,
// allow early exit, but log it.
logprintf(0, "Log: Net thread did not receive any data, exiting.\n");
} else {
char buf[256] = "";
sat_strerror(err, buf, sizeof(buf));
// Print why we failed.
logprintf(0, "Process Error: Thread %d, "
"Network read failed, bailing (%s).\n",
thread_num_, buf);
status_ = false;
// Print arguments and results.
logprintf(0, "Log: recv(%d, address %x, size %x, 0) == %x, err %d\n",
sock, address + (page_length - size),
size, transferred, err);
if ((transferred == 0) &&
(page_length - size < 512) &&
(page_length - size > 0)) {
// Print null terminated data received, to see who's been
// sending us supicious unwanted data.
address[page_length - size] = 0;
logprintf(0, "Log: received %d bytes: '%s'\n",
page_length - size, address);
}
}
}
return false;
}
size = size - transferred;
}
return true;
}
// Network IO work loop. Execute until marked done.
// Return true if the thread ran as expected.
bool NetworkThread::Work() {
logprintf(9, "Log: Starting network thread %d, ip %s\n",
thread_num_,
ipaddr_);
// Make a socket.
int sock = 0;
if (!CreateSocket(&sock))
return false;
// Network IO loop requires network slave thread to have already initialized.
// We will sleep here for awhile to ensure that the slave thread will be
// listening by the time we connect.
// Sleep for 15 seconds.
sat_sleep(15);
logprintf(9, "Log: Starting execution of network thread %d, ip %s\n",
thread_num_,
ipaddr_);
// Connect to a slave thread.
if (!Connect(sock))
return false;
// Loop until done.
bool result = true;
int strict = sat_->strict();
int64 loops = 0;
while (IsReadyToRun()) {
struct page_entry src;
struct page_entry dst;
result = result && sat_->GetValid(&src);
result = result && sat_->GetEmpty(&dst);
if (!result) {
logprintf(0, "Process Error: net_thread failed to pop pages, "
"bailing\n");
break;
}
// Check data correctness.
if (strict)
CrcCheckPage(&src);
// Do the network write.
if (!(result = result && SendPage(sock, &src)))
break;
// Update pattern reference to reflect new contents.
dst.pattern = src.pattern;
// Do the network read.
if (!(result = result && ReceivePage(sock, &dst)))
break;
// Ensure that the transfer ended up with correct data.
if (strict)
CrcCheckPage(&dst);
// Return all of our pages to the queue.
result = result && sat_->PutValid(&dst);
result = result && sat_->PutEmpty(&src);
if (!result) {
logprintf(0, "Process Error: net_thread failed to push pages, "
"bailing\n");
break;
}
loops++;
}
pages_copied_ = loops;
status_ = result;
// Clean up.
CloseSocket(sock);
logprintf(9, "Log: Completed %d: network thread status %d, "
"%d pages copied\n",
thread_num_, status_, pages_copied_);
return result;
}
// Spawn slave threads for incoming connections.
bool NetworkListenThread::SpawnSlave(int newsock, int threadid) {
logprintf(12, "Log: Listen thread spawning slave\n");
// Spawn slave thread, to reflect network traffic back to sender.
ChildWorker *child_worker = new ChildWorker;
child_worker->thread.SetSock(newsock);
child_worker->thread.InitThread(threadid, sat_, os_, patternlist_,
&child_worker->status);
child_worker->status.Initialize();
child_worker->thread.SpawnThread();
child_workers_.push_back(child_worker);
return true;
}
// Reap slave threads.
bool NetworkListenThread::ReapSlaves() {
bool result = true;
// Gather status and reap threads.
logprintf(12, "Log: Joining all outstanding threads\n");
for (size_t i = 0; i < child_workers_.size(); i++) {
NetworkSlaveThread& child_thread = child_workers_[i]->thread;
logprintf(12, "Log: Joining slave thread %d\n", i);
child_thread.JoinThread();
if (child_thread.GetStatus() != 1) {
logprintf(0, "Process Error: Slave Thread %d failed with status %d\n", i,
child_thread.GetStatus());
result = false;
}
errorcount_ += child_thread.GetErrorCount();
logprintf(9, "Log: Slave Thread %d found %lld miscompares\n", i,
child_thread.GetErrorCount());
pages_copied_ += child_thread.GetPageCount();
}
return result;
}
// Network listener IO work loop. Execute until marked done.
// Return false on fatal software error.
bool NetworkListenThread::Work() {
logprintf(9, "Log: Starting network listen thread %d\n",
thread_num_);
// Make a socket.
sock_ = 0;
if (!CreateSocket(&sock_)) {
status_ = false;
return false;
}
logprintf(9, "Log: Listen thread created sock\n");
// Allows incoming connections to be queued up by socket library.
int newsock = 0;
Listen();
logprintf(12, "Log: Listen thread waiting for incoming connections\n");
// Wait on incoming connections, and spawn worker threads for them.
int threadcount = 0;
while (IsReadyToRun()) {
// Poll for connections that we can accept().
if (Wait()) {
// Accept those connections.
logprintf(12, "Log: Listen thread found incoming connection\n");
if (GetConnection(&newsock)) {
SpawnSlave(newsock, threadcount);
threadcount++;
}
}
}
// Gather status and join spawned threads.
ReapSlaves();
// Delete the child workers.
for (ChildVector::iterator it = child_workers_.begin();
it != child_workers_.end(); ++it) {
(*it)->status.Destroy();
delete *it;
}
child_workers_.clear();
CloseSocket(sock_);
status_ = true;
logprintf(9,
"Log: Completed %d: network listen thread status %d, "
"%d pages copied\n",
thread_num_, status_, pages_copied_);
return true;
}
// Set network reflector socket struct.
void NetworkSlaveThread::SetSock(int sock) {
sock_ = sock;
}
// Network reflector IO work loop. Execute until marked done.
// Return false on fatal software error.
bool NetworkSlaveThread::Work() {
logprintf(9, "Log: Starting network slave thread %d\n",
thread_num_);
// Verify that we have a socket.
int sock = sock_;
if (!sock) {
status_ = false;
return false;
}
// Loop until done.
int64 loops = 0;
// Init a local buffer for storing data.
void *local_page = NULL;
#ifdef HAVE_POSIX_MEMALIGN
int result = posix_memalign(&local_page, 512, sat_->page_length());
if (result) {
logprintf(0, "Process Error: net slave posix_memalign "
"returned %d (fail)\n",
result);
status_ = false;
return false;
}
#else
local_page = memalign(512, sat_->page_length());
if (!local_page) {
logprintf(0, "Process Error: net slave memalign failed.\n");
status_ = false;
return false;
}
#endif
struct page_entry page;
page.addr = local_page;
// This thread will continue to run as long as the thread on the other end of
// the socket is still sending and receiving data.
while (1) {
// Do the network read.
if (!ReceivePage(sock, &page))
break;
// Do the network write.
if (!SendPage(sock, &page))
break;
loops++;
}
pages_copied_ = loops;
// No results provided from this type of thread.
status_ = true;
// Clean up.
CloseSocket(sock);
logprintf(9,
"Log: Completed %d: network slave thread status %d, "
"%d pages copied\n",
thread_num_, status_, pages_copied_);
return true;
}
// Thread work loop. Execute until marked finished.
bool ErrorPollThread::Work() {
logprintf(9, "Log: Starting system error poll thread %d\n", thread_num_);
// This calls a generic error polling function in the Os abstraction layer.
do {
errorcount_ += os_->ErrorPoll();
os_->ErrorWait();
} while (IsReadyToRun());
logprintf(9, "Log: Finished system error poll thread %d: %d errors\n",
thread_num_, errorcount_);
status_ = true;
return true;
}
// Worker thread to heat up CPU.
// This thread does not evaluate pass/fail or software error.
bool CpuStressThread::Work() {
logprintf(9, "Log: Starting CPU stress thread %d\n", thread_num_);
do {
// Run ludloff's platform/CPU-specific assembly workload.
os_->CpuStressWorkload();
YieldSelf();
} while (IsReadyToRun());
logprintf(9, "Log: Finished CPU stress thread %d:\n",
thread_num_);
status_ = true;
return true;
}
CpuCacheCoherencyThread::CpuCacheCoherencyThread(cc_cacheline_data *data,
int cacheline_count,
int thread_num,
int inc_count) {
cc_cacheline_data_ = data;
cc_cacheline_count_ = cacheline_count;
cc_thread_num_ = thread_num;
cc_inc_count_ = inc_count;
}
// Worked thread to test the cache coherency of the CPUs
// Return false on fatal sw error.
bool CpuCacheCoherencyThread::Work() {
logprintf(9, "Log: Starting the Cache Coherency thread %d\n",
cc_thread_num_);
uint64 time_start, time_end;
struct timeval tv;
unsigned short seed = static_cast<unsigned int>(gettid());
gettimeofday(&tv, NULL); // Get the timestamp before increments.
time_start = tv.tv_sec * 1000000ULL + tv.tv_usec;
uint64 total_inc = 0; // Total increments done by the thread.
while (IsReadyToRun()) {
for (int i = 0; i < cc_inc_count_; i++) {
// Choose a datastructure in random and increment the appropriate
// member in that according to the offset (which is the same as the
// thread number.
int r = nrand48(&seed);
r = cc_cacheline_count_ * (r / (RAND_MAX + 1.0));
// Increment the member of the randomely selected structure.
(cc_cacheline_data_[r].num[cc_thread_num_])++;
}
total_inc += cc_inc_count_;
// Calculate if the local counter matches with the global value
// in all the cache line structures for this particular thread.
int cc_global_num = 0;
for (int cline_num = 0; cline_num < cc_cacheline_count_; cline_num++) {
cc_global_num += cc_cacheline_data_[cline_num].num[cc_thread_num_];
// Reset the cachline member's value for the next run.
cc_cacheline_data_[cline_num].num[cc_thread_num_] = 0;
}
if (sat_->error_injection())
cc_global_num = -1;
if (cc_global_num != cc_inc_count_) {
errorcount_++;
logprintf(0, "Hardware Error: global(%d) and local(%d) do not match\n",
cc_global_num, cc_inc_count_);
}
}
gettimeofday(&tv, NULL); // Get the timestamp at the end.
time_end = tv.tv_sec * 1000000ULL + tv.tv_usec;
uint64 us_elapsed = time_end - time_start;
// inc_rate is the no. of increments per second.
double inc_rate = total_inc * 1e6 / us_elapsed;
logprintf(4, "Stats: CC Thread(%d): Time=%llu us,"
" Increments=%llu, Increments/sec = %.6lf\n",
cc_thread_num_, us_elapsed, total_inc, inc_rate);
logprintf(9, "Log: Finished CPU Cache Coherency thread %d:\n",
cc_thread_num_);
status_ = true;
return true;
}
#ifdef HAVE_LIBAIO_H
DiskThread::DiskThread(DiskBlockTable *block_table) {
read_block_size_ = kSectorSize; // default 1 sector (512 bytes)
write_block_size_ = kSectorSize; // this assumes read and write block size
// are the same
segment_size_ = -1; // use the entire disk as one segment
cache_size_ = 16 * 1024 * 1024; // assume 16MiB cache by default
// Use a queue such that 3/2 times as much data as the cache can hold
// is written before it is read so that there is little chance the read
// data is in the cache.
queue_size_ = ((cache_size_ / write_block_size_) * 3) / 2;
blocks_per_segment_ = 32;
read_threshold_ = 100000; // 100ms is a reasonable limit for
write_threshold_ = 100000; // reading/writing a sector
read_timeout_ = 5000000; // 5 seconds should be long enough for a
write_timeout_ = 5000000; // timout for reading/writing
device_sectors_ = 0;
non_destructive_ = 0;
aio_ctx_ = 0;
block_table_ = block_table;
update_block_table_ = 1;
block_buffer_ = NULL;
blocks_written_ = 0;
blocks_read_ = 0;
}
DiskThread::~DiskThread() {
if (block_buffer_)
free(block_buffer_);
}
// Set filename for device file (in /dev).
void DiskThread::SetDevice(const char *device_name) {
device_name_ = device_name;
}
// Set various parameters that control the behaviour of the test.
// -1 is used as a sentinel value on each parameter (except non_destructive)
// to indicate that the parameter not be set.
bool DiskThread::SetParameters(int read_block_size,
int write_block_size,
int64 segment_size,
int64 cache_size,
int blocks_per_segment,
int64 read_threshold,
int64 write_threshold,
int non_destructive) {
if (read_block_size != -1) {
// Blocks must be aligned to the disk's sector size.
if (read_block_size % kSectorSize != 0) {
logprintf(0, "Process Error: Block size must be a multiple of %d "
"(thread %d).\n", kSectorSize, thread_num_);
return false;
}
read_block_size_ = read_block_size;
}
if (write_block_size != -1) {
// Write blocks must be aligned to the disk's sector size and to the
// block size.
if (write_block_size % kSectorSize != 0) {
logprintf(0, "Process Error: Write block size must be a multiple "
"of %d (thread %d).\n", kSectorSize, thread_num_);
return false;
}
if (write_block_size % read_block_size_ != 0) {
logprintf(0, "Process Error: Write block size must be a multiple "
"of the read block size, which is %d (thread %d).\n",
read_block_size_, thread_num_);
return false;
}
write_block_size_ = write_block_size;
} else {
// Make sure write_block_size_ is still valid.
if (read_block_size_ > write_block_size_) {
logprintf(5, "Log: Assuming write block size equal to read block size, "
"which is %d (thread %d).\n", read_block_size_,
thread_num_);
write_block_size_ = read_block_size_;
} else {
if (write_block_size_ % read_block_size_ != 0) {
logprintf(0, "Process Error: Write block size (defined as %d) must "
"be a multiple of the read block size, which is %d "
"(thread %d).\n", write_block_size_, read_block_size_,
thread_num_);
return false;
}
}
}
if (cache_size != -1) {
cache_size_ = cache_size;
}
if (blocks_per_segment != -1) {
if (blocks_per_segment <= 0) {
logprintf(0, "Process Error: Blocks per segment must be greater than "
"zero.\n (thread %d)", thread_num_);
return false;
}
blocks_per_segment_ = blocks_per_segment;
}
if (read_threshold != -1) {
if (read_threshold <= 0) {
logprintf(0, "Process Error: Read threshold must be greater than "
"zero (thread %d).\n", thread_num_);
return false;
}
read_threshold_ = read_threshold;
}
if (write_threshold != -1) {
if (write_threshold <= 0) {
logprintf(0, "Process Error: Write threshold must be greater than "
"zero (thread %d).\n", thread_num_);
return false;
}
write_threshold_ = write_threshold;
}
if (segment_size != -1) {
// Segments must be aligned to the disk's sector size.
if (segment_size % kSectorSize != 0) {
logprintf(0, "Process Error: Segment size must be a multiple of %d"
" (thread %d).\n", kSectorSize, thread_num_);
return false;
}
segment_size_ = segment_size / kSectorSize;
}
non_destructive_ = non_destructive;
// Having a queue of 150% of blocks that will fit in the disk's cache
// should be enough to force out the oldest block before it is read and hence,
// making sure the data comes form the disk and not the cache.
queue_size_ = ((cache_size_ / write_block_size_) * 3) / 2;
// Updating DiskBlockTable parameters
if (update_block_table_) {
block_table_->SetParameters(kSectorSize, write_block_size_,
device_sectors_, segment_size_,
device_name_);
}
return true;
}
// Open a device, return false on failure.
bool DiskThread::OpenDevice(int *pfile) {
int fd = open(device_name_.c_str(),
O_RDWR | O_SYNC | O_DIRECT | O_LARGEFILE,
0);
if (fd < 0) {
logprintf(0, "Process Error: Failed to open device %s (thread %d)!!\n",
device_name_.c_str(), thread_num_);
return false;
}
*pfile = fd;
return GetDiskSize(fd);
}
// Retrieves the size (in bytes) of the disk/file.
// Return false on failure.
bool DiskThread::GetDiskSize(int fd) {
struct stat device_stat;
if (fstat(fd, &device_stat) == -1) {
logprintf(0, "Process Error: Unable to fstat disk %s (thread %d).\n",
device_name_.c_str(), thread_num_);
return false;
}
// For a block device, an ioctl is needed to get the size since the size
// of the device file (i.e. /dev/sdb) is 0.
if (S_ISBLK(device_stat.st_mode)) {
uint64 block_size = 0;
if (ioctl(fd, BLKGETSIZE64, &block_size) == -1) {
logprintf(0, "Process Error: Unable to ioctl disk %s (thread %d).\n",
device_name_.c_str(), thread_num_);
return false;
}
// Zero size indicates nonworking device..
if (block_size == 0) {
os_->ErrorReport(device_name_.c_str(), "device-size-zero", 1);
++errorcount_;
status_ = true; // Avoid a procedural error.
return false;
}
device_sectors_ = block_size / kSectorSize;
} else if (S_ISREG(device_stat.st_mode)) {
device_sectors_ = device_stat.st_size / kSectorSize;
} else {
logprintf(0, "Process Error: %s is not a regular file or block "
"device (thread %d).\n", device_name_.c_str(),
thread_num_);
return false;
}
logprintf(12, "Log: Device sectors: %lld on disk %s (thread %d).\n",
device_sectors_, device_name_.c_str(), thread_num_);
if (update_block_table_) {
block_table_->SetParameters(kSectorSize, write_block_size_,
device_sectors_, segment_size_,
device_name_);
}
return true;
}
bool DiskThread::CloseDevice(int fd) {
close(fd);
return true;
}
// Return the time in microseconds.
int64 DiskThread::GetTime() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000 + tv.tv_usec;
}
// Do randomized reads and (possibly) writes on a device.
// Return false on fatal SW error, true on SW success,
// regardless of whether HW failed.
bool DiskThread::DoWork(int fd) {
int64 block_num = 0;
int64 num_segments;
if (segment_size_ == -1) {
num_segments = 1;
} else {
num_segments = device_sectors_ / segment_size_;
if (device_sectors_ % segment_size_ != 0)
num_segments++;
}
// Disk size should be at least 3x cache size. See comment later for
// details.
sat_assert(device_sectors_ * kSectorSize > 3 * cache_size_);
// This disk test works by writing blocks with a certain pattern to
// disk, then reading them back and verifying it against the pattern
// at a later time. A failure happens when either the block cannot
// be written/read or when the read block is different than what was
// written. If a block takes too long to write/read, then a warning
// is given instead of an error since taking too long is not
// necessarily an error.
//
// To prevent the read blocks from coming from the disk cache,
// enough blocks are written before read such that a block would
// be ejected from the disk cache by the time it is read.
//
// TODO(amistry): Implement some sort of read/write throttling. The
// flood of asynchronous I/O requests when a drive is
// unplugged is causing the application and kernel to
// become unresponsive.
while (IsReadyToRun()) {
// Write blocks to disk.
logprintf(16, "Log: Write phase %sfor disk %s (thread %d).\n",
non_destructive_ ? "(disabled) " : "",
device_name_.c_str(), thread_num_);
while (IsReadyToRunNoPause() &&
in_flight_sectors_.size() <
static_cast<size_t>(queue_size_ + 1)) {
// Confine testing to a particular segment of the disk.
int64 segment = (block_num / blocks_per_segment_) % num_segments;
if (!non_destructive_ &&
(block_num % blocks_per_segment_ == 0)) {
logprintf(20, "Log: Starting to write segment %lld out of "
"%lld on disk %s (thread %d).\n",
segment, num_segments, device_name_.c_str(),
thread_num_);
}
block_num++;
BlockData *block = block_table_->GetUnusedBlock(segment);
// If an unused sequence of sectors could not be found, skip to the
// next block to process. Soon, a new segment will come and new
// sectors will be able to be allocated. This effectively puts a
// minumim on the disk size at 3x the stated cache size, or 48MiB
// if a cache size is not given (since the cache is set as 16MiB
// by default). Given that todays caches are at the low MiB range
// and drive sizes at the mid GB, this shouldn't pose a problem.
// The 3x minimum comes from the following:
// 1. In order to allocate 'y' blocks from a segment, the
// segment must contain at least 2y blocks or else an
// allocation may not succeed.
// 2. Assume the entire disk is one segment.
// 3. A full write phase consists of writing blocks corresponding to
// 3/2 cache size.
// 4. Therefore, the one segment must have 2 * 3/2 * cache
// size worth of blocks = 3 * cache size worth of blocks
// to complete.
// In non-destructive mode, don't write anything to disk.
if (!non_destructive_) {
if (!WriteBlockToDisk(fd, block)) {
block_table_->RemoveBlock(block);
return true;
}
blocks_written_++;
}
// Block is either initialized by writing, or in nondestructive case,
// initialized by being added into the datastructure for later reading.
block->SetBlockAsInitialized();
in_flight_sectors_.push(block);
}
// Verify blocks on disk.
logprintf(20, "Log: Read phase for disk %s (thread %d).\n",
device_name_.c_str(), thread_num_);
while (IsReadyToRunNoPause() && !in_flight_sectors_.empty()) {
BlockData *block = in_flight_sectors_.front();
in_flight_sectors_.pop();
if (!ValidateBlockOnDisk(fd, block))
return true;
block_table_->RemoveBlock(block);
blocks_read_++;
}
}
pages_copied_ = blocks_written_ + blocks_read_;
return true;
}
// Do an asynchronous disk I/O operation.
// Return false if the IO is not set up.
bool DiskThread::AsyncDiskIO(IoOp op, int fd, void *buf, int64 size,
int64 offset, int64 timeout) {
// Use the Linux native asynchronous I/O interface for reading/writing.
// A read/write consists of three basic steps:
// 1. create an io context.
// 2. prepare and submit an io request to the context
// 3. wait for an event on the context.
struct {
const int opcode;
const char *op_str;
const char *error_str;
} operations[2] = {
{ IO_CMD_PREAD, "read", "disk-read-error" },
{ IO_CMD_PWRITE, "write", "disk-write-error" }
};
struct iocb cb;
memset(&cb, 0, sizeof(cb));
cb.aio_fildes = fd;
cb.aio_lio_opcode = operations[op].opcode;
cb.u.c.buf = buf;
cb.u.c.nbytes = size;
cb.u.c.offset = offset;
struct iocb *cbs[] = { &cb };
if (io_submit(aio_ctx_, 1, cbs) != 1) {
int error = errno;
char buf[256];
sat_strerror(error, buf, sizeof(buf));
logprintf(0, "Process Error: Unable to submit async %s "
"on disk %s (thread %d). Error %d, %s\n",
operations[op].op_str, device_name_.c_str(),
thread_num_, error, buf);
return false;
}
struct io_event event;
memset(&event, 0, sizeof(event));
struct timespec tv;
tv.tv_sec = timeout / 1000000;
tv.tv_nsec = (timeout % 1000000) * 1000;
if (io_getevents(aio_ctx_, 1, 1, &event, &tv) != 1) {
// A ctrl-c from the keyboard will cause io_getevents to fail with an
// EINTR error code. This is not an error and so don't treat it as such,
// but still log it.
int error = errno;
if (error == EINTR) {
logprintf(5, "Log: %s interrupted on disk %s (thread %d).\n",
operations[op].op_str, device_name_.c_str(),
thread_num_);
} else {
os_->ErrorReport(device_name_.c_str(), operations[op].error_str, 1);
errorcount_ += 1;
logprintf(0, "Hardware Error: Timeout doing async %s to sectors "
"starting at %lld on disk %s (thread %d).\n",
operations[op].op_str, offset / kSectorSize,
device_name_.c_str(), thread_num_);
}
// Don't bother checking return codes since io_cancel seems to always fail.
// Since io_cancel is always failing, destroying and recreating an I/O
// context is a workaround for canceling an in-progress I/O operation.
// TODO(amistry): Find out why io_cancel isn't working and make it work.
io_cancel(aio_ctx_, &cb, &event);
io_destroy(aio_ctx_);
aio_ctx_ = 0;
if (io_setup(5, &aio_ctx_)) {
int error = errno;
char buf[256];
sat_strerror(error, buf, sizeof(buf));
logprintf(0, "Process Error: Unable to create aio context on disk %s"
" (thread %d) Error %d, %s\n",
device_name_.c_str(), thread_num_, error, buf);
}
return false;
}
// event.res contains the number of bytes written/read or
// error if < 0, I think.
if (event.res != static_cast<uint64>(size)) {
errorcount_++;
os_->ErrorReport(device_name_.c_str(), operations[op].error_str, 1);
if (event.res < 0) {
switch (event.res) {
case -EIO:
logprintf(0, "Hardware Error: Low-level I/O error while doing %s to "
"sectors starting at %lld on disk %s (thread %d).\n",
operations[op].op_str, offset / kSectorSize,
device_name_.c_str(), thread_num_);
break;
default:
logprintf(0, "Hardware Error: Unknown error while doing %s to "
"sectors starting at %lld on disk %s (thread %d).\n",
operations[op].op_str, offset / kSectorSize,
device_name_.c_str(), thread_num_);
}
} else {
logprintf(0, "Hardware Error: Unable to %s to sectors starting at "
"%lld on disk %s (thread %d).\n",
operations[op].op_str, offset / kSectorSize,
device_name_.c_str(), thread_num_);
}
return false;
}
return true;
}
// Write a block to disk.
// Return false if the block is not written.
bool DiskThread::WriteBlockToDisk(int fd, BlockData *block) {
memset(block_buffer_, 0, block->GetSize());
// Fill block buffer with a pattern
struct page_entry pe;
if (!sat_->GetValid(&pe)) {
// Even though a valid page could not be obatined, it is not an error
// since we can always fill in a pattern directly, albeit slower.
unsigned int *memblock = static_cast<unsigned int *>(block_buffer_);
block->SetPattern(patternlist_->GetRandomPattern());
logprintf(11, "Log: Warning, using pattern fill fallback in "
"DiskThread::WriteBlockToDisk on disk %s (thread %d).\n",
device_name_.c_str(), thread_num_);
for (int i = 0; i < block->GetSize()/wordsize_; i++) {
memblock[i] = block->GetPattern()->pattern(i);
}
} else {
memcpy(block_buffer_, pe.addr, block->GetSize());
block->SetPattern(pe.pattern);
sat_->PutValid(&pe);
}
logprintf(12, "Log: Writing %lld sectors starting at %lld on disk %s"
" (thread %d).\n",
block->GetSize()/kSectorSize, block->GetAddress(),
device_name_.c_str(), thread_num_);
int64 start_time = GetTime();
if (!AsyncDiskIO(ASYNC_IO_WRITE, fd, block_buffer_, block->GetSize(),
block->GetAddress() * kSectorSize, write_timeout_)) {
return false;
}
int64 end_time = GetTime();
logprintf(12, "Log: Writing time: %lld us (thread %d).\n",
end_time - start_time, thread_num_);
if (end_time - start_time > write_threshold_) {
logprintf(5, "Log: Write took %lld us which is longer than threshold "
"%lld us on disk %s (thread %d).\n",
end_time - start_time, write_threshold_, device_name_.c_str(),
thread_num_);
}
return true;
}
// Verify a block on disk.
// Return true if the block was read, also increment errorcount
// if the block had data errors or performance problems.
bool DiskThread::ValidateBlockOnDisk(int fd, BlockData *block) {
int64 blocks = block->GetSize() / read_block_size_;
int64 bytes_read = 0;
int64 current_blocks;
int64 current_bytes;
uint64 address = block->GetAddress();
logprintf(20, "Log: Reading sectors starting at %lld on disk %s "
"(thread %d).\n",
address, device_name_.c_str(), thread_num_);
// Read block from disk and time the read. If it takes longer than the
// threshold, complain.
if (lseek64(fd, address * kSectorSize, SEEK_SET) == -1) {
logprintf(0, "Process Error: Unable to seek to sector %lld in "
"DiskThread::ValidateSectorsOnDisk on disk %s "
"(thread %d).\n", address, device_name_.c_str(), thread_num_);
return false;
}
int64 start_time = GetTime();
// Split a large write-sized block into small read-sized blocks and
// read them in groups of randomly-sized multiples of read block size.
// This assures all data written on disk by this particular block
// will be tested using a random reading pattern.
while (blocks != 0) {
// Test all read blocks in a written block.
current_blocks = (random() % blocks) + 1;
current_bytes = current_blocks * read_block_size_;
memset(block_buffer_, 0, current_bytes);
logprintf(20, "Log: Reading %lld sectors starting at sector %lld on "
"disk %s (thread %d)\n",
current_bytes / kSectorSize,
(address * kSectorSize + bytes_read) / kSectorSize,
device_name_.c_str(), thread_num_);
if (!AsyncDiskIO(ASYNC_IO_READ, fd, block_buffer_, current_bytes,
address * kSectorSize + bytes_read,
write_timeout_)) {
return false;
}
int64 end_time = GetTime();
logprintf(20, "Log: Reading time: %lld us (thread %d).\n",
end_time - start_time, thread_num_);
if (end_time - start_time > read_threshold_) {
logprintf(5, "Log: Read took %lld us which is longer than threshold "
"%lld us on disk %s (thread %d).\n",
end_time - start_time, read_threshold_,
device_name_.c_str(), thread_num_);
}
// In non-destructive mode, don't compare the block to the pattern since
// the block was never written to disk in the first place.
if (!non_destructive_) {
if (CheckRegion(block_buffer_, block->GetPattern(), current_bytes,
0, bytes_read)) {
os_->ErrorReport(device_name_.c_str(), "disk-pattern-error", 1);
errorcount_ += 1;
logprintf(0, "Hardware Error: Pattern mismatch in block starting at "
"sector %lld in DiskThread::ValidateSectorsOnDisk on "
"disk %s (thread %d).\n",
address, device_name_.c_str(), thread_num_);
}
}
bytes_read += current_blocks * read_block_size_;
blocks -= current_blocks;
}
return true;
}
// Direct device access thread.
// Return false on software error.
bool DiskThread::Work() {
int fd;
logprintf(9, "Log: Starting disk thread %d, disk %s\n",
thread_num_, device_name_.c_str());
srandom(time(NULL));
if (!OpenDevice(&fd)) {
status_ = false;
return false;
}
// Allocate a block buffer aligned to 512 bytes since the kernel requires it
// when using direst IO.
#ifdef HAVE_POSIX_MEMALIGN
int memalign_result = posix_memalign(&block_buffer_, kBufferAlignment,
sat_->page_length());
if (memalign_result) {
CloseDevice(fd);
logprintf(0, "Process Error: Unable to allocate memory for buffers "
"for disk %s (thread %d) posix memalign returned %d.\n",
device_name_.c_str(), thread_num_, memalign_result);
status_ = false;
return false;
}
#else
block_buffer_ = memalign(kBufferAlignment
sat_->page_length());
if (!block_buffer_) {
CloseDevice(fd);
logprintf(0, "Process Error: Unable to allocate memory for buffers "
"for disk %s (thread %d) memalign failed.\n",
device_name_.c_str(), thread_num_);
status_ = false;
return false;
}
#endif
if (io_setup(5, &aio_ctx_)) {
CloseDevice(fd);
logprintf(0, "Process Error: Unable to create aio context for disk %s"
" (thread %d).\n",
device_name_.c_str(), thread_num_);
status_ = false;
return false;
}
bool result = DoWork(fd);
status_ = result;
io_destroy(aio_ctx_);
CloseDevice(fd);
logprintf(9, "Log: Completed %d (disk %s): disk thread status %d, "
"%d pages copied\n",
thread_num_, device_name_.c_str(), status_, pages_copied_);
return result;
}
RandomDiskThread::RandomDiskThread(DiskBlockTable *block_table)
: DiskThread(block_table) {
update_block_table_ = 0;
}
RandomDiskThread::~RandomDiskThread() {
}
// Workload for random disk thread.
bool RandomDiskThread::DoWork(int fd) {
logprintf(11, "Log: Random phase for disk %s (thread %d).\n",
device_name_.c_str(), thread_num_);
while (IsReadyToRun()) {
BlockData *block = block_table_->GetRandomBlock();
if (block == NULL) {
logprintf(12, "Log: No block available for device %s (thread %d).\n",
device_name_.c_str(), thread_num_);
} else {
ValidateBlockOnDisk(fd, block);
block_table_->ReleaseBlock(block);
blocks_read_++;
}
}
pages_copied_ = blocks_read_;
return true;
}
#endif
MemoryRegionThread::MemoryRegionThread() {
error_injection_ = false;
pages_ = NULL;
}
MemoryRegionThread::~MemoryRegionThread() {
if (pages_ != NULL)
delete pages_;
}
// Set a region of memory or MMIO to be tested.
// Return false if region could not be mapped.
bool MemoryRegionThread::SetRegion(void *region, int64 size) {
int plength = sat_->page_length();
int npages = size / plength;
if (size % plength) {
logprintf(0, "Process Error: region size is not a multiple of SAT "
"page length\n");
return false;
} else {
if (pages_ != NULL)
delete pages_;
pages_ = new PageEntryQueue(npages);
char *base_addr = reinterpret_cast<char*>(region);
region_ = base_addr;
for (int i = 0; i < npages; i++) {
struct page_entry pe;
init_pe(&pe);
pe.addr = reinterpret_cast<void*>(base_addr + i * plength);
pe.offset = i * plength;
pages_->Push(&pe);
}
return true;
}
}
// More detailed error printout for hardware errors in memory or MMIO
// regions.
void MemoryRegionThread::ProcessError(struct ErrorRecord *error,
int priority,
const char *message) {
uint32 buffer_offset;
if (phase_ == kPhaseCopy) {
// If the error occurred on the Copy Phase, it means that
// the source data (i.e., the main memory) is wrong. so
// just pass it to the original ProcessError to call a
// bad-dimm error
WorkerThread::ProcessError(error, priority, message);
} else if (phase_ == kPhaseCheck) {
// A error on the Check Phase means that the memory region tested
// has an error. Gathering more information and then reporting
// the error.
// Determine if this is a write or read error.
os_->Flush(error->vaddr);
error->reread = *(error->vaddr);
char *good = reinterpret_cast<char*>(&(error->expected));
char *bad = reinterpret_cast<char*>(&(error->actual));
sat_assert(error->expected != error->actual);
unsigned int offset = 0;
for (offset = 0; offset < (sizeof(error->expected) - 1); offset++) {
if (good[offset] != bad[offset])
break;
}
error->vbyteaddr = reinterpret_cast<char*>(error->vaddr) + offset;
buffer_offset = error->vbyteaddr - region_;
// Find physical address if possible.
error->paddr = os_->VirtualToPhysical(error->vbyteaddr);
logprintf(priority,
"%s: miscompare on %s, CRC check at %p(0x%llx), "
"offset %llx: read:0x%016llx, reread:0x%016llx "
"expected:0x%016llx\n",
message,
identifier_.c_str(),
error->vaddr,
error->paddr,
buffer_offset,
error->actual,
error->reread,
error->expected);
} else {
logprintf(0, "Process Error: memory region thread raised an "
"unexpected error.");
}
}
// Workload for testion memory or MMIO regions.
// Return false on software error.
bool MemoryRegionThread::Work() {
struct page_entry source_pe;
struct page_entry memregion_pe;
bool result = true;
int64 loops = 0;
const uint64 error_constant = 0x00ba00000000ba00LL;
// For error injection.
int64 *addr = 0x0;
int offset = 0;
int64 data = 0;
logprintf(9, "Log: Starting Memory Region thread %d\n", thread_num_);
while (IsReadyToRun()) {
// Getting pages from SAT and queue.
phase_ = kPhaseNoPhase;
result = result && sat_->GetValid(&source_pe);
if (!result) {
logprintf(0, "Process Error: memory region thread failed to pop "
"pages from SAT, bailing\n");
break;
}
result = result && pages_->PopRandom(&memregion_pe);
if (!result) {
logprintf(0, "Process Error: memory region thread failed to pop "
"pages from queue, bailing\n");
break;
}
// Error injection for CRC copy.
if ((sat_->error_injection() || error_injection_) && loops == 1) {
addr = reinterpret_cast<int64*>(source_pe.addr);
offset = random() % (sat_->page_length() / wordsize_);
data = addr[offset];
addr[offset] = error_constant;
}
// Copying SAT page into memory region.
phase_ = kPhaseCopy;
CrcCopyPage(&memregion_pe, &source_pe);
memregion_pe.pattern = source_pe.pattern;
// Error injection for CRC Check.
if ((sat_->error_injection() || error_injection_) && loops == 2) {
addr = reinterpret_cast<int64*>(memregion_pe.addr);
offset = random() % (sat_->page_length() / wordsize_);
data = addr[offset];
addr[offset] = error_constant;
}
// Checking page content in memory region.
phase_ = kPhaseCheck;
CrcCheckPage(&memregion_pe);
phase_ = kPhaseNoPhase;
// Storing pages on their proper queues.
result = result && sat_->PutValid(&source_pe);
if (!result) {
logprintf(0, "Process Error: memory region thread failed to push "
"pages into SAT, bailing\n");
break;
}
result = result && pages_->Push(&memregion_pe);
if (!result) {
logprintf(0, "Process Error: memory region thread failed to push "
"pages into queue, bailing\n");
break;
}
if ((sat_->error_injection() || error_injection_) &&
loops >= 1 && loops <= 2) {
addr[offset] = data;
}
loops++;
YieldSelf();
}
pages_copied_ = loops;
status_ = result;
logprintf(9, "Log: Completed %d: Memory Region thread. Status %d, %d "
"pages checked\n", thread_num_, status_, pages_copied_);
return result;
}
| [
"amit.pundir@linaro.org"
] | amit.pundir@linaro.org |
2b5e10c1900d74a4f496b9d24e37cbd97cfadefd | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_log_535.cpp | 886ff07fe8780905d5dc504154228619aab3dfc4 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 110 | cpp | archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Parsing filters is unsupported."); | [
"993273596@qq.com"
] | 993273596@qq.com |
0b04aea7ae6dbce6e6ad9bf265547a78eda9ceb3 | d27a12add8024b04f227a0f3d9c3c7c35872d49a | /DataStructures/LinkedList/doubly_linkedlist.h | 2701bc047d22be23c0a3649347490ace711c93cc | [] | no_license | rishit-singh/Hacktoberfest2021 | e1763ce6adfb7109c5e898c1b6cde0ed3664b90d | eb1bb2f646022d7e5b400bdabadb14d303b63fa5 | refs/heads/main | 2023-09-03T13:43:12.079504 | 2021-10-31T20:30:22 | 2021-10-31T20:30:22 | 412,822,804 | 2 | 17 | null | 2021-11-01T05:55:23 | 2021-10-02T14:40:09 | C++ | UTF-8 | C++ | false | false | 3,793 | h | #include<iostream>
#include<stdlib.h>
using namespace std;
class Node
{
public:
int data;
Node * next;
Node * previous; Node()
{
data=0;
previous=NULL;
next=NULL;
}
Node(int d)
{
data=d;
previous=NULL;
next=NULL;
}
};
class DoublyLinkedlist
{
public:
Node *head;
DoublyLinkedlist()
{
head=NULL;
}
~DoublyLinkedlist()
{
delete head;
}
void createNode(int A[],int);
int append(Node *);
int prepend(Node *);
int insert(int,Node *);
int deleteNode(int);
void update(int,int);
void display();
int length();
};
int DoublyLinkedlist::length()
{
if(head==NULL) return 0;
Node *p=head;
int len=0;
while(p)
{
len++;
p=p->next;
}
return len;
}
void DoublyLinkedlist::createNode(int A[],int n)
{
Node *p=new Node(A[0]);
Node *t;
if(head==NULL)
{
head=p;
head->next=head->previous=NULL;
for (int i=1;i<n;i++)
{
t=new Node(A[i]);
t->next=NULL;
t->previous=p;
p->next=t;
p=t;
}
}
else
{
p=head;
while(p->next!=NULL)
p=p->next;
for (int i=0;i<n;i++)
{
t=new Node(A[i]);
t->next=NULL;
t->previous=p;
p->next=t;
p=t;
}
}
}
int DoublyLinkedlist::deleteNode(int x)
{
if (head==NULL)
{
cout<<"LINKED LIST IS ALREADY EMPTY";
return -1;
}
else
{
if(x<0 || x>length()-1)
{
cout<<"INVALID INDEX\n";
return -1;
}
else
{
int l;
Node *p,*q;
if(x==0)
{
p=head;
head=head->next;
l=p->data;
delete p;
return l;
}
else
{
p=head;
for(int i=0;i<x;i++)
p=p->next;
l=p->data;
p->previous->next=p->next;
if(p->next)
p->next->previous=p->previous;
delete p;
return l;
}
}
}
}
int DoublyLinkedlist::append(Node * n)
{
if(head==NULL)
{
head=n;
head->next=head->previous=NULL;
}
else
{
Node * p=head;
while(p->next!=NULL)
p=p->next;
p->next=n;
n->previous=p;
}
return n->data;
}
int DoublyLinkedlist::prepend(Node * n)
{
if(head==NULL)
{
head=n;
n->next=n->previous=NULL;
}
else
{
head->previous=n;
n->next=head;
head=n;
}
return n->data;
}
int DoublyLinkedlist::insert(int x,Node * n)
{
if(x<0 || x>length())
{
cout<<"INVALID INDEX\n";
return -1;
}
else
{
if(x==0)
return prepend(n);
else if(x==length())
return append(n);
else
{
Node * p=head;
for(int i=0;i<x-1;i++)
p=p->next;
n->next=p->next;
p->next->previous=n;
p->next=n;
n->previous=p;
return n->data;
}
}
}
void DoublyLinkedlist::update(int x,int d)
{
if(x<0 || x>length())
cout<<"INVALID INDEX\n";
else
{
int k;
Node *p=head;
for(int i=0;i<x;i++)
p=p->next;
k=p->data;
p->data=d;
cout<<"ELEMENT WAS UPDATED FROM "<<k<<" to "<<d<<" IN INDEX "<<x<<endl;
}
}
void DoublyLinkedlist::display()
{
if(head==NULL)
cout<<"LINKED LIST IS EMPTY.\n";
else
{
cout<<"ELEMENTS PRESENT IN LINKEDLIST:";
Node *p=head;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
b2c45365076bec95f02878c977b62ab16c4ffa66 | e6fb16da4e1c0742cb11aff4cbb33eaa577e4a4e | /Programs/ResourceEditor/Classes/Qt/DeviceInfo/MemoryTool/Widgets/SnapshotDiffViewerWidget.cpp | 2cce2a1773393dcb0f3ff080cdde68f91af805d9 | [] | no_license | swordlegend/dava.engine | bad0cd86958a6a7969e882225bc57949260b2c7c | a8972143a9cc10c3b398674b78866e4cf766d18f | refs/heads/development | 2021-01-22T20:08:18.649743 | 2017-03-16T12:18:36 | 2017-03-16T12:18:36 | 85,283,729 | 0 | 1 | null | 2017-03-17T07:35:31 | 2017-03-17T07:35:31 | null | UTF-8 | C++ | false | false | 4,146 | cpp | #include "Debug/DVAssert.h"
#include "Qt/DeviceInfo/MemoryTool/Models/SymbolsListModel.h"
#include "Qt/DeviceInfo/MemoryTool/Models/BranchDiffTreeModel.h"
#include "Qt/DeviceInfo/MemoryTool/Branch.h"
#include "Qt/DeviceInfo/MemoryTool/BranchDiff.h"
#include "Qt/DeviceInfo/MemoryTool/ProfilingSession.h"
#include "Qt/DeviceInfo/MemoryTool/MemorySnapshot.h"
#include "Qt/DeviceInfo/MemoryTool/Widgets/SymbolsWidget.h"
#include "Qt/DeviceInfo/MemoryTool/Widgets/FilterAndSortBar.h"
#include "Qt/DeviceInfo/MemoryTool/Widgets/MemoryBlocksWidget.h"
#include "Qt/DeviceInfo/MemoryTool/Widgets/SnapshotDiffViewerWidget.h"
#include <QTabWidget>
#include <QTreeView>
#include <QVBoxLayout>
#include <QFrame>
#include <QPushButton>
#include <QLineEdit>
#include <QSplitter>
using namespace DAVA;
SnapshotDiffViewerWidget::SnapshotDiffViewerWidget(const ProfilingSession* session_, size_t snapshotIndex1, size_t snapshotIndex2, QWidget* parent)
: QWidget(parent, Qt::Window)
, session(session_)
{
DVASSERT(session != nullptr);
snapshot1 = &session->Snapshot(snapshotIndex1);
snapshot2 = &session->Snapshot(snapshotIndex2);
allBlocksLinked = BlockLink::CreateBlockLink(snapshot1, snapshot2);
Init();
}
SnapshotDiffViewerWidget::~SnapshotDiffViewerWidget() = default;
void SnapshotDiffViewerWidget::Init()
{
tab = new QTabWidget;
InitMemoryBlocksView();
InitSymbolsView();
InitBranchView();
QVBoxLayout* mainLayout = new QVBoxLayout;
mainLayout->addWidget(tab);
setLayout(mainLayout);
}
void SnapshotDiffViewerWidget::InitSymbolsView()
{
symbolWidget = new SymbolsWidget(*snapshot1->SymbolTable());
QPushButton* buildTree = new QPushButton("Build tree");
connect(buildTree, &QPushButton::clicked, this, &SnapshotDiffViewerWidget::SymbolView_OnBuldTree);
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(buildTree);
layout->addWidget(symbolWidget);
QFrame* frame = new QFrame;
frame->setLayout(layout);
tab->addTab(frame, "Symbols");
}
void SnapshotDiffViewerWidget::InitBranchView()
{
branchTreeModel.reset(new BranchDiffTreeModel(snapshot1, snapshot2));
branchTree = new QTreeView;
branchTree->setFont(QFont("Consolas", 10, 500));
branchTree->setModel(branchTreeModel.get());
QItemSelectionModel* selModel = branchTree->selectionModel();
connect(selModel, &QItemSelectionModel::currentChanged, this, &SnapshotDiffViewerWidget::BranchView_SelectionChanged);
branchBlocksWidget = new MemoryBlocksWidget(session, &branchBlockLinked, false, false);
connect(branchBlocksWidget, &MemoryBlocksWidget::MemoryBlockDoubleClicked, this, &SnapshotDiffViewerWidget::MemoryBlockDoubleClicked);
QSplitter* splitter = new QSplitter(Qt::Vertical);
splitter->addWidget(branchTree);
splitter->addWidget(branchBlocksWidget);
tab->addTab(splitter, "Branches");
}
void SnapshotDiffViewerWidget::InitMemoryBlocksView()
{
memoryBlocksWidget = new MemoryBlocksWidget(session, &allBlocksLinked, true, true);
tab->addTab(memoryBlocksWidget, "Memory blocks");
}
void SnapshotDiffViewerWidget::SymbolView_OnBuldTree()
{
Vector<const String*> selection = symbolWidget->GetSelectedSymbols();
if (!selection.empty())
{
branchTreeModel->PrepareModel(selection);
tab->setCurrentIndex(2);
}
}
void SnapshotDiffViewerWidget::BranchView_SelectionChanged(const QModelIndex& current, const QModelIndex& previous)
{
BranchDiff* branchDiff = static_cast<BranchDiff*>(current.internalPointer());
branchBlocks1.clear();
branchBlocks2.clear();
if (branchDiff->left != nullptr)
{
branchBlocks1 = branchDiff->left->GetMemoryBlocks();
}
if (branchDiff->right)
{
branchBlocks2 = branchDiff->right->GetMemoryBlocks();
}
branchBlockLinked = BlockLink::CreateBlockLink(branchBlocks1, snapshot1, branchBlocks2, snapshot2);
branchBlocksWidget->SetBlockLink(&branchBlockLinked);
}
void SnapshotDiffViewerWidget::MemoryBlockDoubleClicked(const BlockLink::Item& item)
{
// TODO: expand callstack tree to view block allocation site
}
| [
"m_lazarev@wargaming.net"
] | m_lazarev@wargaming.net |
ad758a16fc15ff1b305471f9a88077cd4ec64937 | 950b0247ff19401d5ad8fad64fa44b0420f82496 | /Steps/main.cpp | c55a2c72caf09ce1682a1244a4b76d3daa86c0b6 | [] | no_license | Nada-Nasser/Problem-Solving | 24a96ffaf03deb75c387386e9cf5d57b394079c1 | fc7b86a9349eadb0c06a168ed88ce58e0732e42a | refs/heads/master | 2022-11-23T23:53:20.561601 | 2020-07-02T21:09:38 | 2020-07-02T21:09:38 | 276,746,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 770 | cpp | #include <iostream>
#define FastIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long
using namespace std;
int main()
{
FastIO;
ll n,m,Xc,Yc,k , nSteps = 0 , dx,dy;
cin >> n >> m >> Xc >> Yc >> k;
for(ll i = 0 ; i < k ; i++)
{
cin >> dx >> dy;
ll stepX = INT_MAX , stepY = INT_MAX;
if(dx > 0) stepX = (n-Xc)/dx;
else if (dx < 0) stepX = (1 - Xc)/dx;
if(dy > 0) stepY = (m-Yc)/dy;
else if(dy < 0) stepY = (1-Yc)/dy;
ll newSteps = min(stepX,stepY);
if(newSteps > 0 && newSteps!= INT_MAX)
{
Xc+= (newSteps*dx);
Yc+= (newSteps*dy);
nSteps+=newSteps;
}
}
cout << nSteps;
return 0;
}
| [
"36134746+Nada-Nasser@users.noreply.github.com"
] | 36134746+Nada-Nasser@users.noreply.github.com |
f74b3bb207f528dc884b21aee8bb2932ae5bd712 | d7d46d067b642ed71659f2c08ca12cd112775c9a | /codechef/gcdmax1.cpp | afd6e5fd5a602f8e7d25adab91cdc50c99273369 | [] | no_license | crbonilha/cp-problems | 9a1c36aef6bf755b3039926f8117a32c9298cf99 | 800ff7fb266930044423e8b0644ac09b48b80cc4 | refs/heads/main | 2023-08-17T13:52:34.579725 | 2021-10-02T08:56:10 | 2021-10-02T08:56:10 | 391,211,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,336 | cpp | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e5;
int n, k;
int v[MAXN+1];
int gcd(int a, int b) {
if(a < b) {
return gcd(b, a);
}
if(!b) {
return a;
}
return gcd(b, a%b);
}
int tree[MAXN*4];
int initTree(int idx, int l, int r) {
if(l == r) {
return tree[idx] = v[l];
}
int mid = (l+r)/2;
return tree[idx] = gcd(
initTree(idx*2, l, mid),
initTree(idx*2+1, mid+1, r)
);
}
int queryTree(int idx, int l, int r, int ql, int qr) {
if(qr < l or r < ql) {
return 0;
}
if(ql <= l and r <= qr) {
return tree[idx];
}
int mid = (l+r)/2;
return gcd(
queryTree(idx*2, l, mid, ql, qr),
queryTree(idx*2+1, mid+1, r, ql, qr)
);
}
bool solve(int len) {
for(int i=0; i+len<=n; i++) {
if(queryTree(1, 1, n, i+1, i+len) >= k) {
return true;
}
}
return false;
}
int main() {
scanf("%d %d", &n, &k);
for(int i=0; i<n; i++) {
scanf("%d", &v[i+1]);
}
initTree(1, 1, n);
int ans = 0, ini = 1, mid, fim = n+1;
while(ini < fim) {
mid = (ini+fim)/2;
if(solve(mid)) {
ans = mid;
ini = mid+1;
}
else {
fim = mid;
}
}
printf("%d\n", ans);
}
| [
"cristhian.bonilha@hotmail.com"
] | cristhian.bonilha@hotmail.com |
ee343fd6e21c1bf610a8e0f68b384de2e39d9432 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_7090.cpp | c83a7347b4e7d67fd6821e0b6c95aecd9b355822 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | cpp | f(old_cred != connssl->cred) {
infof(data, "schannel: old credential handle is stale, removing\n");
/* we're not taking old_cred ownership here, no refcount++ is needed */
Curl_ssl_delsessionid(conn, (void *)old_cred);
incache = FALSE;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
78e1e4cd0aa1912c640f4946c88a39a54666e9e4 | 65f9576021285bc1f9e52cc21e2d49547ba77376 | /LINUX/android/vendor/qcom/proprietary/qcril-hal/modules/sms/src/RilRequestWriteSmsToSimMessage.cpp | eac082bf57b51abd8ae626f60434ab5e2861f42a | [
"Apache-2.0"
] | permissive | AVCHD/qcs605_root_qcom | 183d7a16e2f9fddc9df94df9532cbce661fbf6eb | 44af08aa9a60c6ca724c8d7abf04af54d4136ccb | refs/heads/main | 2023-03-18T21:54:11.234776 | 2021-02-26T11:03:59 | 2021-02-26T11:03:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,780 | cpp | /******************************************************************************
# Copyright (c) 2017 Qualcomm Technologies, Inc.
# All Rights Reserved.
# Confidential and Proprietary - Qualcomm Technologies, Inc.
#******************************************************************************/
#include <string.h>
#include "modules/sms/RilRequestWriteSmsToSimMessage.h"
#include "telephony/ril.h"
RilRequestWriteSmsToSimMessage::~RilRequestWriteSmsToSimMessage() {
RIL_SMS_WriteArgs *payload = static_cast<RIL_SMS_WriteArgs*>(params.data);
delete payload->pdu;
delete payload->smsc;
delete payload;
}
void RilRequestWriteSmsToSimMessage::deepCopy(const ril_request_type &request) {
params.instance_id = request.instance_id;
params.modem_id = QCRIL_DEFAULT_MODEM_ID;
params.event_id = request.req_id;
params.t = request.t;
params.datalen = request.payload_len;
RIL_SMS_WriteArgs *payload = static_cast<RIL_SMS_WriteArgs*>(const_cast<void*>(request.payload));
RIL_SMS_WriteArgs *payload_copy = nullptr;
if (payload) {
char *pdu = nullptr;
size_t pdu_len;
if (payload->pdu) {
pdu_len = strlen(payload->pdu) + 1;
pdu = new char[pdu_len];
if (pdu) {
memcpy(pdu, payload->pdu, pdu_len);
}
}
char *smsc = nullptr;
size_t smsc_len;
if (payload->smsc) {
smsc_len = strlen(payload->smsc) + 1;
smsc = new char[smsc_len];
if (smsc) {
memcpy(smsc, payload->smsc, smsc_len);
}
}
payload_copy = new RIL_SMS_WriteArgs;
if (payload_copy) {
payload_copy->status = payload->status;
payload_copy->pdu = pdu;
payload_copy->smsc = smsc;
}
}
params.data = payload_copy;
}
string RilRequestWriteSmsToSimMessage::dump() {
return mName;
}
| [
"jagadeshkumar.s@pathpartnertech.com"
] | jagadeshkumar.s@pathpartnertech.com |
19207fd0c964ad511ecc6ec688b60bbaf0d2998c | 9e48aee08decf2bac02150454bfff2fc7d5af161 | /PS/2151 거울 설치.cc | 6912738cb38c059be9d9878289f6c4bb17c409fc | [] | no_license | sooooojinlee/TIL | f29649174506cfdf92ffeaaeaaedf343c232df0b | bd3755731a9cddc22117a5f57ccbdaa9c02d0fc4 | refs/heads/master | 2022-05-07T07:37:59.105932 | 2022-03-15T13:36:26 | 2022-03-15T13:36:26 | 202,124,182 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | cc | /*
설치해야 할 거울의 최소 개수
***#*
*.!.*
*!.!*
*.!.*
*#***
! : 거울을 놓을 수 있는 위치
# : 문
* : 벽
00010
00200
03040
00500
06000 -> 이런 형태로 만들어 주기
123456
1FFFTFF
2FFFFTF
3FFFTFT
4TFTTFF
5FTFFFF
6FFTFFF -> d[i][j] : i번 정점에서 j번 정점을 볼 수 있으면 i번 정점에서 직교하는(?) 방향으로 있으면 true
시작과 끝이 몇 번 정점인지 알아야 함
-> 항상 시작 정점에서 시작해서 끝 정점에서 끝나야 하기 때문에
mirror[i] : i번 정점까지 거쳐온 정점의 개수
-> mirror[end]-1 가 정답이 됨
mirror배열을 갱신해주면서 정답 찾기
*/
#include <iostream>
#include <vector>
#include <string>
#include <queue>
using namespace std;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
int main() {
int n;
cin >> n;
vector<string> a(n);
vector<pair<int, int>> v; //정점의 위치
int start, end; //시작 정점 번호
start = end = -1; //끝 정점 번호
for (int i = 0; i < n; i++) {
cin >> a[i];
for (int j = 0; j < n; j++) {
if (a[i][j] == '#') {
if (start == -1) {
start = v.size();
v.push_back(make_pair(i, j));
}
else {
v.push_back(make_pair(i, j));
end = v.size() - 1;
}
}
else if (a[i][j] == '!') {
v.push_back(make_pair(i, j));
}
}
}
int l = v.size();
vector<vector<int>> b(n, vector<int>(n)); //정점 번호로 표시
for (int i = 0; i < l; i++) {
int x, y;
x = v[i].first;
y = v[i].second;
b[x][y] = i;
}
vector<vector<bool>> d(l, vector<bool>(l, false)); //d[i][j] : i번 정점에서 j를 볼 수 있으면 true
for (int i = 0; i < l; i++) {
for (int k = 0; k < 4; k++) {
int x = v[i].first + dx[k];
int y = v[i].second + dy[k];
while (0 <= x && x < n && 0 <= y && y < n) {
if (a[x][y] == '*') break;
if (a[x][y] == '!' || a[x][y] == '#') {
d[i][b[x][y]] = true;
}
x += dx[k];
y += dy[k];
}
}
}
//거울을 놓는 최소 개수 -> start에서 end까지 정점을 방문하는 최소횟수 -> bfs
queue<int> q;
vector<int> mirror(l, -1);
mirror[start] = 0;
q.push(start);
while (!q.empty()) {
int x = q.front();
q.pop();
for (int i = 0; i < l; i++) {
if (d[x][i]==true && mirror[i] == -1) {
mirror[i] = mirror[x] + 1;
q.push(i);
}
}
}
cout << mirror[end] - 1 << '\n';
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
371d9669b034e968d0ac211bf2d6bce55ac60159 | be0aab78ff4fc4690733df831ba97d305ae8fa63 | /contests/may-world-codesprint/absolute-permutation.cc | b427fe97dab2d2074f349c8c2276a27a69a301cb | [] | no_license | nishchitajagadish/HackerRank | 502ec6a50724f9d9de2ce625b77b3b05bbd83622 | 2154268e24ecc0db8a80f4f40e8bf105e2064cd9 | refs/heads/master | 2022-12-20T12:02:19.461441 | 2020-04-29T13:58:28 | 2020-04-29T23:20:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cc | #include <iostream>
#include <type_traits>
using namespace std;
#define FOR(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
long cases, n, k;
for (cin >> cases; cases--; ) {
cin >> n >> k;
if (! k)
REP(i, n)
cout << i+1 << " \n"[i == n-1];
else if (n%k || n/k%2)
cout << -1 << '\n';
else
for (long i = 0; i < n; i += 2*k) {
REP(j, k)
cout << i+j+k+1 << ' ';
REP(j, k)
cout << i+j+1 << " \n"[i+j+k+1 == n];
}
}
}
| [
"i@maskray.me"
] | i@maskray.me |
59e53c8b01ada8ad55e617cb6bf98d6e67de4185 | 93f6e57c85b96892a86320d49d607d17fbf4ae21 | /3300/assignment8/huffman.cpp | 259bba6f054897edfdc5fe54f81419c31dbb0bf5 | [] | no_license | reiman2222/school-assigments | 53a1c43961f3ca068d654549fdd2b640cdcb6c04 | cf2fd649faedcfb54c1833a047847f64506d7fc4 | refs/heads/master | 2021-01-01T22:32:00.451220 | 2020-02-09T21:29:00 | 2020-02-09T21:29:00 | 239,371,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,369 | cpp | // CSCI 3300
// Assignment: 08
// Author: Jack Edwards
// File: hufffman.cpp
// Tab stops: 4
//This program encodes a text file using huffman's algorithm.
//This program expects and input file and and output file
//entered into the command line. The input file must come first.
//Ex: ./huffman inputfile outputfile
//to enaple tracing enter -t immediatly before the input file.
#include <cstdio>
#include <stdlib.h>
#include "trace.h"
#include "tree.h"
#include "pqueue.h"
#include <string.h>
#include "binary.h"
using namespace std;
const int FREQUENCIE_ARRAY_SIZE = 256;
const int MAX_TREE_DEPTH = 256;
typedef Node* Tree;
//strCopy(s) copies s into a new string in the heap and returns that string.
char* strCopy(char* s)
{
int length = strlen(s);
char* result = new char[length + 1];
int i = 0;
while(s[i] != '\0')
{
result[i] = s[i];
i++;
}
result[i] = '\0';
return result;
}
//initIntArray(array, size, val) initalizes all values in array to val.
//size is the size of the array.
void initIntArray(int* array, int size, int val)
{
for(int i = 0; i < size; i++)
{
array[i] = val;
}
}
//computeFrequincies(freqArray, inFileName) computes the frequincies of all
//characters in the file called inFileName. The character frequincies are
//stored in freqArray. computeFrequincies returns true if inFileName can be
//opened. if infileName cannot be opened then computeFrequincies returns
//false.
bool computeFrequincies(int* freqArray, char* inFileName)
{
FILE* inFile = fopen(inFileName, "r");
if(inFile == NULL)
{
return false;
}
initIntArray(freqArray, FREQUENCIE_ARRAY_SIZE, 0);
int c = getc(inFile);
while(c != EOF)
{
freqArray[c]++;
c = getc(inFile);
}
fclose(inFile);
return true;
}
//fillPQ(freqArray, treeQueue) inserts a node in to treeQueue
//for all character that have a frequency in freqArray greater than 0.
void fillPQ(int* freqArray, PriorityQueue& q)
{
for(int i = 0; i < FREQUENCIE_ARRAY_SIZE; i++)
{
if(freqArray[i] > 0)
{
Node* newNode = new Node((char)i);
insert(newNode, freqArray[i], q);
}
}
}
//buildHuffmanTree(freqArray) builds a huffman tree in the heap
//and returns that tree. if there is no tree to build buildHuffmanTree
//returns a NULL pointer. freqArray tells buildHuffmanTree which characters
//need to be in the tree.
Tree buildHuffmanTree(int* freqArray)
{
PriorityQueue treeQueue;
fillPQ(freqArray, treeQueue);
int pri1;
int pri2;
Node* node1 = NULL;
Node* node2;
while(!isEmpty(treeQueue))
{
remove(node1, pri1, treeQueue);
if(isEmpty(treeQueue))
{
return node1;
}
remove(node2, pri2, treeQueue);
Node* t = new Node(node1,node2);
insert(t, pri1 + pri2, treeQueue);
}
return node1;
}
//buildCodes(t, codeArray, pref) builds the huffman code for each of the
//characters in t. codeArray is the array to store the codes in.
//pref is the prefix of the code.
void buildCodes(Tree t, char** codeArray, char* pref)
{
if(t->kind == leaf)
{
codeArray[(int)t->ch] = strCopy(pref);
}
else
{
char leftPath[MAX_TREE_DEPTH];
char rightPath[MAX_TREE_DEPTH];
strcpy(leftPath, pref);
strcat(leftPath, "0");
strcpy(rightPath, pref);
strcat(rightPath, "1");
buildCodes(t->left, codeArray, leftPath);
buildCodes(t->right, codeArray, rightPath);
}
}
//buildCodeArray(t) builds codes for all characters in huffman tree t.
//If t has hight 1 then the code for its character will be 1. Otherwise
//the standard convention for huffman codes is used. buildCodeArray returns a
//pointer to the code array.
//
//Tree: (a,(b,c)) yeilds these codes
// a - 0
// b - 10
// c - 11
char** buildCodeArray(Tree t)
{
char** codeArray = new char*[FREQUENCIE_ARRAY_SIZE];
char prefix[MAX_TREE_DEPTH];
prefix[0] = '\0';
for(int i = 0; i < FREQUENCIE_ARRAY_SIZE; i++)
{
codeArray[i] = strCopy(prefix);
}
if(t->kind == leaf)
{
char* code = new char[MAX_TREE_DEPTH];
code[0] = '1';
code[1] = '\0';
codeArray[(int)t->ch] = code;
}
else
{
buildCodes(t, codeArray, prefix);
}
return codeArray;
}
//writeTree(f, t) writes a binary huffman tree to f. t is the tree to write.
void writeTree(BFILE* f, Tree t)
{
if(t->kind == leaf)
{
writeBit(f, 1);
writeByte(f, (int)t->ch);
}
else
{
writeBit(f, 0);
writeTree(f, t->left);
writeTree(f, t->right);
}
}
//writeEncodedChar(codeArray, charToEncode, outputFile) writes charToEncode
//into outputFile using the codes in codeArray.
void writeEncodedChar(char** codeArray, char charToEncode, BFILE* outputFile)
{
char* code = codeArray[(int)charToEncode];
for(int i = 0; code[i] != '\0'; i++)
{
if(code[i] == '1')
{
writeBit(outputFile, 1);
}
else
{
writeBit(outputFile, 0);
}
}
}
//writeEncodedFile(codeArray, outputFile, inputFile) uses the codes in codeArray
//to encode inputFile. The encoded text is stored in outputFile.
void writeEncodedFile(char** codeArray, BFILE* outputFile, const char* inputFile)
{
FILE* inFile = fopen(inputFile, "r");
if(inFile == NULL)
{
printf("ERROR: the file \"%s\" could not be read\n", inputFile);
exit(0);
}
int c = getc(inFile);
while(c != EOF)
{
writeEncodedChar(codeArray, c, outputFile);
c = getc(inFile);
}
fclose(inFile);
}
int main(int argc, char** argv)
{
enableTracing(argc, argv);
int* frequencies = new int[FREQUENCIE_ARRAY_SIZE];
Tree huffmanTree;
if(!computeFrequincies(frequencies, argv[argc - 2]))
{
printf("ERROR: the file \"%s\" could not be read\n", argv[argc - 2]);
exit(0);
}
if(tracelevel == 1)
{
printf("The character frequencies are:\n\n");
showFreqArray(frequencies, FREQUENCIE_ARRAY_SIZE);
printf("\n");
}
huffmanTree = buildHuffmanTree(frequencies);
if(tracelevel == 1)
{
printf("The Huffman tree is as follows: ");
printTree(huffmanTree);
printf("\n\n");
}
char** codes = buildCodeArray(huffmanTree);
if(tracelevel == 1)
{
printf("A Huffman code is as follows.\n\n");
printCodeArray(codes, FREQUENCIE_ARRAY_SIZE);
}
BFILE* outFile = openBinaryFileWrite(argv[argc - 1]);
if(outFile == NULL)
{
printf("ERROR: the file \"%s\" could not be opened\n", argv[argc - 1]);
exit(0);
}
writeTree(outFile, huffmanTree);
writeEncodedFile(codes, outFile, argv[argc - 2]);
closeBinaryFileWrite(outFile);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
3e5879bd021a8238ca916d35bf9bf2b785ebf65e | 6e06d982dc9700ab913e927c2a543a42ddbb6ba0 | /mxnet/src/legacy/array.hh | 4bdf5ba9b1aa67bd78e03f67f7cdac459f64879c | [] | no_license | chenjunweii/Object-Detection-T | 42fb45a5782075041b9926178b9860e129de9b66 | 0afd6c566896b757d0d7bdc9658ac4403261230c | refs/heads/master | 2020-04-08T17:50:45.576616 | 2019-06-28T03:00:34 | 2019-06-28T03:00:34 | 159,583,276 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 586 | hh | #ifndef FLT_ARRAY_HH
#define FLT_ARRAY_HH
#include <iostream>
#include "shape.hh"
using namespace std;
template <typename T>
inline flt::farray::farray(T * t, flt::fshape s) : shape(s), data(t), rank(s.rank){};
template <typename T>
inline T flt::farray::operator [] (T i) {
cursor = 0;
rank_cursor = 0;
if (rank == 1)
return (*data)[i];
}
/* recursive */
template <typename T>
inline flt::farray flt::farray::operator [] (T i){
if (i > shape[0])
cout << "not allowed slice"
cursor += shape[0] * i;
rank_cursor += 1;
return this;
}
#endif
| [
"iewnujnehc@gmail.com"
] | iewnujnehc@gmail.com |
04420c3b37c38a5a96325f434453c15a946d0409 | c0ea8c2ff266b21de05f8cd016d5d95b37489a58 | /UI/mysite/media/fun.h | 527070daf1486ee9519ebcda54559fd952eb669a | [] | no_license | VishnuTeja27/BTP-BranchChange | 98960ccd37434ddeedbb444678cb6c595a8f6307 | c2f0819a737846cda575420bde0c222ce6b1f94e | refs/heads/master | 2022-10-22T15:17:33.106538 | 2020-06-15T10:56:34 | 2020-06-15T10:56:34 | 220,156,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,788 | h | #include <bits/stdc++.h>
using namespace std;
int mode;
struct stream
{
string name;
string ID;
int san_strength;
int exis_strength;
int max_strength;
int min_strength;
};
struct student
{
int roll_no;
string name;
string current_stream;
float CGPA;
int jee_rank;
vector<string> preferences;
};
bool student_sorter(struct student a, struct student b)
{
if(a.CGPA!=b.CGPA)return (a.CGPA>b.CGPA);
return (a.jee_rank<b.jee_rank);
}
int get_mode()
{
return mode;
}
pair< vector<stream>,vector<student> >get_data()
{
ifstream file;
string w;
int m,n;
vector<stream> branch;
vector<student> stud;
file.open("input.txt");
if (!file.is_open())
{
cout<<"error 1 reading file";
}
file>>w;
mode=stoi(w);
file>>w;
m=stoi(w);
file>>w;
n=stoi(w);
for(int i=0;i<m;i++) // reading branches data
{
stream temp;
file>>w;
temp.name=w;
file>>w;
temp.ID=w;
file>>w;
temp.san_strength=stoi(w);
file>>w;
temp.exis_strength=stoi(w);
temp.max_strength=1.1*temp.san_strength-temp.exis_strength;
temp.min_strength=ceil(0.1*temp.exis_strength);
cout<<temp.name <<" : max:"<<temp.max_strength<<" min: "<<temp.min_strength<<"\n";
branch.push_back(temp);
}
for(int i=0;i<n;i++) //reading student data
{
student std;
int count;
file>>w;
std.roll_no=stoi(w);
file>>w;std.name=w;
file>>w;std.jee_rank=stoi(w);
file>>w;std.current_stream=w;
file>>w;std.CGPA=stof(w);
// file>>w;std.jee_rank=stoi(w);
file>>w;count=stoi(w);
for(int k=0;k<count;k++)
{
file>>w;
std.preferences.push_back(w);
}
stud.push_back(std);
}
sort(stud.begin(),stud.end(),student_sorter);
return (make_pair(branch,stud));
}
| [
"111601028@smail.iitpkd.ac.in"
] | 111601028@smail.iitpkd.ac.in |
b5968e3ef62b7bccd45432d033e7e2faea5aea72 | bb6ebff7a7f6140903d37905c350954ff6599091 | /chrome/browser/ui/webui/options/managed_user_import_handler.h | 52d129f1a132a6606166d57f5ea5638903062ca0 | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 3,520 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_MANAGED_USER_IMPORT_HANDLER_H_
#define CHROME_BROWSER_UI_WEBUI_OPTIONS_MANAGED_USER_IMPORT_HANDLER_H_
#include "base/callback_list.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observer.h"
#include "chrome/browser/supervised_user/supervised_user_sync_service_observer.h"
#include "chrome/browser/ui/webui/options/options_ui.h"
#include "components/signin/core/browser/signin_error_controller.h"
namespace base {
class DictionaryValue;
class ListValue;
}
namespace options {
// Handler for the 'import existing managed user' dialog.
class ManagedUserImportHandler : public OptionsPageUIHandler,
public SupervisedUserSyncServiceObserver,
public SigninErrorController::Observer {
public:
typedef base::CallbackList<void(const std::string&, const std::string&)>
CallbackList;
ManagedUserImportHandler();
virtual ~ManagedUserImportHandler();
// OptionsPageUIHandler implementation.
virtual void GetLocalizedValues(
base::DictionaryValue* localized_strings) OVERRIDE;
virtual void InitializeHandler() OVERRIDE;
// WebUIMessageHandler implementation.
virtual void RegisterMessages() OVERRIDE;
// SupervisedUserSyncServiceObserver implementation.
virtual void OnSupervisedUserAcknowledged(
const std::string& supervised_user_id) OVERRIDE {}
virtual void OnSupervisedUsersSyncingStopped() OVERRIDE {}
virtual void OnSupervisedUsersChanged() OVERRIDE;
// SigninErrorController::Observer implementation.
virtual void OnErrorChanged() OVERRIDE;
private:
// Clears the cached list of managed users and fetches the new list of managed
// users.
void FetchManagedUsers();
// Callback for the "requestManagedUserImportUpdate" message.
// Checks the sign-in status of the custodian and accordingly
// sends an update to the WebUI. The update can be to show/hide
// an error bubble and update/clear the managed user list.
void RequestManagedUserImportUpdate(const base::ListValue* args);
// Sends an array of managed users to WebUI. Each entry is of the form:
// managedProfile = {
// id: "Managed User ID",
// name: "Managed User Name",
// iconURL: "chrome://path/to/icon/image",
// onCurrentDevice: true or false,
// needAvatar: true or false
// }
// The array holds all existing managed users attached to the
// custodian's profile which initiated the request.
void SendExistingManagedUsers(const base::DictionaryValue* dict);
// Sends messages to the JS side to clear managed users and show an error
// bubble.
void ClearManagedUsersAndShowError();
bool IsAccountConnected() const;
bool HasAuthError() const;
// Called when a managed user shared setting is changed. If the avatar was
// changed, FetchManagedUsers() is called.
void OnSharedSettingChanged(const std::string& managed_user_id,
const std::string& key);
scoped_ptr<CallbackList::Subscription> subscription_;
ScopedObserver<SigninErrorController, ManagedUserImportHandler> observer_;
base::WeakPtrFactory<ManagedUserImportHandler> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ManagedUserImportHandler);
};
} // namespace options
#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_MANAGED_USER_IMPORT_HANDLER_H_
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
9e3c69fc97baf2d5cde45a395dbe88780dc88069 | 567aca2e067e136ed525fe1dfbcd34e6ee697107 | /lab13/src/vector.hpp | bf7278c18d8ddcefeb0d198ee3c3275b7638ac1f | [] | no_license | santroy/TAU | c884edea78ce9bc4b83575e6b8c47587510aba29 | 60897a359170414deb40428c1f3dda7fd7af174a | refs/heads/master | 2021-01-17T21:21:34.522013 | 2017-06-20T09:24:26 | 2017-06-20T09:24:26 | 84,177,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | hpp | #ifndef __VECTOR_HPP__
#define __VECTOR_HPP__
#include <vector>
class Vector {
private:
std::vector <int> params;
void printVector (int i);
public:
void addPoint(int point);
void add(Vector vectorToAdd);
void subtract(Vector vectorToAdd);
void multiply(Vector vectorToAdd);
void print();
bool equals(Vector vectorToCompare);
};
#endif // __WEKTOR_HPP__ | [
"krytront@gmail.com"
] | krytront@gmail.com |
8c6060cee7a3bb3f3247e1b4433bef1e09cf4829 | 01b2a5eb6f1b63bababb2eed55976b1b1d61305d | /InBus.cpp | 14a24dc8e2a7187e70266cf47934e3846c351620 | [] | no_license | Deathhero/DLabOOP | e39e7df66011da6fe83b93fc32d3eb4dce97693e | 24b38ee41b27ba92d39a19c38cbdcd8f4c6c528e | refs/heads/master | 2021-08-22T16:08:38.525970 | 2017-11-30T14:33:49 | 2017-11-30T14:33:49 | 112,617,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp | #include "Bus.h"
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
using namespace std;
void CheckInputFile(ifstream &ifst);
void CheckWrongInput(ifstream &ifst);
void bus::InData(ifstream &ifst)
{
CheckInputFile(ifst);
car::InData(ifst);
ifst >> passengercapacity;
CheckWrongInput(ifst);
if (passengercapacity <= 0)
{
cout << "Incorrect values in bus input." << endl;
exit(1);
}
} | [
"Deathhero"
] | Deathhero |
1816a1fc201e91fcaf66f506fdd8a4c3fe61b776 | 80c10e1aab0738d4c30a832538558ea6d294c3ff | /PhysX.Net-3.3/PhysX.Net-3/Source/MathUtil.h | 2b6a34eb79acca3afa748da91ed77c3d5048594c | [
"MIT"
] | permissive | corefan/PhysX.Net | 4f2334520043aa7c9cfd96c054cc2ee30bf3974e | f1144841e397088301bacbd4b8e24f5066180f7c | refs/heads/master | 2020-12-30T13:40:16.784563 | 2017-01-11T21:08:59 | 2017-01-11T21:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | h | #pragma once
namespace PhysX
{
public ref class MathUtil
{
internal:
static Matrix4x4 PxTransformToMatrix(PxTransform* transform);
static PxTransform MatrixToPxTransform(Matrix4x4 transform);
static Matrix4x4 PxMat33ToMatrix(PxMat33* matrix);
static PxMat33 MatrixToPxMat33(Matrix4x4 matrix);
static Matrix4x4 PxMat44ToMatrix(PxMat44* mat44);
static PxMat44 MatrixToPxMat44(Matrix4x4 matrix);
static Vector3 PxVec3ToVector3(PxVec3 vector);
static PxVec3 Vector3ToPxVec3(Vector3 vector);
static Vector3 PxExtendedVec3ToVector3(PxExtendedVec3 vector);
static PxExtendedVec3 Vector3ToPxExtendedVec3(Vector3 vector);
static Vector2 PxVec2ToVector2(PxVec2 vector);
static PxVec2 Vector2ToPxVec2(Vector2 vector);
static Quaternion PxQuatToQuaternion(PxQuat quat);
static PxQuat QuaternionToPxQuat(Quaternion quat);
public:
static bool IsMultipleOf(int num, int divisor);
const static float Pi = 3.1415926535897932384626433832795f;
const static float PiOver2 = Pi / 2.0f;
static int Vector3SizeInBytes = 12;
};
}; | [
"chad@stilldesign.co.nz"
] | chad@stilldesign.co.nz |
d7280c2c4f3cea2a3bb2528c62bf1bff51c8dc81 | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /boost/graph/grid_graph.hpp | b64f10e7d33c35369f06e0a9853e740be93bb1a8 | [] | no_license | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 62 | hpp | #include "thirdparty/boost_1_58_0/boost/graph/grid_graph.hpp"
| [
"qinzuoyan@xiaomi.com"
] | qinzuoyan@xiaomi.com |
2dbd4b45002ee56219a56a4fc060d7b062b8bf88 | 631cd4d687c4a8120e8bb60451bbd7b84f3ffb43 | /TinyGPSLibTest/TinyGPSLibTest.ino | 1c0ced683b760b97758d0f426dd72f81cdb0ac59 | [] | no_license | ianballou/Arduino | a33830fa7bc6af1fc8adc241b263d1f543c5b85c | 93917163eb281cec5ec36139c1851acdb0f0cece | refs/heads/master | 2021-06-26T22:17:56.175687 | 2017-03-20T16:59:23 | 2017-03-20T16:59:23 | 103,441,479 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 354 | ino | #include <TinyGPS++.h>
static const int RXPin = 19, TXPin = 18;
static const uint32_t GPSBaud = 115200;
// The TinyGPS++ object
TinyGPSPlus gps;
void setup() {
Serial.begin(115200);
Serial1.begin(GPSBaud);
}
void loop() {
while (Serial1.available() > 0) {
if (gps.encode(Serial1.read()))
Serial.println(gps.location.lat());
}
}
| [
"ianballou67@gmail.com"
] | ianballou67@gmail.com |
293609590cc0092ec9d51c0487aa1aa8e10101af | 6977220522948d2dd0218a9d9fc8cbb1f93c3536 | /MFCApplication4/MFCApplication4.cpp | 0cc6d14fa18afe31423cbf61b36676d4d9fa277b | [] | no_license | KevinJoback/MFCApplication4 | 841d651cd1f79e36a3cacbca96331eb3a9333b7b | 46abfe7886ff1550391bb8f4fcf6b0693f802555 | refs/heads/master | 2023-08-18T09:49:50.965256 | 2021-09-18T04:55:26 | 2021-09-18T04:55:26 | 407,753,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,370 | cpp |
// MFCApplication4.cpp : Defines the class behaviors for the application.
//
#include "pch.h"
#include "framework.h"
#include "afxwinappex.h"
#include "afxdialogex.h"
#include "MFCApplication4.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "MFCApplication4Doc.h"
#include "MFCApplication4View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFCApplication4App
BEGIN_MESSAGE_MAP(CMFCApplication4App, CWinApp)
ON_COMMAND(ID_APP_ABOUT, &CMFCApplication4App::OnAppAbout)
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
// CMFCApplication4App construction
CMFCApplication4App::CMFCApplication4App() noexcept
{
// support Restart Manager
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#ifdef _MANAGED
// If the application is built using Common Language Runtime support (/clr):
// 1) This additional setting is needed for Restart Manager support to work properly.
// 2) In your project, you must add a reference to System.Windows.Forms in order to build.
System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif
// TODO: replace application ID string below with unique ID string; recommended
// format for string is CompanyName.ProductName.SubProduct.VersionInformation
SetAppID(_T("MFCApplication4.AppID.NoVersion"));
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CMFCApplication4App object
CMFCApplication4App theApp;
// This identifier was generated to be statistically unique for your app
// You may change it if you prefer to choose a specific identifier
// {57008ad8-a511-4146-b52e-4b557c606b46}
static const CLSID clsid =
{0x57008ad8,0xa511,0x4146,{0xb5,0x2e,0x4b,0x55,0x7c,0x60,0x6b,0x46}};
const GUID CDECL _tlid = {0x2a2edf81,0x8cf6,0x44ce,{0x9c,0x96,0xcd,0x97,0x58,0x3e,0x09,0xcd}};
const WORD _wVerMajor = 1;
const WORD _wVerMinor = 0;
// CMFCApplication4App initialization
BOOL CMFCApplication4App::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
UINT wndStyle = CS_DBLCLKS; // | CS_HREDRAW | CS_VREDRAW;
m_WndClassName = AfxRegisterWndClass(wndStyle);
AfxEnableControlContainer();
EnableTaskbarInteraction(FALSE);
// AfxInitRichEdit2() is required to use RichEdit control
// AfxInitRichEdit2();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(4); // Load standard INI file options (including MRU)
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views
CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(IDR_MFCApplication4TYPE,
RUNTIME_CLASS(CMFCApplication4Doc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CMFCApplication4View));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// Connect the COleTemplateServer to the document template
// The COleTemplateServer creates new documents on behalf
// of requesting OLE containers by using information
// specified in the document template
m_server.ConnectTemplate(clsid, pDocTemplate, FALSE);
// Register all OLE server factories as running. This enables the
// OLE libraries to create objects from other applications
COleTemplateServer::RegisterAll();
// Note: MDI applications register all server objects without regard
// to the /Embedding or /Automation on the command line
// create main MDI Frame window
CMainFrame* pMainFrame = new CMainFrame;
if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
{
delete pMainFrame;
return FALSE;
}
m_pMainWnd = pMainFrame;
// call DragAcceptFiles only if there's a suffix
// In an MDI app, this should occur immediately after setting m_pMainWnd
// Enable drag/drop open
m_pMainWnd->DragAcceptFiles();
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Enable DDE Execute open
EnableShellOpen();
RegisterShellFileTypes(TRUE);
// App was launched with /Embedding or /Automation switch.
// Run app as automation server.
if (cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated)
{
// Don't show the main window
return TRUE;
}
// App was launched with /Unregserver or /Unregister switch. Unregister
// typelibrary. Other unregistration occurs in ProcessShellCommand().
else if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister)
{
UnregisterShellFileTypes();
m_server.UpdateRegistry(OAT_DISPATCH_OBJECT, nullptr, nullptr, FALSE);
AfxOleUnregisterTypeLib(_tlid, _wVerMajor, _wVerMinor);
}
// App was launched standalone or with other switches (e.g. /Register
// or /Regserver). Update registry entries, including typelibrary.
else
{
m_server.UpdateRegistry(OAT_DISPATCH_OBJECT);
COleObjectFactory::UpdateRegistryAll();
AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid);
}
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The main window has been initialized, so show and update it
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();
return TRUE;
}
int CMFCApplication4App::ExitInstance()
{
//TODO: handle additional resources you may have added
AfxOleTerm(FALSE);
return CWinApp::ExitInstance();
}
// CMFCApplication4App message handlers
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg() noexcept;
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() noexcept : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// App command to run the dialog
void CMFCApplication4App::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CMFCApplication4App message handlers
| [
"kevinjoback@outlook.com"
] | kevinjoback@outlook.com |
8190b27e2e487523c2d5f5ce82fefe4ada8fa9e1 | 47933728cd916c6d9de1e2f8afa64c82b197afcb | /ampblas/inc/detail/tuning/tune.h | 9dd6723c9bb908fda87f2941b9452f9d9ac98912 | [
"LicenseRef-scancode-blas-2017",
"Apache-2.0"
] | permissive | TechnikEmpire/ampblas | 6742bb054ff4bb213101e266aa2e5d0514882c95 | ac461cf8474951034e9d92c82ff98ca245991c07 | refs/heads/master | 2023-09-03T04:34:46.614195 | 2012-10-01T21:13:55 | 2012-10-01T21:13:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | h | #ifndef AMPBLAS_TUNE_H
#define AMPBLAS_TUNE_H
#include "ampblas_dev.h"
#include <string>
AMPBLAS_NAMESPACE_BEGIN
DETAIL_NAMESPACE_BEGIN
// a list of architectures used by the tuning framework
enum class architecture
{
// AMD architectures
amd, // generic
// NVIDIA architectures
nvidia, // generic
nvidia_xxx, // unused example of another architecture that could be added
// fall back
unknown
};
// incredibly simple architecture parser
inline enum class architecture get_architecture(std::wstring& description)
{
const std::wstring& amd_key(L"AMD");
const std::wstring& nvidia_key(L"NVIDIA");
if (description.find(amd_key) != std::string::npos)
return architecture::amd;
else if (description.find(nvidia_key) != std::string::npos)
return architecture::nvidia;
else
return architecture::unknown;
}
DETAIL_NAMESPACE_END
AMPBLAS_NAMESPACE_END
#endif // AMPBLAS_TUNE_H
| [
"SND\\kyle_spagnoli_cp@4a90e977-6436-4932-9605-20e10c2b6fb3"
] | SND\kyle_spagnoli_cp@4a90e977-6436-4932-9605-20e10c2b6fb3 |
781ea66bbc60f8814679e85ebe28051989513376 | bd5b975eb16d7167ddcb37715146e2962b2b7592 | /otl4_examples/ex444_odbc.cpp | 2a94df0a1aa8591df2b495517a36d4f5db243925 | [] | no_license | HJolin1986/otl | 5bfa1c98dfbe34c1cf38964cd114ef09a4bf454a | d3d12b0bb8749455a0e5fd9a1ee222e3b77323a5 | refs/heads/master | 2020-08-26T09:41:58.977048 | 2013-12-09T16:02:13 | 2013-12-09T16:02:13 | 15,051,842 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,965 | cpp | #include <iostream>
using namespace std;
#include <stdio.h>
#define OTL_ODBC
//#define OTL_ODBC_UNIX // Compile OTL 4.0/DB2-CLI
#include <otlv4.h> // include the OTL 4.0 header file
otl_connect db; // connect object
void insert()
// insert rows into table
{otl_long_string f2(6000); // define long string variable
otl_stream o; // defined an otl_stream variable
o.set_lob_stream_mode(true); // set the "lob stream mode" flag
o.open(1, // buffer size has to be set to 1 for operations with LOBs
"insert into test_tab values(:f1<int>,:f2<raw_long>, "
":f3<raw_long>) ",
// SQL statement
db // connect object
);
o.set_commit(0); // setting stream "auto-commit" to "off". It is required
// when LOB stream mode is used.
int i,j;
otl_lob_stream lob; // LOB stream for reading/writing unlimited number
// of bytes regardless of the buffer size.
otl_lob_stream lob2; // LOB stream for reading/writing unlimited number
// of bytes regardless of the buffer size.
for(i=1;i<=20;++i){
o<<i;
o<<lob; // Initialize otl_lob_stream by writing it
// into otl_stream.
o<<lob2; // Initialize otl_lob_stream by writing it
// into otl_stream.
for(j=0;j<5000;++j)
f2[j]='*';
f2[5000]='?';
f2.set_len(5001);
// OTL 4.0.138 and higher does not require the LOB's total length to be
// set beforehand. Instead, otl_long_string::last_piece can be used.
// lob.set_len(5001+2123); // setting the total size of
// // the IMAGE to be written.
lob<<f2; // writing first chunk of the IMAGE into lob
f2[2122]='?';
f2.set_len(2123); // setting the size of the second chunk
lob<<f2; // writing the second chunk of the IMAGE into lob
lob.close(); // closing the otl_lob_stream
for(j=0;j<5000;++j)
f2[j]='*';
f2[5000]='?';
f2.set_len(5001);
lob2.set_len(5001+2123); // setting the total size of
// the IMAGE to be written.
lob2<<f2; // writing first chunk of the IMAGE into lob
f2[2122]='?';
f2.set_len(2123); // setting the size of the second chunk
lob2<<f2; // writing the second chunk of the IMAGE into lob
lob2.close(); // closing the otl_lob_stream
}
db.commit(); // committing transaction.
}
void update()
// insert rows in table
{
otl_long_string f2(6200); // define long string variable
otl_stream o; // defined an otl_stream variable
o.set_lob_stream_mode(true); // set the "lob stream mode" flag
o.open(1, // buffer size has to be set to 1 for operations with LOBs
"update test_tab "
" set f2=:f2<raw_long> "
"where f1=:f1<int> ",
// SQL statement
db // connect object
);
otl_lob_stream lob;
o.set_commit(0); // setting stream "auto-commit" to "off".
for(int j=0;j<6000;++j){
f2[j]='#';
}
f2[6000]='?';
f2.set_len(6001);
o<<lob; // Initialize otl_lob_stream by writing it
// into otl_stream.
o<<5;
// OTL 4.0.138 and higher does not require the LOB's total length to be
// set beforehand. Instead, otl_long_string::last_piece can be used.
// lob.set_len(6001*4); // setting the total size of of the IMAGE to be written
for(int i=1;i<=4;++i)
lob<<f2; // writing chunks of the IMAGE into the otl_lob_stream
lob.close(); // closing the otl_lob_stream
db.commit(); // committing transaction
}
void select()
{
otl_long_string f2(3000); // define long string variable
otl_stream i; // defined an otl_stream variable
i.set_lob_stream_mode(true); // set the "lob stream mode" flag
i.open(1, // buffer size. To read IMAGEs, it should be set to 1
"select * from test_tab where f1>=:f11<int> and f1<=:f12<int>*2",
// SELECT statement
db // connect object
);
// create select stream
int f1;
otl_lob_stream lob; // Stream for reading IMAGE
otl_lob_stream lob2; // Stream for reading IMAGE
i<<4<<4; // assigning :f11 = 4, :f12 = 4
// SELECT automatically executes when all input variables are
// assigned. First portion of output rows is fetched to the buffer
while(!i.eof()){ // while not end-of-data
i>>f1;
cout<<"f1="<<f1<<endl;
i>>lob; // initializing LOB stream by reading the IMAGE reference
// into the otl_lob_stream from the otl_stream.
i>>lob2; // initializing LOB stream by reading the IMAGE reference
// into the otl_lob_stream from the otl_stream.
int n=0;
while(!lob.eof()){ // read while not "end-of-file" -- end of IMAGE
++n;
lob>>f2; // reading a chunk of IMAGE
cout<<" chunk #"<<n;
cout<<", f2="<<f2[0]<<f2[f2.len()-1]<<", len="<<f2.len()<<endl;
}
lob.close(); // closing the otl_lob_stream.
n=0;
while(!lob2.eof()){ // read while not "end-of-file" -- end of IMAGE
++n;
lob2>>f2; // reading a chunk of IMAGE
cout<<" chunk #"<<n;
cout<<", f3="<<f2[0]<<f2[f2.len()-1]<<", len="<<f2.len()<<endl;
}
lob2.close(); // closing the otl_lob_stream.
}
}
int main()
{
otl_connect::otl_initialize(); // initialize the environment
try{
db.rlogon("scott/tigger@sybsql"); // connect to the database
otl_cursor::direct_exec
(
db,
"drop table test_tab",
otl_exception::disabled // disable OTL exceptions
); // drop table
otl_cursor::direct_exec
(
db,
"create table test_tab(f1 int, f2 image, f3 image)"
); // create table
insert(); // insert records into table
update(); // update records in table
select(); // select records from table
}
catch(otl_exception& p){ // intercept OTL exceptions
cerr<<p.msg<<endl; // print out error message
cerr<<p.sqlstate<<endl; // print out SQLSTATE
cerr<<p.stm_text<<endl; // print out SQL that caused the error
cerr<<p.var_info<<endl; // print out the variable that caused the error
}
db.logoff(); // disconnect from the database
return 0;
}
| [
"hjolin1986@gmail.com"
] | hjolin1986@gmail.com |
ca01938b1ac15fbb1312959e69ee64259f6b6ce5 | 691576d742cd713a46784b684204b2f6bcd15117 | /swap_ary.cpp | 8c4e88e876c1c377fc0160012e6f5a4171216835 | [] | no_license | babitab/helloworld | 07b033bcd822972ffb8f19714fbe744ab8ccd907 | c72de033d0f4d35c1d03562090eec0ceb87697e5 | refs/heads/master | 2021-01-22T10:55:57.062677 | 2017-06-18T17:34:53 | 2017-06-18T17:34:53 | 92,661,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | // swap two array of same size
#include<iostream>
using namespace std;
int main()
{
int a[] = {1, 2,3,4};
int b[] = {5,6,7,8};
int n = sizeof(a)/sizeof(0);
int i;
swap( a,b);
cout<<"a[] is :"<<endl;
for( i=0 ; i<n;i++)
{
cout<<a[i]<<","<<endl;
}
cout<<"b[] is :"<<endl;
for( i=0 ; i<n ;i++)
{
cout<<b[i]<<","<<endl;
}
} | [
"burdakbabita207@gmail.com"
] | burdakbabita207@gmail.com |
51798090b7e0e0e6b4a8aff404619cb3f35e4d0c | 49cfc3f1a96b3f75adf74821342999a20da3e04d | /tests/test_time_timezone.cpp | 39fee608c7b9c00d183803c2cc8c60781a8791e6 | [
"MIT"
] | permissive | mrexodia/CppCommon | bfb4456b984ceea64dd98853816f388c29bfe006 | 422bec80be2412e909539b73be40972ecc8acf83 | refs/heads/master | 2020-05-17T15:10:23.069691 | 2019-04-25T14:36:20 | 2019-04-25T14:36:20 | 183,780,482 | 1 | 0 | MIT | 2019-04-27T14:05:08 | 2019-04-27T14:05:08 | null | UTF-8 | C++ | false | false | 932 | cpp | //
// Created by Ivan Shynkarenka on 18.07.2016
//
#include "test.h"
#include "time/timezone.h"
using namespace CppCommon;
TEST_CASE("Timezone", "[CppCommon][Time]")
{
Timezone timezone1("Test", Timespan::hours(-8), Timespan::hours(1));
REQUIRE(timezone1.name() == "Test");
REQUIRE(timezone1.offset() == Timespan::hours(-8));
REQUIRE(timezone1.daylight() == Timespan::hours(1));
REQUIRE(timezone1.total() == Timespan::hours(-7));
Timezone timezone2 = Timezone::utc();
REQUIRE(timezone2 == Timezone("GMT", Timespan::zero()));
UtcTime utctime;
LocalTime localtime(utctime);
Timezone timezone3 = Timezone::local();
REQUIRE(localtime == timezone3.Convert(utctime));
REQUIRE(utctime == timezone3.Convert(localtime));
Timezone timezone4 = Timezone::utc();
Timezone timezone5 = Timezone::local();
REQUIRE(std::abs((timezone4.total() - timezone5.total()).hours()) < 24);
}
| [
"chronoxor@gmail.com"
] | chronoxor@gmail.com |
46169bffb65c1a5fe6feb949fc0fab23f1c54161 | 7dafec8c884552e7f482d5cd0711964f663804d2 | /Reserva.h | 38c43b7d8414928a06bd9846d59b6e92ee82a228 | [] | no_license | pepehdezx2/sistema-de-reservas | 55b564ca7c5e546f0b0c518872b0797492694de1 | 16258600b5510ba23632eefd16b5962f31c4a268 | refs/heads/master | 2020-04-03T18:19:10.656023 | 2018-10-31T01:18:48 | 2018-10-31T01:18:48 | 155,478,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,282 | h | //
// Reserva.h
// avancepro3
//
// Created by Pepe Hdez hdez on 4/13/18.
// Copyright © 2018 Pepe Hdez hdez. All rights reserved.
//
#ifndef Reserva_h
#define Reserva_h
#include "Fecha.h"
#include <iostream>
#include <string>
using namespace std;
class Reserva{
public:
Reserva();
Reserva(int idm, int idc, Fecha fr);
void setMaterial(int);
void setCliente(int);
void setFechaReservacion(Fecha);
int getMaterial();
int getCliente();
Fecha getFechaReservacion();
Fecha calculaFechaFinReserva(int di);
private:
int idmat, idcl;
Fecha fechar;
};
Reserva::Reserva(){
Fecha x(0, 0, 0);
idmat=0;
idcl=0;
fechar=x;
}
Reserva::Reserva(int idm, int idc, Fecha fr){
idmat=idm;
idcl=idc;
fechar=fr;
}
void Reserva::setCliente(int idcl){
this->idcl=idcl;
}
void Reserva::setMaterial(int idmat){
this->idmat=idmat;
}
void Reserva::setFechaReservacion(Fecha fr){
this->fechar=fechar;
}
int Reserva::getCliente(){
return idcl;
}
int Reserva::getMaterial(){
return idmat;
}
Fecha Reserva::getFechaReservacion(){
return fechar;
}
Fecha Reserva::calculaFechaFinReserva(int di){
int year, month, day, dias;
dias=di;
year=fechar.getYear();
month=fechar.getMonth();
day=fechar.getDay();
if(month == 1 || month == 3 || month == 7 || month == 8 || month == 10 || month == 12){
if(day+dias>31){
day-=31;
month+=1;
if(month>12)
{
month=1;
year+=1;
}
}
else
day+=dias;
}
else
if(month == 2){
if(year%4==0){
if(day+dias>29)
{
day-=29;
month+=1;
}
else
day+=dias;
}
else{
if(day+dias>28){
day-=28;
month+=1;
}
else
day+=dias;
}
}
else
if(day+dias>30){
day-=30;
month+=1;
}
else
day+=dias;
Fecha x(day, month, year);
return x;
}
#endif /* Reserva_h */
| [
"pepehdezx2@gmail.com"
] | pepehdezx2@gmail.com |
3b969cd880211fc72cf9e9bf843ee4a05ea8fdf9 | ae936fb07d9478152cb998e94b9937d625f5c3dd | /Codeforces/CF1352G.cpp | 74429b8d07d4c5ad7a9b1d2e3df7f6ed2c3c71a3 | [] | no_license | Jorgefiestas/CompetitiveProgramming | f035978fd2d3951dbd1ffd14d60236ef548a1974 | b35405d6be5adf87e9a257be2fa0b14f5eba3c83 | refs/heads/master | 2021-06-12T06:28:20.878137 | 2021-04-21T01:32:37 | 2021-04-21T01:32:37 | 164,651,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
int t, n, a[N];
const int b[4][7] = {{2, 4, 1, 3},
{2, 4, 1, 3, 5},
{2, 4, 6, 3, 1, 5},
{2, 4, 6, 3, 1, 5, 7}};
void solve() {
cin >> n;
if (n == 1) {
cout << 1 << '\n';
return;
}
if (n <= 3) {
cout << -1 << '\n';
return;
}
int d = 0;
while (n >= 8) {
for (int i = 0; i < 4; i++) {
cout << b[0][i] + d<< ' ';
}
n -= 4;
d += 4;
}
for (int i = 0; i < n; i++) {
cout << b[n - 4][i] + d << ' ';
}
cout << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> t;
while (t--) {
solve();
}
return 0;
}
| [
"jorge.fiestas@utec.edu.pe"
] | jorge.fiestas@utec.edu.pe |
3607e3c66b2a552f23eee628ec6904890391a445 | c831d5b1de47a062e1e25f3eb3087404b7680588 | /webkit/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h | 78fd8eeea4bae6ca7fa8db51c125089ef2083df9 | [] | no_license | naver/sling | 705b09c6bba6a5322e6478c8dc58bfdb0bfb560e | 5671cd445a2caae0b4dd0332299e4cfede05062c | refs/heads/master | 2023-08-24T15:50:41.690027 | 2016-12-20T17:19:13 | 2016-12-20T17:27:47 | 75,152,972 | 126 | 6 | null | 2022-10-31T00:25:34 | 2016-11-30T04:59:07 | C++ | UTF-8 | C++ | false | false | 1,898 | h | /*
* Copyright (C) 2012 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ewk_error_private_h
#define ewk_error_private_h
#include "WKEinaSharedString.h"
#include <WKRetainPtr.h>
#include <WebKit/WKBase.h>
class EwkError {
public:
explicit EwkError(WKErrorRef errorRef);
const char* url() const;
const char* description() const;
WKRetainPtr<WKStringRef> domain() const;
int errorCode() const;
bool isCancellation() const;
private:
WKRetainPtr<WKErrorRef> m_wkError;
WKEinaSharedString m_url;
WKEinaSharedString m_description;
};
#endif // ewk_error_private_h
| [
"daewoong.jang@navercorp.com"
] | daewoong.jang@navercorp.com |
101188770f4e89d389f20d2be95d9e29d420f25a | bd7c8bb8679bc2eebe86ffb339930baa8cf82821 | /matrix/init_backfill.cc | 1baac5189299e9d7a9726e6c1e79951dc541ae59 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | andyoknen/construct | 9eddaf912642ada2f283497483e46e91cbf321ca | 3e2e876ebe49d7747097d7ede5cec41212fab83e | refs/heads/master | 2023-02-07T21:26:17.283640 | 2020-12-29T03:39:30 | 2020-12-29T03:41:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,621 | cc | // Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2019 Jason Volk <jason@zemos.net>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
namespace ircd::m::init::backfill
{
void handle_room(const room::id &);
void worker();
extern size_t count, complete;
extern ircd::run::changed handle_quit;
extern ctx::ctx *worker_context;
extern ctx::pool *worker_pool;
extern conf::item<seconds> delay;
extern conf::item<seconds> gossip_timeout;
extern conf::item<bool> gossip_enable;
extern conf::item<bool> local_joined_only;
extern conf::item<size_t> viewports;
extern conf::item<size_t> attempt_max;
extern conf::item<size_t> pool_size;
extern conf::item<bool> enable;
extern log::log log;
};
decltype(ircd::m::init::backfill::log)
ircd::m::init::backfill::log
{
"m.init.backfill"
};
decltype(ircd::m::init::backfill::enable)
ircd::m::init::backfill::enable
{
{ "name", "ircd.m.init.backfill.enable" },
{ "default", true },
};
decltype(ircd::m::init::backfill::pool_size)
ircd::m::init::backfill::pool_size
{
{ "name", "ircd.m.init.backfill.pool_size" },
{ "default", 12L },
};
decltype(ircd::m::init::backfill::local_joined_only)
ircd::m::init::backfill::local_joined_only
{
{ "name", "ircd.m.init.backfill.local_joined_only" },
{ "default", true },
};
decltype(ircd::m::init::backfill::gossip_enable)
ircd::m::init::backfill::gossip_enable
{
{ "name", "ircd.m.init.backfill.gossip.enable" },
{ "default", true },
};
decltype(ircd::m::init::backfill::gossip_timeout)
ircd::m::init::backfill::gossip_timeout
{
{ "name", "ircd.m.init.backfill.gossip.timeout" },
{ "default", 5L },
};
decltype(ircd::m::init::backfill::delay)
ircd::m::init::backfill::delay
{
{ "name", "ircd.m.init.backfill.delay" },
{ "default", 15L },
};
decltype(ircd::m::init::backfill::viewports)
ircd::m::init::backfill::viewports
{
{ "name", "ircd.m.init.backfill.viewports" },
{ "default", 4L },
};
decltype(ircd::m::init::backfill::attempt_max)
ircd::m::init::backfill::attempt_max
{
{ "name", "ircd.m.init.backfill.attempt_max" },
{ "default", 8L },
};
decltype(ircd::m::init::backfill::count)
ircd::m::init::backfill::count;
decltype(ircd::m::init::backfill::complete)
ircd::m::init::backfill::complete;
decltype(ircd::m::init::backfill::worker_pool)
ircd::m::init::backfill::worker_pool;
decltype(ircd::m::init::backfill::worker_context)
ircd::m::init::backfill::worker_context;
decltype(ircd::m::init::backfill::handle_quit)
ircd::m::init::backfill::handle_quit
{
run::level::QUIT, []
{
fini();
}
};
void
ircd::m::init::backfill::init()
{
if(!enable)
{
log::warning
{
log, "Initial synchronization of rooms from remote servers has"
" been disabled by the configuration. Not fetching latest events."
};
return;
}
ctx::context context
{
"m.init.backfill",
512_KiB,
&worker,
context::POST
};
// Detach into the worker_context ptr. When the worker finishes it
// will free itself.
assert(!worker_context);
worker_context = context.detach();
}
void
ircd::m::init::backfill::fini()
noexcept
{
if(worker_context)
log::debug
{
log, "Terminating worker context..."
};
if(worker_pool)
worker_pool->terminate();
if(worker_context)
{
ctx::terminate(*worker_context);
worker_context = nullptr;
}
}
void
ircd::m::init::backfill::worker()
try
{
// Wait for runlevel RUN before proceeding...
run::barrier<ctx::interrupted>{};
// Set a low priority for this context; see related pool_opts
ionice(ctx::cur(), 4);
nice(ctx::cur(), 4);
// Prepare to iterate all of the rooms this server is aware of which
// contain at least one member from another server in any state, and
// one member from our server in a joined state.
rooms::opts opts;
opts.remote_only = true;
opts.local_joined_only = local_joined_only;
// This is only an estimate because the rooms on the server can change
// before this task completes.
const auto estimate
{
1UL //rooms::count(opts)
};
if(!estimate)
return;
// Wait a delay before starting.
ctx::sleep(seconds(delay));
log::notice
{
log, "Starting initial backfill of rooms from other servers...",
estimate,
};
// Prepare a pool of child contexts to process rooms concurrently.
// The context pool lives directly in this frame.
static const ctx::pool::opts pool_opts
{
512_KiB, // stack sz
size_t(pool_size), // pool sz
-1, // queue max hard
0, // queue max soft
true, // queue max blocking
true, // queue max warning
3, // ionice
3, // nice
};
ctx::pool pool
{
"m.init.backfill", pool_opts
};
const scope_restore backfill_worker_pool
{
backfill::worker_pool, std::addressof(pool)
};
// Iterate the room_id's, submitting a copy of each to the next pool
// worker; the submission blocks when all pool workers are busy, as per
// the pool::opts.
ctx::dock dock;
const ctx::uninterruptible ui;
rooms::for_each(opts, [&pool, &estimate, &dock]
(const room::id &room_id)
{
if(unlikely(ctx::interruption_requested()))
return false;
++count;
pool([&, room_id(std::string(room_id))] // asynchronous
{
const unwind completed{[&dock]
{
++complete;
dock.notify_one();
}};
handle_room(room_id);
log::info
{
log, "Initial backfill of %s complete:%zu", //estimate:%zu %02.2lf%%",
string_view{room_id},
complete,
estimate,
(complete / double(estimate)) * 100.0,
};
});
return true;
});
if(complete < count)
log::dwarning
{
log, "Waiting for initial resynchronization count:%zu complete:%zu rooms...",
count,
complete,
};
// All rooms have been submitted to the pool but the pool workers might
// still be busy. If we unwind now the pool's dtor will kill the workers
// so we synchronize their completion here.
dock.wait([]
{
return complete >= count;
});
if(count)
log::notice
{
log, "Initial resynchronization of %zu rooms completed.",
count,
};
}
catch(const ctx::interrupted &e)
{
if(count)
log::derror
{
log, "Worker interrupted without completing resynchronization of all rooms."
};
throw;
}
catch(const ctx::terminated &e)
{
if(count)
log::error
{
log, "Worker terminated without completing resynchronization of all rooms."
};
throw;
}
catch(const std::exception &e)
{
log::critical
{
log, "Worker fatal :%s",
e.what(),
};
}
void
ircd::m::init::backfill::handle_room(const room::id &room_id)
{
{
struct m::acquire::opts opts;
opts.room = room_id;
opts.viewport_size = ssize_t(m::room::events::viewport_size);
opts.viewport_size *= size_t(viewports);
opts.vmopts.infolog_accept = true;
opts.vmopts.warnlog &= ~vm::fault::EXISTS;
opts.attempt_max = size_t(attempt_max);
m::acquire
{
opts
};
const size_t num_reset
{
m::room::head::reset(opts.room)
};
}
if((false))
{
struct m::gossip::opts opts;
opts.room = room_id;
m::gossip
{
opts
};
}
}
| [
"jason@zemos.net"
] | jason@zemos.net |
a94cea6625409cd71d8a7740491853eab4545a7d | 7c967fcc31034f7478db30c7ace18bea3af0ba89 | /other/SoundHound_Inc_2018/d1.cpp | 6f77706cdd9a53bc3dbd4a89efbb435b6a5293a0 | [] | no_license | 2019Shun/AtCoder | 8079cb6714519ac4ce9cc864a6cc24f24fa1c21d | 4dc2280663f9d0db623df9da4a0db1ba4999b5b2 | refs/heads/master | 2020-06-01T15:34:36.212422 | 2019-09-26T18:06:07 | 2019-09-26T18:06:07 | 190,835,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,028 | cpp | #include <bits/stdc++.h>
#include <vector>
#include <numeric>
#define PI 3.14159265358979323846
#define MAXINF (1e18L)
#define INF (1e9L)
#define EPS (1e-9)
#define MOD (1e9+7)
#define REP(i, n) for(int i=0;i<int(n);++i)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define RREP(i, n) for(int i=int(n)-1;i>=0;--i)
#define ALL(v) v.begin(),v.end()
#define FIND(v,x) (binary_search(ALL(v),(x)))
#define SORT(v) sort(ALL(v))
#define RSORT(v) sort(ALL(v));reverse(ALL(v))
#define DEBUG(x) cerr<<#x<<": "<<x<<endl;
#define DEBUG_VEC(v) cerr<<#v<<":";for(int i=0;i<v.size();i++) cerr<<" "<<v[i]; cerr<<endl
#define Yes(n) cout<<((n)?"Yes":"No")<<endl
#define YES(n) cout<<((n)?"YES":"NO")<<endl
#define pb push_back
#define fi first
#define se second
using namespace std;
template<class A>void pr(A a){cout << (a) << endl;}
template<class A,class B>void pr(A a,B b){cout << a << " " ;pr(b);}
template<class A,class B,class C>void pr(A a,B b,C c){cout << a << " " ;pr(b,c);}
template<class A,class B,class C,class D>void pr(A a,B b,C c,D d){cout << a << " " ;pr(b,c,d);}
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll,ll> pll;
//cost_map pll -> <to, cost>
// vector<ll> dijkstra(ll s, vector<vector<pll>>& cost_map){
// vector<ll> d(cost_map.size(), MAXINF);
// priority_queue<pll, vector<pll>, greater<pll>> q;
// q.push(pll(0, s));
// d[s] = 0;
// while(!q.empty()){
// pll f = q.top();q.pop();
// if(d[f.se] < f.fi) continue;
// for(auto&& v : cost_map[f.se]){
// ll value = f.fi + v.se;
// if(value < d[v.fi]) {
// q.push(pll(d[v.fi] = f.fi + v.se, v.fi));
// }
// }
// }
// return d;
// }
//cost_map pll -> <to, cost>
vector<ll> dijkstra(ll s, vector<vector<pll>>& cost_map){
vector<ll> d(cost_map.size(), MAXINF);
priority_queue<pll, vector<pll>, greater<pll>> q;
q.push(pll(0, s));
d[s] = 0;
while(!q.empty()){
pll f = q.top();q.pop();
if(d[f.se] < f.fi) continue;
for(auto&& v : cost_map[f.se]){
ll value = f.fi + v.se;
if(value < d[v.fi]) q.push(pll(d[v.fi] = f.fi + v.se, v.fi));
}
}
return d;
}
int main(void)
{
ll n,m;
cin >> n >> m;
ll s,t;
cin >> s >> t;
s--;t--;
vector<vector<pll>>Y(n);
vector<vector<pll>>S(n);
REP(i, m){
ll u,v;
cin >> u >> v;
ll a,b;
cin >> a >> b;
u--;v--;
Y[u].pb(make_pair(v, a));
Y[v].pb(make_pair(u, a));
S[u].pb(make_pair(v, b));
S[v].pb(make_pair(u, b));
}
auto yen = dijkstra(s, Y);
auto snk = dijkstra(t, S);
vector<ll> ans(n+1,MAXINF);
RREP(i, n){
ans[i]=min(ans[i+1], yen[i] + snk[i]);
}
// DEBUG_VEC(yen);
// DEBUG_VEC(snk);
// DEBUG_VEC(ans);
REP(i, n){
pr(1'000'000'000'000'000 - ans[i]);
}
} | [
"taka.shun.2018@gmail.com"
] | taka.shun.2018@gmail.com |
d51d557c7375f73fcd33d9678158f4d5fb591cc1 | 49de83d66a5052bdec06d2448424138125cc865e | /TankGame/src/Engine/Components/CharacterControllerComponent.cpp | cb4dd7b12e716cdaf0f52028a13e40d7985a7853 | [] | no_license | thomasgoodwin/tankgame | 7ea677c658d923397161c47ccdcf7ea8d13d2a49 | a201cb93095c8db55b174570f7624806bf94f039 | refs/heads/master | 2023-02-25T05:58:42.406939 | 2021-02-11T06:22:36 | 2021-02-11T06:22:36 | 337,945,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,078 | cpp | #include "CharacterControllerComponent.h"
#include "../Math.h"
#include "../GameObjects/PlayerGameObject.h"
#include "../Engine.h"
#include "../Systems/SFMLSystem.h"
CharacterControllerComponent::CharacterControllerComponent()
{
}
CharacterControllerComponent::~CharacterControllerComponent()
{
}
void CharacterControllerComponent::initialize()
{
PlayerGameObject* player = dynamic_cast<PlayerGameObject*>(getParent());
MATH::calculateDirectionVector(m_directionVector, player->getShape().getRotation());
}
void CharacterControllerComponent::shutdown()
{
}
void CharacterControllerComponent::tick(float dt)
{
PlayerGameObject* player = dynamic_cast<PlayerGameObject*>(getParent());
if (player->getPlayerID() == 1)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
MATH::calculateDirectionVector(m_directionVector, player->getShape().getRotation());
sf::Vector2f movementDelta = sf::Vector2f(m_directionVector.x * m_moveSpeed * dt, m_directionVector.y * m_moveSpeed * dt);
if (!checkBounds(movementDelta))
{
player->move(movementDelta);
}
//std::cout << player->getPosition().x << ", " << player->getPosition().y << std::endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
MATH::calculateDirectionVector(m_directionVector, player->getShape().getRotation());
sf::Vector2f movementDelta = sf::Vector2f(m_directionVector.x * -m_moveSpeed * dt, m_directionVector.y * -m_moveSpeed * dt);
if (!checkBounds(movementDelta))
{
player->move(movementDelta);
}
//std::cout << player->getPosition().x << ", " << player->getPosition().y << std::endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
{
player->isFiring(true);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
player->getShape().setRotation(player->getShape().getRotation() - (dt * m_rotationSpeed));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
player->getShape().setRotation(player->getShape().getRotation() + (dt * m_rotationSpeed));
}
}
else
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::I))
{
MATH::calculateDirectionVector(m_directionVector, player->getShape().getRotation());
sf::Vector2f movementDelta = sf::Vector2f(m_directionVector.x * m_moveSpeed * dt, m_directionVector.y * m_moveSpeed * dt);
if (!checkBounds(movementDelta))
{
player->move(movementDelta);
}
//std::cout << player->getPosition().x << ", " << player->getPosition().y << std::endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::K))
{
MATH::calculateDirectionVector(m_directionVector, player->getShape().getRotation());
sf::Vector2f movementDelta = sf::Vector2f(m_directionVector.x * -m_moveSpeed * dt, m_directionVector.y * -m_moveSpeed * dt);
if (!checkBounds(movementDelta))
{
player->move(movementDelta);
}
//std::cout << player->getPosition().x << ", " << player->getPosition().y << std::endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::O))
{
player->isFiring(true);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::J))
{
player->getShape().setRotation(player->getShape().getRotation() - (dt * m_rotationSpeed));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::L))
{
player->getShape().setRotation(player->getShape().getRotation() + (dt * m_rotationSpeed));
}
}
}
void CharacterControllerComponent::render()
{
}
bool CharacterControllerComponent::checkBounds(sf::Vector2f movementDelta)
{
PlayerGameObject* player = dynamic_cast<PlayerGameObject*>(getParent());
sf::Vector2u windowSize = Engine::get().getSFMLSystem().getWindow()->getSize();
sf::Vector2f playerNewPosition = { player->getPosition().x + movementDelta.x , player->getPosition().y + movementDelta.y };
if (playerNewPosition.x < 0.0f || playerNewPosition.y < 0.0f || playerNewPosition.x > windowSize.x || playerNewPosition.y > windowSize.y)
{
return true;
}
return false;
} | [
"thomas.goodwin99@gmail.com"
] | thomas.goodwin99@gmail.com |
9e79b1b19741b25f355bd69f0859d307cc6e389e | b3fb26d3e99b331abd77dde6800ca22ef2102e29 | /单程序混合高斯模型/StdAfx.cpp | 0c4eb1eb4c5302572fd6f9198f6e7143f821c1f2 | [] | no_license | hypo123/VehicleVideoTracking | 7828a220273bfdd318b17b3b29675e460b15c60e | 9eeaaae3c0cf1345b3beae9b5be7e6aa6b873688 | refs/heads/master | 2020-04-06T07:11:08.697393 | 2017-07-19T02:43:10 | 2017-07-19T02:43:10 | 64,911,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | // stdafx.cpp : source file that includes just the standard includes
// gmm.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"863153658@qq.com"
] | 863153658@qq.com |
1f78a6ac80ac7c40c335ad1065d03cbebbf5cc66 | e96a0bc65d1e015881030f3f94e2145bb2b163ea | /Usefull/dfs.cpp | c143f76c20e98e31f7430b16949f44b069dd4b3c | [] | no_license | TimTam725/Atcoder | 85a8d2f1961da9ed873312e90bd357f46eb2892b | 067dcb03e6ad2f311f0b4de911fae273cee5113c | refs/heads/main | 2023-06-06T02:06:34.833164 | 2021-06-20T06:22:01 | 2021-06-20T06:22:01 | 378,565,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,462 | cpp | #include<bits/stdc++.h>
#include<bits/stdc++.h>
#include<iomanip>
using namespace std;
typedef long long ll;
typedef long l;
typedef pair<int,int> P;
#define rep(i,n) for(int i=0;i<n;i++)
#define fs first
#define sc second
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define ALL(A) A.begin(),A.end()
const int INF=1000000001;
const double PI=3.141592653589;
int main(){
int h,w; cin>>h>>w;
vector<string> s(h);
rep(i,h) cin>>s[i];
vector<int> dx={-1,0,1,0};
vector<int> dy={0,1,0,-1};
// rep(i,4)
// cout<<dx[i]<<endl;
vector<vector<bool>> memo(h,vector<bool>(w));
rep(i,h){
rep(j,w){
if(memo[i][j]||s[i][j]=='.') continue;
queue<P> st;
// cout<<"iku"<<endl;
st.push({i,j});
while(!(st.empty())){
int x=st.front().fs;
int y=st.front().sc;
rep(k,4){
int zx=x+dx[k];
int zy=y+dy[k];
// if(x==0&&y==6)
// cout<<zx<<" "<<zy<<endl;
if(zx<0||h<=zx||zy<0||w<=zy) continue;
if(s[zx][zy]=='#'&&!(memo[zx][zy])){
memo[zx][zy]=1;
// memo[zx-dx[k]][zy-dy[k]]=1;
st.push({zx,zy});
}
}
st.pop();
}
}
}
rep(i,h){
rep(j,w){
if(s[i][j]=='#'&&!(memo[i][j])){
cout<<"No"<<endl;
return 0;
}
}
}
cout<<"Yes"<<endl;
return 0;
}
| [
"root@DESKTOP-PJOIK5S.localdomain"
] | root@DESKTOP-PJOIK5S.localdomain |
ca71e95a242804a9433a0d3e846805081b32b150 | d9f81d536aab8d00535fed9bfb463601321af248 | /JuceLibraryCode/modules/juce_audio_devices/native/juce_win32_DirectSound.cpp | 1953581944f26dceda84dd023cb91bbe33478264 | [] | no_license | teragonaudio/Convolver | 698a818a348a996e7527947abfe57e790030817d | 4d91e2383e3b7b17e5c4ce0c5aaf226d05ca64d1 | refs/heads/master | 2016-09-15T21:47:43.305102 | 2013-03-24T13:19:45 | 2013-03-24T13:19:45 | 8,984,945 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 45,060 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
} // (juce namespace)
extern "C"
{
// Declare just the minimum number of interfaces for the DSound objects that we need..
typedef struct typeDSBUFFERDESC
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwBufferBytes;
DWORD dwReserved;
LPWAVEFORMATEX lpwfxFormat;
GUID guid3DAlgorithm;
} DSBUFFERDESC;
struct IDirectSoundBuffer;
#undef INTERFACE
#define INTERFACE IDirectSound
DECLARE_INTERFACE_(IDirectSound, IUnknown)
{
STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
STDMETHOD(GetCaps) (THIS_ void*) PURE;
STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
STDMETHOD(Compact) (THIS) PURE;
STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
};
#undef INTERFACE
#define INTERFACE IDirectSoundBuffer
DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
{
STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
STDMETHOD(GetCaps) (THIS_ void*) PURE;
STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
STDMETHOD(SetVolume) (THIS_ LONG) PURE;
STDMETHOD(SetPan) (THIS_ LONG) PURE;
STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
STDMETHOD(Stop) (THIS) PURE;
STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
STDMETHOD(Restore) (THIS) PURE;
};
//==============================================================================
typedef struct typeDSCBUFFERDESC
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwBufferBytes;
DWORD dwReserved;
LPWAVEFORMATEX lpwfxFormat;
} DSCBUFFERDESC;
struct IDirectSoundCaptureBuffer;
#undef INTERFACE
#define INTERFACE IDirectSoundCapture
DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
{
STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
STDMETHOD(GetCaps) (THIS_ void*) PURE;
STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
};
#undef INTERFACE
#define INTERFACE IDirectSoundCaptureBuffer
DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
{
STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
STDMETHOD(GetCaps) (THIS_ void*) PURE;
STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
STDMETHOD(Start) (THIS_ DWORD) PURE;
STDMETHOD(Stop) (THIS) PURE;
STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
};
#undef INTERFACE
}
namespace juce
{
//==============================================================================
namespace DSoundLogging
{
String getErrorMessage (HRESULT hr)
{
const char* result = nullptr;
switch (hr)
{
case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
case E_INVALIDARG: result = "Invalid parameter"; break;
case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
case E_FAIL: result = "Generic error"; break;
case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
case E_OUTOFMEMORY: result = "Out of memory"; break;
case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
case E_NOTIMPL: result = "Unsupported function"; break;
case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
case E_NOINTERFACE: result = "No interface"; break;
case S_OK: result = "No error"; break;
default: return "Unknown error: " + String ((int) hr);
}
return result;
}
//==============================================================================
#if JUCE_DIRECTSOUND_LOGGING
static void logMessage (String message)
{
message = "DSOUND: " + message;
DBG (message);
Logger::writeToLog (message);
}
static void logError (HRESULT hr, int lineNum)
{
if (FAILED (hr))
{
String error ("Error at line ");
error << lineNum << ": " << getErrorMessage (hr);
logMessage (error);
}
}
#define CATCH JUCE_CATCH_EXCEPTION
#define JUCE_DS_LOG(a) DSoundLogging::logMessage(a);
#define JUCE_DS_LOG_ERROR(a) DSoundLogging::logError(a, __LINE__);
#else
#define CATCH JUCE_CATCH_ALL
#define JUCE_DS_LOG(a)
#define JUCE_DS_LOG_ERROR(a)
#endif
}
//==============================================================================
namespace
{
#define DSOUND_FUNCTION(functionName, params) \
typedef HRESULT (WINAPI *type##functionName) params; \
static type##functionName ds##functionName = nullptr;
#define DSOUND_FUNCTION_LOAD(functionName) \
ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
jassert (ds##functionName != nullptr);
typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
void initialiseDSoundFunctions()
{
if (dsDirectSoundCreate == nullptr)
{
HMODULE h = LoadLibraryA ("dsound.dll");
DSOUND_FUNCTION_LOAD (DirectSoundCreate)
DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
}
}
// the overall size of buffer used is this value x the block size
enum { blocksPerOverallBuffer = 16 };
}
//==============================================================================
class DSoundInternalOutChannel
{
public:
DSoundInternalOutChannel (const String& name_, const GUID& guid_, int rate,
int bufferSize, float* left, float* right)
: bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
pDirectSound (nullptr), pOutputBuffer (nullptr)
{
}
~DSoundInternalOutChannel()
{
close();
}
void close()
{
if (pOutputBuffer != nullptr)
{
JUCE_DS_LOG ("closing output: " + name);
HRESULT hr = pOutputBuffer->Stop();
JUCE_DS_LOG_ERROR (hr); (void) hr;
pOutputBuffer->Release();
pOutputBuffer = nullptr;
}
if (pDirectSound != nullptr)
{
pDirectSound->Release();
pDirectSound = nullptr;
}
}
String open()
{
JUCE_DS_LOG ("opening output: " + name + " rate=" + String (sampleRate)
+ " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
pDirectSound = nullptr;
pOutputBuffer = nullptr;
writeOffset = 0;
String error;
HRESULT hr = E_NOINTERFACE;
if (dsDirectSoundCreate != nullptr)
hr = dsDirectSoundCreate (&guid, &pDirectSound, nullptr);
if (SUCCEEDED (hr))
{
bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
totalBytesPerBuffer = (blocksPerOverallBuffer * bytesPerBuffer) & ~15;
const int numChannels = 2;
hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
JUCE_DS_LOG_ERROR (hr);
if (SUCCEEDED (hr))
{
IDirectSoundBuffer* pPrimaryBuffer;
DSBUFFERDESC primaryDesc = { 0 };
primaryDesc.dwSize = sizeof (DSBUFFERDESC);
primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
primaryDesc.dwBufferBytes = 0;
primaryDesc.lpwfxFormat = 0;
JUCE_DS_LOG ("co-op level set");
hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
JUCE_DS_LOG_ERROR (hr);
if (SUCCEEDED (hr))
{
WAVEFORMATEX wfFormat;
wfFormat.wFormatTag = WAVE_FORMAT_PCM;
wfFormat.nChannels = (unsigned short) numChannels;
wfFormat.nSamplesPerSec = (DWORD) sampleRate;
wfFormat.wBitsPerSample = (unsigned short) bitDepth;
wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
wfFormat.cbSize = 0;
hr = pPrimaryBuffer->SetFormat (&wfFormat);
JUCE_DS_LOG_ERROR (hr);
if (SUCCEEDED (hr))
{
DSBUFFERDESC secondaryDesc = { 0 };
secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
| 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
secondaryDesc.dwBufferBytes = (DWORD) totalBytesPerBuffer;
secondaryDesc.lpwfxFormat = &wfFormat;
hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
JUCE_DS_LOG_ERROR (hr);
if (SUCCEEDED (hr))
{
JUCE_DS_LOG ("buffer created");
DWORD dwDataLen;
unsigned char* pDSBuffData;
hr = pOutputBuffer->Lock (0, (DWORD) totalBytesPerBuffer,
(LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
JUCE_DS_LOG_ERROR (hr);
if (SUCCEEDED (hr))
{
zeromem (pDSBuffData, dwDataLen);
hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
if (SUCCEEDED (hr))
{
hr = pOutputBuffer->SetCurrentPosition (0);
if (SUCCEEDED (hr))
{
hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
if (SUCCEEDED (hr))
return String::empty;
}
}
}
}
}
}
}
}
error = DSoundLogging::getErrorMessage (hr);
close();
return error;
}
void synchronisePosition()
{
if (pOutputBuffer != nullptr)
{
DWORD playCursor;
pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
}
}
bool service()
{
if (pOutputBuffer == 0)
return true;
DWORD playCursor, writeCursor;
for (;;)
{
HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
{
pOutputBuffer->Restore();
continue;
}
if (SUCCEEDED (hr))
break;
JUCE_DS_LOG_ERROR (hr);
jassertfalse;
return true;
}
int playWriteGap = (int) (writeCursor - playCursor);
if (playWriteGap < 0)
playWriteGap += totalBytesPerBuffer;
int bytesEmpty = (int) (playCursor - writeOffset);
if (bytesEmpty < 0)
bytesEmpty += totalBytesPerBuffer;
if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
{
writeOffset = writeCursor;
bytesEmpty = totalBytesPerBuffer - playWriteGap;
}
if (bytesEmpty >= bytesPerBuffer)
{
int* buf1 = nullptr;
int* buf2 = nullptr;
DWORD dwSize1 = 0;
DWORD dwSize2 = 0;
HRESULT hr = pOutputBuffer->Lock (writeOffset, (DWORD) bytesPerBuffer,
(void**) &buf1, &dwSize1,
(void**) &buf2, &dwSize2, 0);
if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
{
pOutputBuffer->Restore();
hr = pOutputBuffer->Lock (writeOffset, (DWORD) bytesPerBuffer,
(void**) &buf1, &dwSize1,
(void**) &buf2, &dwSize2, 0);
}
if (SUCCEEDED (hr))
{
if (bitDepth == 16)
{
const float* left = leftBuffer;
const float* right = rightBuffer;
int samples1 = (int) (dwSize1 >> 2);
int samples2 = (int) (dwSize2 >> 2);
if (left == nullptr)
{
for (int* dest = buf1; --samples1 >= 0;) *dest++ = convertInputValues (0, *right++);
for (int* dest = buf2; --samples2 >= 0;) *dest++ = convertInputValues (0, *right++);
}
else if (right == nullptr)
{
for (int* dest = buf1; --samples1 >= 0;) *dest++ = convertInputValues (*left++, 0);
for (int* dest = buf2; --samples2 >= 0;) *dest++ = convertInputValues (*left++, 0);
}
else
{
for (int* dest = buf1; --samples1 >= 0;) *dest++ = convertInputValues (*left++, *right++);
for (int* dest = buf2; --samples2 >= 0;) *dest++ = convertInputValues (*left++, *right++);
}
}
else
{
jassertfalse;
}
writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
pOutputBuffer->Unlock (buf1, dwSize1, buf2, dwSize2);
}
else
{
jassertfalse;
JUCE_DS_LOG_ERROR (hr);
}
bytesEmpty -= bytesPerBuffer;
return true;
}
else
{
return false;
}
}
int bitDepth;
bool doneFlag;
private:
String name;
GUID guid;
int sampleRate, bufferSizeSamples;
float* leftBuffer;
float* rightBuffer;
IDirectSound* pDirectSound;
IDirectSoundBuffer* pOutputBuffer;
DWORD writeOffset;
int totalBytesPerBuffer, bytesPerBuffer;
unsigned int lastPlayCursor;
static inline int convertInputValues (const float l, const float r) noexcept
{
return jlimit (-32768, 32767, roundToInt (32767.0f * r)) << 16
| (0xffff & jlimit (-32768, 32767, roundToInt (32767.0f * l)));
}
JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel)
};
//==============================================================================
struct DSoundInternalInChannel
{
public:
DSoundInternalInChannel (const String& name_, const GUID& guid_, int rate,
int bufferSize, float* left, float* right)
: bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
pDirectSound (nullptr), pDirectSoundCapture (nullptr), pInputBuffer (nullptr)
{
}
~DSoundInternalInChannel()
{
close();
}
void close()
{
HRESULT hr;
if (pInputBuffer != nullptr)
{
JUCE_DS_LOG ("closing input: " + name);
hr = pInputBuffer->Stop();
JUCE_DS_LOG_ERROR (hr);
pInputBuffer->Release();
pInputBuffer = nullptr;
}
if (pDirectSoundCapture != nullptr)
{
pDirectSoundCapture->Release();
pDirectSoundCapture = nullptr;
}
if (pDirectSound != nullptr)
{
pDirectSound->Release();
pDirectSound = nullptr;
}
}
String open()
{
JUCE_DS_LOG ("opening input: " + name
+ " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
pDirectSound = nullptr;
pDirectSoundCapture = nullptr;
pInputBuffer = nullptr;
readOffset = 0;
totalBytesPerBuffer = 0;
HRESULT hr = dsDirectSoundCaptureCreate != nullptr
? dsDirectSoundCaptureCreate (&guid, &pDirectSoundCapture, nullptr)
: E_NOINTERFACE;
if (SUCCEEDED (hr))
{
const int numChannels = 2;
bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
totalBytesPerBuffer = (blocksPerOverallBuffer * bytesPerBuffer) & ~15;
WAVEFORMATEX wfFormat;
wfFormat.wFormatTag = WAVE_FORMAT_PCM;
wfFormat.nChannels = (unsigned short)numChannels;
wfFormat.nSamplesPerSec = (DWORD) sampleRate;
wfFormat.wBitsPerSample = (unsigned short) bitDepth;
wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
wfFormat.cbSize = 0;
DSCBUFFERDESC captureDesc = { 0 };
captureDesc.dwSize = sizeof (DSCBUFFERDESC);
captureDesc.dwFlags = 0;
captureDesc.dwBufferBytes = (DWORD) totalBytesPerBuffer;
captureDesc.lpwfxFormat = &wfFormat;
JUCE_DS_LOG ("object created");
hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
if (SUCCEEDED (hr))
{
hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
if (SUCCEEDED (hr))
return String::empty;
}
}
JUCE_DS_LOG_ERROR (hr);
const String error (DSoundLogging::getErrorMessage (hr));
close();
return error;
}
void synchronisePosition()
{
if (pInputBuffer != nullptr)
{
DWORD capturePos;
pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*) &readOffset);
}
}
bool service()
{
if (pInputBuffer == 0)
return true;
DWORD capturePos, readPos;
HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
JUCE_DS_LOG_ERROR (hr);
if (FAILED (hr))
return true;
int bytesFilled = (int) (readPos - readOffset);
if (bytesFilled < 0)
bytesFilled += totalBytesPerBuffer;
if (bytesFilled >= bytesPerBuffer)
{
short* buf1 = nullptr;
short* buf2 = nullptr;
DWORD dwsize1 = 0;
DWORD dwsize2 = 0;
HRESULT hr = pInputBuffer->Lock ((DWORD) readOffset, (DWORD) bytesPerBuffer,
(void**) &buf1, &dwsize1,
(void**) &buf2, &dwsize2, 0);
if (SUCCEEDED (hr))
{
if (bitDepth == 16)
{
const float g = 1.0f / 32768.0f;
float* destL = leftBuffer;
float* destR = rightBuffer;
int samples1 = (int) (dwsize1 >> 2);
int samples2 = (int) (dwsize2 >> 2);
if (destL == nullptr)
{
for (const short* src = buf1; --samples1 >= 0;) { ++src; *destR++ = *src++ * g; }
for (const short* src = buf2; --samples2 >= 0;) { ++src; *destR++ = *src++ * g; }
}
else if (destR == nullptr)
{
for (const short* src = buf1; --samples1 >= 0;) { *destL++ = *src++ * g; ++src; }
for (const short* src = buf2; --samples2 >= 0;) { *destL++ = *src++ * g; ++src; }
}
else
{
for (const short* src = buf1; --samples1 >= 0;) { *destL++ = *src++ * g; *destR++ = *src++ * g; }
for (const short* src = buf2; --samples2 >= 0;) { *destL++ = *src++ * g; *destR++ = *src++ * g; }
}
}
else
{
jassertfalse;
}
readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
pInputBuffer->Unlock (buf1, dwsize1, buf2, dwsize2);
}
else
{
JUCE_DS_LOG_ERROR (hr);
jassertfalse;
}
bytesFilled -= bytesPerBuffer;
return true;
}
else
{
return false;
}
}
unsigned int readOffset;
int bytesPerBuffer, totalBytesPerBuffer;
int bitDepth;
bool doneFlag;
private:
String name;
GUID guid;
int sampleRate, bufferSizeSamples;
float* leftBuffer;
float* rightBuffer;
IDirectSound* pDirectSound;
IDirectSoundCapture* pDirectSoundCapture;
IDirectSoundCaptureBuffer* pInputBuffer;
JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel)
};
//==============================================================================
class DSoundAudioIODevice : public AudioIODevice,
public Thread
{
public:
DSoundAudioIODevice (const String& deviceName,
const int outputDeviceIndex_,
const int inputDeviceIndex_)
: AudioIODevice (deviceName, "DirectSound"),
Thread ("Juce DSound"),
outputDeviceIndex (outputDeviceIndex_),
inputDeviceIndex (inputDeviceIndex_),
isOpen_ (false),
isStarted (false),
bufferSizeSamples (0),
sampleRate (0.0),
inputBuffers (1, 1),
outputBuffers (1, 1),
callback (nullptr)
{
if (outputDeviceIndex_ >= 0)
{
outChannels.add (TRANS("Left"));
outChannels.add (TRANS("Right"));
}
if (inputDeviceIndex_ >= 0)
{
inChannels.add (TRANS("Left"));
inChannels.add (TRANS("Right"));
}
}
~DSoundAudioIODevice()
{
close();
}
String open (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double sampleRate, int bufferSizeSamples)
{
lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
isOpen_ = lastError.isEmpty();
return lastError;
}
void close()
{
stop();
if (isOpen_)
{
closeDevice();
isOpen_ = false;
}
}
bool isOpen() { return isOpen_ && isThreadRunning(); }
int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
double getCurrentSampleRate() { return sampleRate; }
BigInteger getActiveOutputChannels() const { return enabledOutputs; }
BigInteger getActiveInputChannels() const { return enabledInputs; }
int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
StringArray getOutputChannelNames() { return outChannels; }
StringArray getInputChannelNames() { return inChannels; }
int getNumSampleRates() { return 4; }
int getDefaultBufferSize() { return 2560; }
int getNumBufferSizesAvailable() { return 50; }
double getSampleRate (int index)
{
const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
return samps [jlimit (0, 3, index)];
}
int getBufferSizeSamples (int index)
{
int n = 64;
for (int i = 0; i < index; ++i)
n += (n < 512) ? 32
: ((n < 1024) ? 64
: ((n < 2048) ? 128 : 256));
return n;
}
int getCurrentBitDepth()
{
int bits = 256;
for (int i = inChans.size(); --i >= 0;)
bits = jmin (bits, inChans[i]->bitDepth);
for (int i = outChans.size(); --i >= 0;)
bits = jmin (bits, outChans[i]->bitDepth);
if (bits > 32)
bits = 16;
return bits;
}
void start (AudioIODeviceCallback* call)
{
if (isOpen_ && call != nullptr && ! isStarted)
{
if (! isThreadRunning())
{
// something gone wrong and the thread's stopped..
isOpen_ = false;
return;
}
call->audioDeviceAboutToStart (this);
const ScopedLock sl (startStopLock);
callback = call;
isStarted = true;
}
}
void stop()
{
if (isStarted)
{
AudioIODeviceCallback* const callbackLocal = callback;
{
const ScopedLock sl (startStopLock);
isStarted = false;
}
if (callbackLocal != nullptr)
callbackLocal->audioDeviceStopped();
}
}
bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
String getLastError() { return lastError; }
//==============================================================================
StringArray inChannels, outChannels;
int outputDeviceIndex, inputDeviceIndex;
private:
bool isOpen_;
bool isStarted;
String lastError;
OwnedArray <DSoundInternalInChannel> inChans;
OwnedArray <DSoundInternalOutChannel> outChans;
WaitableEvent startEvent;
int bufferSizeSamples;
double sampleRate;
BigInteger enabledInputs, enabledOutputs;
AudioSampleBuffer inputBuffers, outputBuffers;
AudioIODeviceCallback* callback;
CriticalSection startStopLock;
String openDevice (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double sampleRate_, int bufferSizeSamples_);
void closeDevice()
{
isStarted = false;
stopThread (5000);
inChans.clear();
outChans.clear();
inputBuffers.setSize (1, 1);
outputBuffers.setSize (1, 1);
}
void resync()
{
if (! threadShouldExit())
{
sleep (5);
for (int i = 0; i < outChans.size(); ++i)
outChans.getUnchecked(i)->synchronisePosition();
for (int i = 0; i < inChans.size(); ++i)
inChans.getUnchecked(i)->synchronisePosition();
}
}
public:
void run()
{
while (! threadShouldExit())
{
if (wait (100))
break;
}
const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
const int maxTimeMS = jmax (5, 3 * latencyMs);
while (! threadShouldExit())
{
int numToDo = 0;
uint32 startTime = Time::getMillisecondCounter();
for (int i = inChans.size(); --i >= 0;)
{
inChans.getUnchecked(i)->doneFlag = false;
++numToDo;
}
for (int i = outChans.size(); --i >= 0;)
{
outChans.getUnchecked(i)->doneFlag = false;
++numToDo;
}
if (numToDo > 0)
{
const int maxCount = 3;
int count = maxCount;
for (;;)
{
for (int i = inChans.size(); --i >= 0;)
{
DSoundInternalInChannel* const in = inChans.getUnchecked(i);
if ((! in->doneFlag) && in->service())
{
in->doneFlag = true;
--numToDo;
}
}
for (int i = outChans.size(); --i >= 0;)
{
DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
if ((! out->doneFlag) && out->service())
{
out->doneFlag = true;
--numToDo;
}
}
if (numToDo <= 0)
break;
if (Time::getMillisecondCounter() > startTime + maxTimeMS)
{
resync();
break;
}
if (--count <= 0)
{
Sleep (1);
count = maxCount;
}
if (threadShouldExit())
return;
}
}
else
{
sleep (1);
}
const ScopedLock sl (startStopLock);
if (isStarted)
{
callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
inputBuffers.getNumChannels(),
outputBuffers.getArrayOfChannels(),
outputBuffers.getNumChannels(),
bufferSizeSamples);
}
else
{
outputBuffers.clear();
sleep (1);
}
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice)
};
//==============================================================================
struct DSoundDeviceList
{
StringArray outputDeviceNames, inputDeviceNames;
Array<GUID> outputGuids, inputGuids;
void scan()
{
outputDeviceNames.clear();
inputDeviceNames.clear();
outputGuids.clear();
inputGuids.clear();
if (dsDirectSoundEnumerateW != 0)
{
dsDirectSoundEnumerateW (outputEnumProcW, this);
dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
}
}
bool operator!= (const DSoundDeviceList& other) const noexcept
{
return outputDeviceNames != other.outputDeviceNames
|| inputDeviceNames != other.inputDeviceNames
|| outputGuids != other.outputGuids
|| inputGuids != other.inputGuids;
}
private:
static BOOL enumProc (LPGUID lpGUID, String desc, StringArray& names, Array<GUID>& guids)
{
desc = desc.trim();
if (desc.isNotEmpty())
{
const String origDesc (desc);
int n = 2;
while (names.contains (desc))
desc = origDesc + " (" + String (n++) + ")";
names.add (desc);
guids.add (lpGUID != nullptr ? *lpGUID : GUID());
}
return TRUE;
}
BOOL outputEnumProc (LPGUID guid, LPCWSTR desc) { return enumProc (guid, desc, outputDeviceNames, outputGuids); }
BOOL inputEnumProc (LPGUID guid, LPCWSTR desc) { return enumProc (guid, desc, inputDeviceNames, inputGuids); }
static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
{
return static_cast<DSoundDeviceList*> (object)->outputEnumProc (lpGUID, description);
}
static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
{
return static_cast<DSoundDeviceList*> (object)->inputEnumProc (lpGUID, description);
}
};
//==============================================================================
String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double sampleRate_, int bufferSizeSamples_)
{
closeDevice();
sampleRate = sampleRate_;
if (bufferSizeSamples_ <= 0)
bufferSizeSamples_ = 960; // use as a default size if none is set.
bufferSizeSamples = bufferSizeSamples_ & ~7;
DSoundDeviceList dlh;
dlh.scan();
enabledInputs = inputChannels;
enabledInputs.setRange (inChannels.size(),
enabledInputs.getHighestBit() + 1 - inChannels.size(),
false);
inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
inputBuffers.clear();
int numIns = 0;
for (int i = 0; i <= enabledInputs.getHighestBit(); i += 2)
{
float* left = nullptr;
if (enabledInputs[i])
left = inputBuffers.getSampleData (numIns++);
float* right = nullptr;
if (enabledInputs[i + 1])
right = inputBuffers.getSampleData (numIns++);
if (left != nullptr || right != nullptr)
inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
dlh.inputGuids [inputDeviceIndex],
(int) sampleRate, bufferSizeSamples,
left, right));
}
enabledOutputs = outputChannels;
enabledOutputs.setRange (outChannels.size(),
enabledOutputs.getHighestBit() + 1 - outChannels.size(),
false);
outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
outputBuffers.clear();
int numOuts = 0;
for (int i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
{
float* left = nullptr;
if (enabledOutputs[i])
left = outputBuffers.getSampleData (numOuts++);
float* right = nullptr;
if (enabledOutputs[i + 1])
right = outputBuffers.getSampleData (numOuts++);
if (left != nullptr || right != nullptr)
outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
dlh.outputGuids [outputDeviceIndex],
(int) sampleRate, bufferSizeSamples,
left, right));
}
String error;
// boost our priority while opening the devices to try to get better sync between them
const int oldThreadPri = GetThreadPriority (GetCurrentThread());
const DWORD oldProcPri = GetPriorityClass (GetCurrentProcess());
SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
for (int i = 0; i < outChans.size(); ++i)
{
error = outChans[i]->open();
if (error.isNotEmpty())
{
error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
break;
}
}
if (error.isEmpty())
{
for (int i = 0; i < inChans.size(); ++i)
{
error = inChans[i]->open();
if (error.isNotEmpty())
{
error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
break;
}
}
}
if (error.isEmpty())
{
for (int i = 0; i < outChans.size(); ++i)
outChans.getUnchecked(i)->synchronisePosition();
for (int i = 0; i < inChans.size(); ++i)
inChans.getUnchecked(i)->synchronisePosition();
startThread (9);
sleep (10);
notify();
}
else
{
JUCE_DS_LOG ("Opening failed: " + error);
}
SetThreadPriority (GetCurrentThread(), oldThreadPri);
SetPriorityClass (GetCurrentProcess(), oldProcPri);
return error;
}
//==============================================================================
class DSoundAudioIODeviceType : public AudioIODeviceType,
private DeviceChangeDetector
{
public:
DSoundAudioIODeviceType()
: AudioIODeviceType ("DirectSound"),
DeviceChangeDetector (L"DirectSound"),
hasScanned (false)
{
initialiseDSoundFunctions();
}
void scanForDevices()
{
hasScanned = true;
deviceList.scan();
}
StringArray getDeviceNames (bool wantInputNames) const
{
jassert (hasScanned); // need to call scanForDevices() before doing this
return wantInputNames ? deviceList.inputDeviceNames
: deviceList.outputDeviceNames;
}
int getDefaultDeviceIndex (bool /*forInput*/) const
{
jassert (hasScanned); // need to call scanForDevices() before doing this
return 0;
}
int getIndexOfDevice (AudioIODevice* device, bool asInput) const
{
jassert (hasScanned); // need to call scanForDevices() before doing this
if (DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device))
return asInput ? d->inputDeviceIndex
: d->outputDeviceIndex;
return -1;
}
bool hasSeparateInputsAndOutputs() const { return true; }
AudioIODevice* createDevice (const String& outputDeviceName,
const String& inputDeviceName)
{
jassert (hasScanned); // need to call scanForDevices() before doing this
const int outputIndex = deviceList.outputDeviceNames.indexOf (outputDeviceName);
const int inputIndex = deviceList.inputDeviceNames.indexOf (inputDeviceName);
if (outputIndex >= 0 || inputIndex >= 0)
return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
: inputDeviceName,
outputIndex, inputIndex);
return nullptr;
}
private:
DSoundDeviceList deviceList;
bool hasScanned;
void systemDeviceChanged()
{
DSoundDeviceList newList;
newList.scan();
if (newList != deviceList)
{
deviceList = newList;
callDeviceChangeListeners();
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType)
};
//==============================================================================
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound()
{
return new DSoundAudioIODeviceType();
}
| [
"nik.reiman@gmail.com"
] | nik.reiman@gmail.com |
afc1b0400c1b9709c20ed90028893f11d73b7c92 | 17e6ece2271f386f87a4dbd6a70f74d5f3ed2e71 | /2339.cpp | 07b5bb3a85580d480532362cddb501b6dc4e2fef | [] | no_license | equation9/BOJ | d5e101eb995b7ef10c7115e5a15992a99a2cbaa0 | 8e1e23de5fed36e0487aff46469cb27d31af7818 | refs/heads/master | 2021-01-23T07:44:51.018792 | 2019-01-09T07:43:21 | 2019-01-09T07:43:21 | 86,442,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | cpp | /*2339번 석판 자르기(C++11)*/
#include <iostream>
#include <set>
using namespace std;
int N, Slate[21][21];
int DQ(int sy, int sx, int dy, int dx, int flag)
{
if(sy == dy || sx == dx) return 0;
int i, j;
int res = 0;
set<int> yp, xp;
int df=0, cr=0; //불순물, 결정
for(i = sy; i < dy ; i++){
for(j = sx; j < dx; j++){
if(Slate[i][j] == 1){
df++;
yp.insert(i);
xp.insert(j);
}
else if(Slate[i][j] == 2)
cr++;
}
}
if(cr == 0) return 0;
if(cr == 1) return !df;
if(df == 0 ) return 0;
if(flag != 1)
{
for(int x : xp){
bool possible = true;
for(i = sy; i < dy; i++){
if(Slate[i][x] == 2){
possible = false;
break;
}
}
if(possible)
res += DQ(sy, sx, dy, x, 1) * DQ(sy,x+1, dy, dx, 1);
}
}
if(flag != 2)
{
for(int y : yp){
bool possible = true;
for(i = sx; i < dx; i++){
if(Slate[y][i] == 2){
possible = false;
break;
}
}
if(possible)
res += DQ(sy, sx, y, dx, 2) * DQ(y+1, sx, dy, dx, 2);
}
}
return res;
}
int main()
{
ios::sync_with_stdio(false);
int i, j, res=0;
int df = 0, cr = 0;
cin>>N;
for(i = 0; i < N; i++){
for(j = 0; j < N; j++){
cin>>Slate[i][j];
if(Slate[i][j] == 1) df++;
else if(Slate[i][j] == 2) cr++;
}
}
res = DQ(0, 0, N, N, 0);
if(!res) res = -1;
cout<< res <<endl;
return 0;
}
| [
"equation9@naver.com"
] | equation9@naver.com |
50ee79a28be2524df3aec59d3c94affff9a54f54 | a90684b91351b4a3bf982e3232c3a45ba394bce5 | /Template/Config.h | b7c18d972b0de625c596050b3b58eca8c71f012e | [] | no_license | woonhak-kong/GameFundamental2Assignment2 | 5a991472dd1c78ae84754377b3b0482cef031ab5 | f259f7196fcf00fc500fa448b4e51230e60469c8 | refs/heads/master | 2023-07-14T10:12:34.689779 | 2021-08-15T23:53:30 | 2021-08-15T23:53:30 | 393,162,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,331 | h | #pragma once
#ifndef __CONFIG__
#define __CONFIG__
#include <SDL_ttf.h>
#include <memory>
#include <string>
#include "glm/vec2.hpp"
class Config {
public:
static const int SCREEN_WIDTH = 1280;
static const int SCREEN_HEIGHT = 720;
static const int ROW_NUM = 15;
static const int COL_NUM = 20;
static const int TILE_SIZE = 40;
static const int TILE_COST = 1;
static const int MINE_NUM = 50;
static const int SCORE = 0;
static const int LIVES = 5;
static const int GRAVITY = 5.0f;
inline static bool SHOWING_DEBUG = false;
inline static bool GAME_OVER = false;
inline static float TIME_SCORE = 0;
inline static int mapWidth = 0;
inline static int mapHeight = 0;
// about texture
inline static const std::string TEXTURE_LOCATION = "assets/state.xml";
inline static const std::string SCENE0_LOCATION = "assets/maps/scene0.tmx";
inline static const std::string SCENE1_LOCATION = "assets/maps/scene1.tmx";
inline static const std::string TUTORIAL_SCENE = "TUTORIALSCENE";
inline static const std::string START_SCENE = "STARTSCENE";
inline static const std::string END_SCENE = "ENDSCENE";
inline static const std::string PLAY_SCENE1 = "PLAYSCENE1";
inline static const std::string PLAY_SCENE2 = "PLAYSCENE2";
inline static const std::string PLAY_SCENE3 = "PLAYSCENE3";
};
#endif /* defined (__CONFIG__) */ | [
"woonhak.kong@georgebrown.ca"
] | woonhak.kong@georgebrown.ca |
c20073a2dd9ed1da5db5334f2021d6ba62224f41 | fae551eb54ab3a907ba13cf38aba1db288708d92 | /chrome/browser/infobars/simple_alert_infobar_creator.cc | 89ee7655ceb006c3656f794037e50b920488c41d | [
"BSD-3-Clause"
] | permissive | xtblock/chromium | d4506722fc6e4c9bc04b54921a4382165d875f9a | 5fe0705b86e692c65684cdb067d9b452cc5f063f | refs/heads/main | 2023-04-26T18:34:42.207215 | 2021-05-27T04:45:24 | 2021-05-27T04:45:24 | 371,258,442 | 2 | 1 | BSD-3-Clause | 2021-05-27T05:36:28 | 2021-05-27T05:36:28 | null | UTF-8 | C++ | false | false | 1,023 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/infobars/simple_alert_infobar_creator.h"
#include <memory>
#include "chrome/browser/infobars/confirm_infobar_creator.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar.h"
#include "components/infobars/core/simple_alert_infobar_delegate.h"
#include "third_party/skia/include/core/SkBitmap.h"
void CreateSimpleAlertInfoBar(
infobars::ContentInfoBarManager* infobar_manager,
infobars::InfoBarDelegate::InfoBarIdentifier infobar_identifier,
const gfx::VectorIcon* vector_icon,
const std::u16string& message,
bool auto_expire,
bool should_animate) {
infobar_manager->AddInfoBar(
CreateConfirmInfoBar(std::make_unique<SimpleAlertInfoBarDelegate>(
infobar_identifier, vector_icon, message, auto_expire,
should_animate)));
}
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
99fef69d38ab4fdf6dffab93fb3a4ada0c8732b2 | 818f062da25c6070f7d4974c980044473df7f053 | /c++/leftrotate.cpp | 4368fda6572c162619e5004920bc65d6e233db29 | [] | no_license | srivarshan12/Cplusplus | 141644e471c858e07c1330a1a4a925affe1c3c25 | f12a4401e2371960a50194104ca73af9f5d1136b | refs/heads/master | 2023-08-25T06:59:46.188466 | 2021-10-19T07:50:40 | 2021-10-19T07:50:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int arr[]={1,2,3,4,5,6,7};
int n=sizeof(arr)/sizeof(arr[0]);
int temp[n];
int ls=n-2,j=0;
for(int i=ls;i<n;i++)
{
temp[j++]=arr[i];
}
for(int i=0;i<ls;i++)
{
temp[j++]=arr[i];
}
for(int i=0;i<n;i++)
{
cout<<temp[i];
}
}
| [
"varshan1206@gmail.com"
] | varshan1206@gmail.com |
b1a1a0d5239d7fcc6e4770efc5e6a22a35e6c296 | 56e694eccce264be2d6b789bccaac4cf5326be8e | /data/th2dplot.cc | 9fa9b346e82f09a40ecf48e4061c0a934495b8de | [] | no_license | kanouyou/CometQuenchCode- | cddb56b6d6017435afa3183f2ff6d834395c448c | aaa2cb3af3da776eac04be39a537ae51b1beae1d | refs/heads/master | 2020-05-21T16:27:35.639423 | 2017-04-07T09:07:35 | 2017-04-07T09:07:35 | 64,641,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,665 | cc | TH2F* Load(const char* filename, const int phi, const int opt, const bool reverse=false)
{
std::ifstream file(filename);
if (!file) {
std::cerr << "Error: file did not exist!" << std::endl;
return NULL;
}
const char* name = Form("CS1-%i-p%i", opt, phi);
double zmin = 0.;
double zmax = 5.;
int nz = 5;
double rmin = 0.;
double rmax = 9.;
int nr = 9;
int ibuff[3];
double dbuff[3];
TH2F* hist = new TH2F(name, name, nz, zmin, zmax, nr, rmin, rmax);
double min = 9999.;
double max = -9999.;
while (true) {
file >> ibuff[0] >> ibuff[1] >> ibuff[2] >> dbuff[0] >> dbuff[1] >> dbuff[2];
dbuff[0] /= 3600.*24*365;
if (!file) break;
if (ibuff[1]==phi) {
if (reverse==false)
hist->Fill(ibuff[0]+0.5, ibuff[2]+0.5, dbuff[opt]);
else
hist->Fill(ibuff[0]+0.5, (rmax-1-ibuff[2])+0.5, dbuff[opt]);
}
if (dbuff[opt]>max) max = dbuff[opt];
if (dbuff[opt]<min) min = dbuff[opt];
}
// opt==0: flux
if (opt==0)
hist->SetTitle(Form("#phi = %i; Z; R; Neutron Flux [n/m^{2}/sec]", phi+1));
// opt==1: heat
if (opt==1)
hist->SetTitle(Form("#phi = %i; Z; R; Energy Deposit [Gy/sec]", phi+1));
hist->GetZaxis()->SetRangeUser(0., max);
std::cout << "=========================" << std::endl;
std::cout << " min.: " << min << std::endl;
std::cout << " max.: " << max << std::endl;
std::cout << "=========================" << std::endl;
return hist;
}
TH2F* LoadCS0(const char* filename, const int opt)
{
std::ifstream file(filename);
if (!file) {
std::cerr << "Error: file did not exist!" << std::endl;
return NULL;
}
const char* name = Form("CS0-%i", opt);
double pmin = 0.;
double pmax = 4.;
int np = 4;
double rmin = 0.;
double rmax = 9.;
int nr = 9;
int ibuff[3];
double dbuff[3];
TH2F* hist = new TH2F(name, name, np, pmin, pmax, nr, rmin, rmax);
int swap = 0;
double min = 1e+100;
double max = -9999.;
while (true) {
file >> ibuff[0] >> ibuff[1] >> ibuff[2] >> dbuff[0] >> dbuff[1] >> dbuff[2];
if (!file) break;
dbuff[0] /= 3600.*24*365;
if (ibuff[1]==0)
swap = 1;
else if (ibuff[1]==1)
swap = 0;
else
swap = ibuff[1];
//ibuff[1] = swap;
//hist->Fill(ibuff[1]+0.5, (rmax-1-ibuff[2])+0.5, dbuff[opt]);
hist->Fill(ibuff[1]+0.5, ibuff[2]+0.5, dbuff[opt]);
if (dbuff[opt]>max) max = dbuff[opt];
if (dbuff[opt]<min) min = dbuff[opt];
}
// opt==0: flux
if (opt==0)
hist->SetTitle("; #phi; R; Neutron Flux [n/m^{2}/sec]");
// opt==1: heat
if (opt==1)
hist->SetTitle("; $phi; R; Energy Deposit [Gy/sec]");
std::cout << " minimum: " << min << std::endl;
std::cout << " maximum: " << max << std::endl;
return hist;
}
void th2dplot()
{
/*
TCanvas* c0 = new TCanvas("c0", "c0", 550., 400.);
c0->SetTicks(1,1);
c0->SetRightMargin(0.16);
gStyle->SetOptStat(0);
gStyle->SetTitleOffset(1.2, "z");
TH2F* hist = LoadCS0("./161019CS0.dat", 1);
hist->Draw("colz");
*/
TCanvas* c0 = new TCanvas("c0", "c0", 740., 450.);
c0->Divide(2,2);
gStyle->SetOptStat(0);
gStyle->SetTitleOffset(1.2, "z");
for (int i=0; i<4; i++) {
c0->cd(i+1);
gPad->SetTicks(1,1);
gPad->SetRightMargin(0.16);
TH2F* hist = Load("./phits288/161029CS1Kerma.dat",i,1);
//TH2F* hist = Load("./rad_phits.dat",i,1,true);
hist->Draw("colz");
}
}
| [
"kanouyou@kune2a.nucl.kyushu-u.ac.jp"
] | kanouyou@kune2a.nucl.kyushu-u.ac.jp |
6fe3be234adfd1e917385ef30bc639745f1b66bb | b2e169503e1661d6f5d9c8095b289c5e1565f6ed | /sugarchainmininglibrary/src/main/cpp/HelloWorld.cpp | 4f0cf8866f857fcf747858b4b1b9160dd45251b9 | [
"BSD-3-Clause"
] | permissive | decryp2kanon/Sugarchain-Android-Miner | 6680a90bf593c187b5dd638be5f5f7883ce15632 | 87f55a951fc1994504ac14f067631586fb0f52c2 | refs/heads/master | 2022-05-21T09:54:49.123471 | 2020-03-26T02:37:14 | 2020-03-26T02:37:14 | 250,142,913 | 0 | 0 | null | 2020-03-26T02:35:13 | 2020-03-26T02:35:13 | null | UTF-8 | C++ | false | false | 236 | cpp | //
// Created by salma on 2/25/2020.
//
#include <iostream>
using namespace std;
int addition(int a, int b) {
int r;
r=a+b;
return r;
}
int main() {
int x;
x = addition(5, 3);
cout << "The result is " << x;
} | [
"52128634+Nugetzrul3@users.noreply.github.com"
] | 52128634+Nugetzrul3@users.noreply.github.com |
1d506ba2124b820ceffbc5ff335e8cdcf7a0c686 | f5d87ed79a91f17cdf2aee7bea7c15f5b5258c05 | /cuts/iccm/arch/coredx/compiler/Upcall_Event.cpp | 8134d4befd19c7b81444868842dbf6a784840499 | [] | no_license | SEDS/CUTS | a4449214a894e2b47bdea42090fa6cfc56befac8 | 0ad462fadcd3adefd91735aef6d87952022db2b7 | refs/heads/master | 2020-04-06T06:57:35.710601 | 2016-08-16T19:37:34 | 2016-08-16T19:37:34 | 25,653,522 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,252 | cpp | // $Id$
#include "Upcall_Event.h"
#include "be_extern.h"
#include "be_global.h"
#include "ast_eventtype.h"
#include "ast_field.h"
#include "ast_module.h"
#include "utl_identifier.h"
#include <iostream>
namespace iCCM
{
//
// Upcall_Event
//
Upcall_Event::Upcall_Event (std::ofstream & hfile, std::ofstream & sfile)
: hfile_ (hfile),
sfile_ (sfile)
{
}
//
// ~Upcall_Event
//
Upcall_Event::~Upcall_Event (void)
{
}
//
// visit_module
//
int Upcall_Event::visit_module (AST_Module * node)
{
ACE_CString local_name (node->local_name ()->get_string ());
ACE_CString backup (this->marshal_scope_);
this->marshal_scope_ += local_name + "_";
if (0 != this->visit_scope (node))
return -1;
this->marshal_scope_ = backup;
return 0;
}
//
// visit_eventtype
//
int Upcall_Event::visit_eventtype (AST_EventType * node)
{
if (!be_global->is_wrapper_eventtype (node))
return 0;
const char * local_name = node->local_name ()->get_string ();
const char * full_name = node->full_name ();
this->upcall_event_ = ACE_CString (local_name) + "Upcall";
ACE_CString dds_event;
be_global->get_wrapper_eventtype (node, dds_event);
this->hfile_
<< "class ";
if (!be_global->stub_export_macro_.empty ())
this->hfile_ << be_global->stub_export_macro_ << " ";
this->hfile_
<< this->upcall_event_ << " :" << std::endl
<< " public virtual " << local_name << "," << std::endl
<< " public virtual ::CORBA::DefaultValueRefCountBase" << std::endl
<< "{"
<< "public:" << std::endl
<< this->upcall_event_ << " (CoreDX::" << dds_event << " & dds_event);"
<< "virtual ~" << this->upcall_event_ << " (void);"
<< std::endl;
this->sfile_
<< this->upcall_event_ << "::" << this->upcall_event_ << " (CoreDX::" << dds_event << " & dds_event)" << std::endl
<< ": dds_event_ (dds_event)"
<< "{"
<< "}"
<< this->upcall_event_ << "::~" << this->upcall_event_ << " (void)"
<< "{"
<< "}";
this->visit_scope (node);
this->hfile_
<< "private:" << std::endl
<< "CoreDX::" << dds_event << " & dds_event_;"
<< std::endl
<< "::CORBA::Boolean _tao_marshal__" << this->marshal_scope_ << local_name << " (TAO_OutputCDR &, TAO_ChunkInfo &) const;"
<< "::CORBA::Boolean _tao_unmarshal__" << this->marshal_scope_ << local_name << " (TAO_InputCDR &, TAO_ChunkInfo &);"
<< "};";
this->sfile_
<< "::CORBA::Boolean " << this->upcall_event_
<< "::_tao_marshal__" << this->marshal_scope_ << local_name << " (TAO_OutputCDR &, TAO_ChunkInfo &) const{return false;}"
<< "::CORBA::Boolean " << this->upcall_event_
<< "::_tao_unmarshal__" << this->marshal_scope_ << local_name << " (TAO_InputCDR &, TAO_ChunkInfo &){return false;}";
return 0;
}
//
// visit_attribute
//
int Upcall_Event::visit_field (AST_Field * node)
{
AST_Type * field_type = node->field_type ();
const char * local_name = node->local_name ()->get_string ();
const char * param_type = field_type->full_name ();
switch (field_type->node_type ())
{
case AST_Decl::NT_pre_defined:
this->hfile_
<< "virtual void " << local_name << " (const ::" << param_type << ");"
<< "virtual " << param_type << " " << local_name << " (void) const;"
<< std::endl;
this->sfile_
<< "void " << this->upcall_event_ << "::"
<< local_name << " (const ::" << param_type << " val){"
<< "this->dds_event_." << local_name << " = val;"
<< "}"
<< param_type << " " << this->upcall_event_ << "::"
<< local_name << " (void) const{"
<< "return this->dds_event_." << local_name << ";"
<< "}";
break;
case AST_Decl::NT_enum:
this->hfile_
<< "virtual void " << local_name << " (const ::" << param_type << ");"
<< "virtual " << param_type << " " << local_name << " (void) const;"
<< std::endl;
this->sfile_
<< "void " << this->upcall_event_ << "::"
<< local_name << " (const ::" << param_type << " val){"
<< "this->dds_event_." << local_name << " = val;"
<< "}"
<< param_type << " " << this->upcall_event_ << "::"
<< local_name << " (void) const{"
<< "return this->dds_event_." << local_name << ";"
<< "}";
break;
case AST_Decl::NT_string:
this->hfile_
<< "virtual void " << local_name << " (" << param_type << ");"
<< "virtual void " << local_name << " (const " << param_type << ");"
<< "virtual void " << local_name << " (const ::CORBA::String_var &);"
<< "virtual const " << param_type << " " << local_name << " (void) const;"
<< std::endl;
this->sfile_
<< "void " << this->upcall_event_
<< "::" << local_name << " (" << param_type << " val){"
<< "this->dds_event_." << local_name << " = val;"
<< "}"
<< "void " << this->upcall_event_
<< "::" << local_name << " (const " << param_type << " val){"
<< "this->dds_event_." << local_name << " = CORBA::string_dup (val);"
<< "}"
<< "void " << this->upcall_event_
<< "::" << local_name << " (const ::CORBA::String_var & val){"
<< "::CORBA::String_var dup = val;"
<< "this->dds_event_." << local_name << " = dup._retn ();"
<< "}"
<< "const " << param_type << " " << this->upcall_event_
<< "::" << local_name << " (void) const {"
<< "return this->dds_event_." << local_name << ";"
<< "}";
break;
default:
this->hfile_
<< "virtual void " << local_name << " (const ::" << param_type << " &);"
<< "virtual const " << param_type << " & " << local_name << " (void) const;"
<< "virtual " << param_type << " & " << local_name << " (void);"
<< std::endl;
this->sfile_
<< "void " << this->upcall_event_
<< "::" << local_name << " (const ::" << param_type << " & val){"
<< "this->dds_event_." << local_name << " = val;"
<< "}"
<< "const " << param_type << " & "
<< this->upcall_event_ << "::" << local_name << " (void) const{"
<< "return this->dds_event_." << local_name << ";"
<< "}"
<< param_type << " & " << this->upcall_event_
<< "::" << local_name << " (void){"
<< "return this->dds_event_." << local_name << ";"
<< "}";
}
return 0;
}
}
| [
"dfeiock@iupui.edu"
] | dfeiock@iupui.edu |
2ac225385db6f273d4dfea0c53e417b75b9625fa | 2aec493c279a0e386131ca1029a64d2dc32086e1 | /src/test/denialofservice_tests.cpp | a14d8bbc607b91babb686a515994f2041b4ede2e | [
"MIT"
] | permissive | mixcan/DNX | fac6daac0f1117242c3cf38cb562749ed1f26344 | fcb35560c9b636141eb613a58ae32225f91e0b37 | refs/heads/main | 2023-02-11T10:42:04.855972 | 2021-01-17T10:47:30 | 2021-01-17T10:47:30 | 330,035,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,291 | cpp | // Copyright (c) 2011-2020 The Dnxcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for denial-of-service detection/prevention code
#include <arith_uint256.h>
#include <banman.h>
#include <chainparams.h>
#include <net.h>
#include <net_processing.h>
#include <pubkey.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <serialize.h>
#include <util/memory.h>
#include <util/string.h>
#include <util/system.h>
#include <util/time.h>
#include <validation.h>
#include <test/util/setup_common.h>
#include <stdint.h>
#include <boost/test/unit_test.hpp>
struct CConnmanTest : public CConnman {
using CConnman::CConnman;
void AddNode(CNode& node)
{
LOCK(cs_vNodes);
vNodes.push_back(&node);
}
void ClearNodes()
{
LOCK(cs_vNodes);
for (CNode* node : vNodes) {
delete node;
}
vNodes.clear();
}
};
// Tests these internal-to-net_processing.cpp methods:
extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer);
extern void EraseOrphansFor(NodeId peer);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
struct COrphanTx {
CTransactionRef tx;
NodeId fromPeer;
int64_t nTimeExpire;
};
extern std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans);
static CService ip(uint32_t i)
{
struct in_addr s;
s.s_addr = i;
return CService(CNetAddr(s), Params().GetDefaultPort());
}
static NodeId id = 0;
void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds);
BOOST_FIXTURE_TEST_SUITE(denialofservice_tests, TestingSetup)
// Test eviction of an outbound peer whose chain never advances
// Mock a node connection, and use mocktime to simulate a peer
// which never sends any headers messages. PeerLogic should
// decide to evict that outbound peer, after the appropriate timeouts.
// Note that we protect 4 outbound nodes from being subject to
// this logic; this test takes advantage of that protection only
// being applied to nodes which send headers with sufficient
// work.
BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
{
const CChainParams& chainparams = Params();
auto connman = MakeUnique<CConnman>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerManager>(chainparams, *connman, nullptr, *m_node.scheduler, *m_node.chainman, *m_node.mempool);
// Mock an outbound peer
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, ServiceFlags(NODE_NETWORK | NODE_WITNESS), 0, INVALID_SOCKET, addr1, 0, 0, CAddress(), "", ConnectionType::OUTBOUND_FULL_RELAY);
dummyNode1.SetCommonVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(&dummyNode1);
dummyNode1.fSuccessfullyConnected = true;
// This test requires that we have a chain with non-zero work.
{
LOCK(cs_main);
BOOST_CHECK(::ChainActive().Tip() != nullptr);
BOOST_CHECK(::ChainActive().Tip()->nChainWork > 0);
}
// Test starts here
{
LOCK(dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(&dummyNode1)); // should result in getheaders
}
{
LOCK(dummyNode1.cs_vSend);
BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
dummyNode1.vSendMsg.clear();
}
int64_t nStartTime = GetTime();
// Wait 21 minutes
SetMockTime(nStartTime+21*60);
{
LOCK(dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(&dummyNode1)); // should result in getheaders
}
{
LOCK(dummyNode1.cs_vSend);
BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
}
// Wait 3 more minutes
SetMockTime(nStartTime+24*60);
{
LOCK(dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(&dummyNode1)); // should result in disconnect
}
BOOST_CHECK(dummyNode1.fDisconnect == true);
SetMockTime(0);
bool dummy;
peerLogic->FinalizeNode(dummyNode1, dummy);
}
static void AddRandomOutboundPeer(std::vector<CNode *> &vNodes, PeerManager &peerLogic, CConnmanTest* connman)
{
CAddress addr(ip(g_insecure_rand_ctx.randbits(32)), NODE_NONE);
vNodes.emplace_back(new CNode(id++, ServiceFlags(NODE_NETWORK | NODE_WITNESS), 0, INVALID_SOCKET, addr, 0, 0, CAddress(), "", ConnectionType::OUTBOUND_FULL_RELAY));
CNode &node = *vNodes.back();
node.SetCommonVersion(PROTOCOL_VERSION);
peerLogic.InitializeNode(&node);
node.fSuccessfullyConnected = true;
connman->AddNode(node);
}
BOOST_AUTO_TEST_CASE(stale_tip_peer_management)
{
const CChainParams& chainparams = Params();
auto connman = MakeUnique<CConnmanTest>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerManager>(chainparams, *connman, nullptr, *m_node.scheduler, *m_node.chainman, *m_node.mempool);
constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS;
CConnman::Options options;
options.nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS;
options.m_max_outbound_full_relay = max_outbound_full_relay;
options.nMaxFeeler = MAX_FEELER_CONNECTIONS;
connman->Init(options);
std::vector<CNode *> vNodes;
// Mock some outbound peers
for (int i=0; i<max_outbound_full_relay; ++i) {
AddRandomOutboundPeer(vNodes, *peerLogic, connman.get());
}
peerLogic->CheckForStaleTipAndEvictPeers();
// No nodes should be marked for disconnection while we have no extra peers
for (const CNode *node : vNodes) {
BOOST_CHECK(node->fDisconnect == false);
}
SetMockTime(GetTime() + 3 * chainparams.GetConsensus().nPowTargetSpacing + 1);
// Now tip should definitely be stale, and we should look for an extra
// outbound peer
peerLogic->CheckForStaleTipAndEvictPeers();
BOOST_CHECK(connman->GetTryNewOutboundPeer());
// Still no peers should be marked for disconnection
for (const CNode *node : vNodes) {
BOOST_CHECK(node->fDisconnect == false);
}
// If we add one more peer, something should get marked for eviction
// on the next check (since we're mocking the time to be in the future, the
// required time connected check should be satisfied).
AddRandomOutboundPeer(vNodes, *peerLogic, connman.get());
peerLogic->CheckForStaleTipAndEvictPeers();
for (int i = 0; i < max_outbound_full_relay; ++i) {
BOOST_CHECK(vNodes[i]->fDisconnect == false);
}
// Last added node should get marked for eviction
BOOST_CHECK(vNodes.back()->fDisconnect == true);
vNodes.back()->fDisconnect = false;
// Update the last announced block time for the last
// peer, and check that the next newest node gets evicted.
UpdateLastBlockAnnounceTime(vNodes.back()->GetId(), GetTime());
peerLogic->CheckForStaleTipAndEvictPeers();
for (int i = 0; i < max_outbound_full_relay - 1; ++i) {
BOOST_CHECK(vNodes[i]->fDisconnect == false);
}
BOOST_CHECK(vNodes[max_outbound_full_relay-1]->fDisconnect == true);
BOOST_CHECK(vNodes.back()->fDisconnect == false);
bool dummy;
for (const CNode *node : vNodes) {
peerLogic->FinalizeNode(*node, dummy);
}
connman->ClearNodes();
}
BOOST_AUTO_TEST_CASE(peer_discouragement)
{
const CChainParams& chainparams = Params();
auto banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME);
auto connman = MakeUnique<CConnman>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerManager>(chainparams, *connman, banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool);
banman->ClearBanned();
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, CAddress(), "", ConnectionType::INBOUND);
dummyNode1.SetCommonVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(&dummyNode1);
dummyNode1.fSuccessfullyConnected = true;
peerLogic->Misbehaving(dummyNode1.GetId(), DISCOURAGEMENT_THRESHOLD, /* message */ ""); // Should be discouraged
{
LOCK(dummyNode1.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(&dummyNode1));
}
BOOST_CHECK(banman->IsDiscouraged(addr1));
BOOST_CHECK(!banman->IsDiscouraged(ip(0xa0b0c001|0x0000ff00))); // Different IP, not discouraged
CAddress addr2(ip(0xa0b0c002), NODE_NONE);
CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, CAddress(), "", ConnectionType::INBOUND);
dummyNode2.SetCommonVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(&dummyNode2);
dummyNode2.fSuccessfullyConnected = true;
peerLogic->Misbehaving(dummyNode2.GetId(), DISCOURAGEMENT_THRESHOLD - 1, /* message */ "");
{
LOCK(dummyNode2.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(&dummyNode2));
}
BOOST_CHECK(!banman->IsDiscouraged(addr2)); // 2 not discouraged yet...
BOOST_CHECK(banman->IsDiscouraged(addr1)); // ... but 1 still should be
peerLogic->Misbehaving(dummyNode2.GetId(), 1, /* message */ ""); // 2 reaches discouragement threshold
{
LOCK(dummyNode2.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(&dummyNode2));
}
BOOST_CHECK(banman->IsDiscouraged(addr1)); // Expect both 1 and 2
BOOST_CHECK(banman->IsDiscouraged(addr2)); // to be discouraged now
bool dummy;
peerLogic->FinalizeNode(dummyNode1, dummy);
peerLogic->FinalizeNode(dummyNode2, dummy);
}
BOOST_AUTO_TEST_CASE(DoS_bantime)
{
const CChainParams& chainparams = Params();
auto banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME);
auto connman = MakeUnique<CConnman>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerManager>(chainparams, *connman, banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool);
banman->ClearBanned();
int64_t nStartTime = GetTime();
SetMockTime(nStartTime); // Overrides future calls to GetTime()
CAddress addr(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, CAddress(), "", ConnectionType::INBOUND);
dummyNode.SetCommonVersion(PROTOCOL_VERSION);
peerLogic->InitializeNode(&dummyNode);
dummyNode.fSuccessfullyConnected = true;
peerLogic->Misbehaving(dummyNode.GetId(), DISCOURAGEMENT_THRESHOLD, /* message */ "");
{
LOCK(dummyNode.cs_sendProcessing);
BOOST_CHECK(peerLogic->SendMessages(&dummyNode));
}
BOOST_CHECK(banman->IsDiscouraged(addr));
bool dummy;
peerLogic->FinalizeNode(dummyNode, dummy);
}
static CTransactionRef RandomOrphan()
{
std::map<uint256, COrphanTx>::iterator it;
LOCK2(cs_main, g_cs_orphans);
it = mapOrphanTransactions.lower_bound(InsecureRand256());
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
return it->second.tx;
}
static void MakeNewKeyWithFastRandomContext(CKey& key)
{
std::vector<unsigned char> keydata;
keydata = g_insecure_rand_ctx.randbytes(32);
key.Set(keydata.data(), keydata.data() + keydata.size(), /*fCompressedIn*/ true);
assert(key.IsValid());
}
BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
{
// This test had non-deterministic coverage due to
// randomly selected seeds.
// This seed is chosen so that all branches of the function
// ecdsa_signature_parse_der_lax are executed during this test.
// Specifically branches that run only when an ECDSA
// signature's R and S values have leading zeros.
g_insecure_rand_ctx = FastRandomContext(ArithToUint256(arith_uint256(33)));
CKey key;
MakeNewKeyWithFastRandomContext(key);
FillableSigningProvider keystore;
BOOST_CHECK(keystore.AddKey(key));
// 50 orphan transactions:
for (int i = 0; i < 50; i++)
{
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = InsecureRand256();
tx.vin[0].scriptSig << OP_1;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
AddOrphanTx(MakeTransactionRef(tx), i);
}
// ... and 50 that depend on other orphans:
for (int i = 0; i < 50; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = txPrev->GetHash();
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
BOOST_CHECK(SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL));
AddOrphanTx(MakeTransactionRef(tx), i);
}
// This really-big orphan should be ignored:
for (int i = 0; i < 10; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
tx.vin.resize(2777);
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
tx.vin[j].prevout.n = j;
tx.vin[j].prevout.hash = txPrev->GetHash();
}
BOOST_CHECK(SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL));
// Re-use same signature for other inputs
// (they don't have to be valid for this test)
for (unsigned int j = 1; j < tx.vin.size(); j++)
tx.vin[j].scriptSig = tx.vin[0].scriptSig;
BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i));
}
LOCK2(cs_main, g_cs_orphans);
// Test EraseOrphansFor:
for (NodeId i = 0; i < 3; i++)
{
size_t sizeBefore = mapOrphanTransactions.size();
EraseOrphansFor(i);
BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore);
}
// Test LimitOrphanTxSize() function:
LimitOrphanTxSize(40);
BOOST_CHECK(mapOrphanTransactions.size() <= 40);
LimitOrphanTxSize(10);
BOOST_CHECK(mapOrphanTransactions.size() <= 10);
LimitOrphanTxSize(0);
BOOST_CHECK(mapOrphanTransactions.empty());
}
BOOST_AUTO_TEST_SUITE_END()
| [
"77495384+mixcan@users.noreply.github.com"
] | 77495384+mixcan@users.noreply.github.com |
cc1bc127fc3e3b69faac55f4dddf7b87812098cb | 99425a2a04a0281324ae02d53e923719c36540a8 | /test/test.cpp | 4ae1d6da66711cdd090248446310146717ccd002 | [] | no_license | wangzhibinjunhua/cpptest | 64aa3f0b5139cd5736c430f0e7201b288da4122a | 41b393782a1c2daf0926bc60843913b8dd593a8c | refs/heads/master | 2020-05-28T09:05:07.015960 | 2019-05-28T06:09:07 | 2019-05-28T06:09:07 | 188,950,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | #include <iostream>
#include <fstream>
using namespace std;
void test()
{
int count = 0;
while(1) {
count++;
printf("count=%d\n", count);
if (count > 5) {
break;
}
}
}
void test2()
{
}
int main(int argc, char **argv)
{
test();
getchar();
return 0;
}
| [
"wangzhibin_x@foxmail.com"
] | wangzhibin_x@foxmail.com |
ea12d57a20126aa7ef5751dfb1c36124c83eb7f8 | 1e2c2688150ddcc894d9049fc353029cd75c8d87 | /supporting libraries/pyside/PySide-1.2.4/pyside_build/py3.5-qt4.8.5-64bit-release/pyside/PySide/QtGui/PySide/QtGui/qcursor_wrapper.cpp | e315c97307e50b3d378d90526989f21b71d6bf3c | [] | no_license | tryanaditya/mainmain | f3f9559230a520b69bdafc8bf9e36ebbf14147fa | fc82048e17587af3b56b977bea476a7f2506a7ba | refs/heads/master | 2021-01-11T03:11:00.020758 | 2016-10-16T23:55:05 | 2016-10-16T23:55:05 | 71,084,893 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,811 | cpp | /*
* This file is part of PySide: Python for Qt
*
* Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
*
* Contact: PySide team <contact@pyside.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
//workaround to access protected functions
#define protected public
// default includes
#include <shiboken.h>
#include <pysidesignal.h>
#include <pysideproperty.h>
#include <pyside.h>
#include <destroylistener.h>
#include <typeresolver.h>
#include <typeinfo>
#include "pyside_qtgui_python.h"
#include "qcursor_wrapper.h"
// Extra includes
#include <QPixmap>
#include <Qt>
#include <qbitmap.h>
#include <qcursor.h>
#include <qdatastream.h>
#include <qpixmap.h>
#include <qpoint.h>
// Target ---------------------------------------------------------
extern "C" {
static int
Sbk_QCursor_Init(PyObject* self, PyObject* args, PyObject* kwds)
{
SbkObject* sbkSelf = reinterpret_cast<SbkObject*>(self);
if (Shiboken::Object::isUserType(self) && !Shiboken::ObjectType::canCallConstructor(self->ob_type, Shiboken::SbkType< ::QCursor >()))
return -1;
::QCursor* cptr = 0;
int overloadId = -1;
PythonToCppFunc pythonToCpp[] = { 0, 0, 0, 0 };
SBK_UNUSED(pythonToCpp)
int numNamedArgs = (kwds ? PyDict_Size(kwds) : 0);
int numArgs = PyTuple_GET_SIZE(args);
PyObject* pyArgs[] = {0, 0, 0, 0};
// invalid argument lengths
if (numArgs + numNamedArgs > 4) {
PyErr_SetString(PyExc_TypeError, "PySide.QtGui.QCursor(): too many arguments");
return -1;
}
if (!PyArg_ParseTuple(args, "|OOOO:QCursor", &(pyArgs[0]), &(pyArgs[1]), &(pyArgs[2]), &(pyArgs[3])))
return -1;
// Overloaded function decisor
// 0: QCursor()
// 1: QCursor(Qt::CursorShape)
// 2: QCursor(Qt::HANDLE)
// 3: QCursor(QBitmap,QBitmap,int,int)
// 4: QCursor(QCursor)
// 5: QCursor(QPixmap,int,int)
if (numArgs == 0) {
overloadId = 0; // QCursor()
} else if (numArgs >= 2
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QBITMAP_IDX], (pyArgs[0])))
&& (pythonToCpp[1] = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QBITMAP_IDX], (pyArgs[1])))) {
if (numArgs == 2) {
overloadId = 3; // QCursor(QBitmap,QBitmap,int,int)
} else if ((pythonToCpp[2] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[2])))) {
if (numArgs == 3) {
overloadId = 3; // QCursor(QBitmap,QBitmap,int,int)
} else if ((pythonToCpp[3] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[3])))) {
overloadId = 3; // QCursor(QBitmap,QBitmap,int,int)
}
}
} else if ((pythonToCpp[0] = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QPIXMAP_IDX], (pyArgs[0])))) {
if (numArgs == 1) {
overloadId = 5; // QCursor(QPixmap,int,int)
} else if ((pythonToCpp[1] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[1])))) {
if (numArgs == 2) {
overloadId = 5; // QCursor(QPixmap,int,int)
} else if ((pythonToCpp[2] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[2])))) {
overloadId = 5; // QCursor(QPixmap,int,int)
}
}
} else if (numArgs == 1
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<Qt::HANDLE>(), (pyArgs[0])))) {
overloadId = 2; // QCursor(Qt::HANDLE)
} else if (numArgs == 1
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(SBK_CONVERTER(SbkPySide_QtCoreTypes[SBK_QT_CURSORSHAPE_IDX]), (pyArgs[0])))) {
overloadId = 1; // QCursor(Qt::CursorShape)
} else if (numArgs == 1
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (pyArgs[0])))) {
overloadId = 4; // QCursor(QCursor)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QCursor_Init_TypeError;
// Call function/method
switch (overloadId) {
case 0: // QCursor()
{
if (!PyErr_Occurred()) {
// QCursor()
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QCursor();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 1: // QCursor(Qt::CursorShape shape)
{
::Qt::CursorShape cppArg0 = ((::Qt::CursorShape)0);
pythonToCpp[0](pyArgs[0], &cppArg0);
if (!PyErr_Occurred()) {
// QCursor(Qt::CursorShape)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QCursor(cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 2: // QCursor(Qt::HANDLE cursor)
{
::Qt::HANDLE cppArg0 = ::Qt::HANDLE();
pythonToCpp[0](pyArgs[0], &cppArg0);
if (!PyErr_Occurred()) {
// QCursor(Qt::HANDLE)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QCursor(cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 3: // QCursor(const QBitmap & bitmap, const QBitmap & mask, int hotX, int hotY)
{
if (kwds) {
PyObject* value = PyDict_GetItemString(kwds, "hotX");
if (value && pyArgs[2]) {
PyErr_SetString(PyExc_TypeError, "PySide.QtGui.QCursor(): got multiple values for keyword argument 'hotX'.");
return -1;
} else if (value) {
pyArgs[2] = value;
if (!(pythonToCpp[2] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[2]))))
goto Sbk_QCursor_Init_TypeError;
}
value = PyDict_GetItemString(kwds, "hotY");
if (value && pyArgs[3]) {
PyErr_SetString(PyExc_TypeError, "PySide.QtGui.QCursor(): got multiple values for keyword argument 'hotY'.");
return -1;
} else if (value) {
pyArgs[3] = value;
if (!(pythonToCpp[3] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[3]))))
goto Sbk_QCursor_Init_TypeError;
}
}
if (!Shiboken::Object::isValid(pyArgs[0]))
return -1;
::QBitmap cppArg0_local = ::QBitmap();
::QBitmap* cppArg0 = &cppArg0_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QBITMAP_IDX], pythonToCpp[0]))
pythonToCpp[0](pyArgs[0], &cppArg0_local);
else
pythonToCpp[0](pyArgs[0], &cppArg0);
if (!Shiboken::Object::isValid(pyArgs[1]))
return -1;
::QBitmap cppArg1_local = ::QBitmap();
::QBitmap* cppArg1 = &cppArg1_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QBITMAP_IDX], pythonToCpp[1]))
pythonToCpp[1](pyArgs[1], &cppArg1_local);
else
pythonToCpp[1](pyArgs[1], &cppArg1);
int cppArg2 = -1;
if (pythonToCpp[2]) pythonToCpp[2](pyArgs[2], &cppArg2);
int cppArg3 = -1;
if (pythonToCpp[3]) pythonToCpp[3](pyArgs[3], &cppArg3);
if (!PyErr_Occurred()) {
// QCursor(QBitmap,QBitmap,int,int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QCursor(*cppArg0, *cppArg1, cppArg2, cppArg3);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 4: // QCursor(const QCursor & cursor)
{
if (!Shiboken::Object::isValid(pyArgs[0]))
return -1;
::QCursor cppArg0_local = ::QCursor();
::QCursor* cppArg0 = &cppArg0_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], pythonToCpp[0]))
pythonToCpp[0](pyArgs[0], &cppArg0_local);
else
pythonToCpp[0](pyArgs[0], &cppArg0);
if (!PyErr_Occurred()) {
// QCursor(QCursor)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QCursor(*cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 5: // QCursor(const QPixmap & pixmap, int hotX, int hotY)
{
if (kwds) {
PyObject* value = PyDict_GetItemString(kwds, "hotX");
if (value && pyArgs[1]) {
PyErr_SetString(PyExc_TypeError, "PySide.QtGui.QCursor(): got multiple values for keyword argument 'hotX'.");
return -1;
} else if (value) {
pyArgs[1] = value;
if (!(pythonToCpp[1] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[1]))))
goto Sbk_QCursor_Init_TypeError;
}
value = PyDict_GetItemString(kwds, "hotY");
if (value && pyArgs[2]) {
PyErr_SetString(PyExc_TypeError, "PySide.QtGui.QCursor(): got multiple values for keyword argument 'hotY'.");
return -1;
} else if (value) {
pyArgs[2] = value;
if (!(pythonToCpp[2] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[2]))))
goto Sbk_QCursor_Init_TypeError;
}
}
if (!Shiboken::Object::isValid(pyArgs[0]))
return -1;
::QPixmap cppArg0_local = ::QPixmap();
::QPixmap* cppArg0 = &cppArg0_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QPIXMAP_IDX], pythonToCpp[0]))
pythonToCpp[0](pyArgs[0], &cppArg0_local);
else
pythonToCpp[0](pyArgs[0], &cppArg0);
int cppArg1 = -1;
if (pythonToCpp[1]) pythonToCpp[1](pyArgs[1], &cppArg1);
int cppArg2 = -1;
if (pythonToCpp[2]) pythonToCpp[2](pyArgs[2], &cppArg2);
if (!PyErr_Occurred()) {
// QCursor(QPixmap,int,int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QCursor(*cppArg0, cppArg1, cppArg2);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
}
if (PyErr_Occurred() || !Shiboken::Object::setCppPointer(sbkSelf, Shiboken::SbkType< ::QCursor >(), cptr)) {
delete cptr;
return -1;
}
if (!cptr) goto Sbk_QCursor_Init_TypeError;
Shiboken::Object::setValidCpp(sbkSelf, true);
Shiboken::BindingManager::instance().registerWrapper(sbkSelf, cptr);
return 1;
Sbk_QCursor_Init_TypeError:
const char* overloads[] = {"", "PySide.QtCore.Qt.CursorShape", "Qt::HANDLE", "PySide.QtGui.QBitmap, PySide.QtGui.QBitmap, int = -1, int = -1", "PySide.QtGui.QCursor", "PySide.QtGui.QPixmap, int = -1, int = -1", 0};
Shiboken::setErrorAboutWrongArguments(args, "PySide.QtGui.QCursor", overloads);
return -1;
}
static PyObject* Sbk_QCursorFunc_bitmap(PyObject* self)
{
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// bitmap()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
const QBitmap * cppResult = const_cast<const ::QCursor*>(cppSelf)->bitmap();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::pointerToPython((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QBITMAP_IDX], cppResult);
Shiboken::Object::setParent(self, pyResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QCursorFunc_hotSpot(PyObject* self)
{
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// hotSpot()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
QPoint cppResult = const_cast<const ::QCursor*>(cppSelf)->hotSpot();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QPOINT_IDX], &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QCursorFunc_mask(PyObject* self)
{
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// mask()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
const QBitmap * cppResult = const_cast<const ::QCursor*>(cppSelf)->mask();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::pointerToPython((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QBITMAP_IDX], cppResult);
Shiboken::Object::setParent(self, pyResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QCursorFunc_pixmap(PyObject* self)
{
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// pixmap()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
QPixmap cppResult = const_cast<const ::QCursor*>(cppSelf)->pixmap();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QPIXMAP_IDX], &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QCursorFunc_pos(PyObject* self)
{
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// pos()
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
QPoint cppResult = ::QCursor::pos();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QPOINT_IDX], &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QCursorFunc_setPos(PyObject* self, PyObject* args)
{
int overloadId = -1;
PythonToCppFunc pythonToCpp[] = { 0, 0 };
SBK_UNUSED(pythonToCpp)
int numArgs = PyTuple_GET_SIZE(args);
PyObject* pyArgs[] = {0, 0};
// invalid argument lengths
if (!PyArg_UnpackTuple(args, "setPos", 1, 2, &(pyArgs[0]), &(pyArgs[1])))
return 0;
// Overloaded function decisor
// 0: setPos(QPoint)
// 1: setPos(int,int)
if (numArgs == 2
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[0])))
&& (pythonToCpp[1] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[1])))) {
overloadId = 1; // setPos(int,int)
} else if (numArgs == 1
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QPOINT_IDX], (pyArgs[0])))) {
overloadId = 0; // setPos(QPoint)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QCursorFunc_setPos_TypeError;
// Call function/method
switch (overloadId) {
case 0: // setPos(const QPoint & p)
{
if (!Shiboken::Object::isValid(pyArgs[0]))
return 0;
::QPoint cppArg0_local = ::QPoint();
::QPoint* cppArg0 = &cppArg0_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QPOINT_IDX], pythonToCpp[0]))
pythonToCpp[0](pyArgs[0], &cppArg0_local);
else
pythonToCpp[0](pyArgs[0], &cppArg0);
if (!PyErr_Occurred()) {
// setPos(QPoint)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
::QCursor::setPos(*cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 1: // setPos(int x, int y)
{
int cppArg0;
pythonToCpp[0](pyArgs[0], &cppArg0);
int cppArg1;
pythonToCpp[1](pyArgs[1], &cppArg1);
if (!PyErr_Occurred()) {
// setPos(int,int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
::QCursor::setPos(cppArg0, cppArg1);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
}
if (PyErr_Occurred()) {
return 0;
}
Py_RETURN_NONE;
Sbk_QCursorFunc_setPos_TypeError:
const char* overloads[] = {"PySide.QtCore.QPoint", "int, int", 0};
Shiboken::setErrorAboutWrongArguments(args, "PySide.QtGui.QCursor.setPos", overloads);
return 0;
}
static PyObject* Sbk_QCursorFunc_setShape(PyObject* self, PyObject* pyArg)
{
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
int overloadId = -1;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
// Overloaded function decisor
// 0: setShape(Qt::CursorShape)
if ((pythonToCpp = Shiboken::Conversions::isPythonToCppConvertible(SBK_CONVERTER(SbkPySide_QtCoreTypes[SBK_QT_CURSORSHAPE_IDX]), (pyArg)))) {
overloadId = 0; // setShape(Qt::CursorShape)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QCursorFunc_setShape_TypeError;
// Call function/method
{
::Qt::CursorShape cppArg0 = ((::Qt::CursorShape)0);
pythonToCpp(pyArg, &cppArg0);
if (!PyErr_Occurred()) {
// setShape(Qt::CursorShape)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cppSelf->setShape(cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
}
if (PyErr_Occurred()) {
return 0;
}
Py_RETURN_NONE;
Sbk_QCursorFunc_setShape_TypeError:
const char* overloads[] = {"PySide.QtCore.Qt.CursorShape", 0};
Shiboken::setErrorAboutWrongArguments(pyArg, "PySide.QtGui.QCursor.setShape", overloads);
return 0;
}
static PyObject* Sbk_QCursorFunc_shape(PyObject* self)
{
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// shape()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
Qt::CursorShape cppResult = const_cast<const ::QCursor*>(cppSelf)->shape();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython(SBK_CONVERTER(SbkPySide_QtCoreTypes[SBK_QT_CURSORSHAPE_IDX]), &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QCursor___copy__(PyObject* self)
{
if (!Shiboken::Object::isValid(self))
return 0;
::QCursor& cppSelf = *(((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self)));
PyObject* pyResult = Shiboken::Conversions::copyToPython((SbkObjectType*)SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], &cppSelf);
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyMethodDef Sbk_QCursor_methods[] = {
{"bitmap", (PyCFunction)Sbk_QCursorFunc_bitmap, METH_NOARGS},
{"hotSpot", (PyCFunction)Sbk_QCursorFunc_hotSpot, METH_NOARGS},
{"mask", (PyCFunction)Sbk_QCursorFunc_mask, METH_NOARGS},
{"pixmap", (PyCFunction)Sbk_QCursorFunc_pixmap, METH_NOARGS},
{"pos", (PyCFunction)Sbk_QCursorFunc_pos, METH_NOARGS|METH_STATIC},
{"setPos", (PyCFunction)Sbk_QCursorFunc_setPos, METH_VARARGS|METH_STATIC},
{"setShape", (PyCFunction)Sbk_QCursorFunc_setShape, METH_O},
{"shape", (PyCFunction)Sbk_QCursorFunc_shape, METH_NOARGS},
{"__copy__", (PyCFunction)Sbk_QCursor___copy__, METH_NOARGS},
{0} // Sentinel
};
static PyObject* Sbk_QCursorFunc___lshift__(PyObject* self, PyObject* pyArg)
{
bool isReverse = SbkObject_TypeCheck(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], pyArg)
&& !SbkObject_TypeCheck(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], self);
if (isReverse)
std::swap(self, pyArg);
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
int overloadId = -1;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
if (!isReverse
&& Shiboken::Object::checkType(pyArg)
&& !PyObject_TypeCheck(pyArg, self->ob_type)
&& PyObject_HasAttrString(pyArg, const_cast<char*>("__rlshift__"))) {
PyObject* revOpMethod = PyObject_GetAttrString(pyArg, const_cast<char*>("__rlshift__"));
if (revOpMethod && PyCallable_Check(revOpMethod)) {
pyResult = PyObject_CallFunction(revOpMethod, const_cast<char*>("O"), self);
if (PyErr_Occurred() && (PyErr_ExceptionMatches(PyExc_NotImplementedError) || PyErr_ExceptionMatches(PyExc_AttributeError))) {
PyErr_Clear();
Py_XDECREF(pyResult);
pyResult = 0;
}
}
Py_XDECREF(revOpMethod);
}
// Do not enter here if other object has implemented a reverse operator.
if (!pyResult) {
// Overloaded function decisor
// 0: operator<<(QDataStream&,QCursor)
if (isReverse
&& (pythonToCpp = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QDATASTREAM_IDX], (pyArg)))) {
overloadId = 0; // operator<<(QDataStream&,QCursor)
}
if (isReverse && overloadId == -1) {
PyErr_SetString(PyExc_NotImplementedError, "reverse operator not implemented.");
return 0;
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QCursorFunc___lshift___TypeError;
// Call function/method
{
if (!Shiboken::Object::isValid(pyArg))
return 0;
::QDataStream* cppArg0;
pythonToCpp(pyArg, &cppArg0);
if (!PyErr_Occurred()) {
// operator<<(QDataStream&,QCursor) [reverse operator]
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
QDataStream & cppResult = (*cppArg0) << (*cppSelf);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::referenceToPython((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QDATASTREAM_IDX], &cppResult);
}
}
} // End of "if (!pyResult)"
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
Sbk_QCursorFunc___lshift___TypeError:
const char* overloads[] = {"PySide.QtCore.QDataStream", 0};
Shiboken::setErrorAboutWrongArguments(pyArg, "PySide.QtGui.QCursor.__lshift__", overloads);
return 0;
}
static PyObject* Sbk_QCursorFunc___rshift__(PyObject* self, PyObject* pyArg)
{
bool isReverse = SbkObject_TypeCheck(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], pyArg)
&& !SbkObject_TypeCheck(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], self);
if (isReverse)
std::swap(self, pyArg);
::QCursor* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
int overloadId = -1;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
if (!isReverse
&& Shiboken::Object::checkType(pyArg)
&& !PyObject_TypeCheck(pyArg, self->ob_type)
&& PyObject_HasAttrString(pyArg, const_cast<char*>("__rrshift__"))) {
PyObject* revOpMethod = PyObject_GetAttrString(pyArg, const_cast<char*>("__rrshift__"));
if (revOpMethod && PyCallable_Check(revOpMethod)) {
pyResult = PyObject_CallFunction(revOpMethod, const_cast<char*>("O"), self);
if (PyErr_Occurred() && (PyErr_ExceptionMatches(PyExc_NotImplementedError) || PyErr_ExceptionMatches(PyExc_AttributeError))) {
PyErr_Clear();
Py_XDECREF(pyResult);
pyResult = 0;
}
}
Py_XDECREF(revOpMethod);
}
// Do not enter here if other object has implemented a reverse operator.
if (!pyResult) {
// Overloaded function decisor
// 0: operator>>(QDataStream&,QCursor&)
if (isReverse
&& (pythonToCpp = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QDATASTREAM_IDX], (pyArg)))) {
overloadId = 0; // operator>>(QDataStream&,QCursor&)
}
if (isReverse && overloadId == -1) {
PyErr_SetString(PyExc_NotImplementedError, "reverse operator not implemented.");
return 0;
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QCursorFunc___rshift___TypeError;
// Call function/method
{
if (!Shiboken::Object::isValid(pyArg))
return 0;
::QDataStream* cppArg0;
pythonToCpp(pyArg, &cppArg0);
if (!PyErr_Occurred()) {
// operator>>(QDataStream&,QCursor&) [reverse operator]
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
QDataStream & cppResult = (*cppArg0) >> (*cppSelf);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::referenceToPython((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QDATASTREAM_IDX], &cppResult);
}
}
} // End of "if (!pyResult)"
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
Sbk_QCursorFunc___rshift___TypeError:
const char* overloads[] = {"PySide.QtCore.QDataStream", 0};
Shiboken::setErrorAboutWrongArguments(pyArg, "PySide.QtGui.QCursor.__rshift__", overloads);
return 0;
}
} // extern "C"
static int Sbk_QCursor_traverse(PyObject* self, visitproc visit, void* arg)
{
return reinterpret_cast<PyTypeObject*>(&SbkObject_Type)->tp_traverse(self, visit, arg);
}
static int Sbk_QCursor_clear(PyObject* self)
{
return reinterpret_cast<PyTypeObject*>(&SbkObject_Type)->tp_clear(self);
}
// Class Definition -----------------------------------------------
extern "C" {
static PyNumberMethods Sbk_QCursor_TypeAsNumber;
static SbkObjectType Sbk_QCursor_Type = { { {
PyVarObject_HEAD_INIT(&SbkObjectType_Type, 0)
/*tp_name*/ "PySide.QtGui.QCursor",
/*tp_basicsize*/ sizeof(SbkObject),
/*tp_itemsize*/ 0,
/*tp_dealloc*/ &SbkDeallocWrapper,
/*tp_print*/ 0,
/*tp_getattr*/ 0,
/*tp_setattr*/ 0,
/*tp_compare*/ 0,
/*tp_repr*/ 0,
/*tp_as_number*/ 0,
/*tp_as_sequence*/ 0,
/*tp_as_mapping*/ 0,
/*tp_hash*/ 0,
/*tp_call*/ 0,
/*tp_str*/ 0,
/*tp_getattro*/ 0,
/*tp_setattro*/ 0,
/*tp_as_buffer*/ 0,
/*tp_flags*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_GC,
/*tp_doc*/ 0,
/*tp_traverse*/ Sbk_QCursor_traverse,
/*tp_clear*/ Sbk_QCursor_clear,
/*tp_richcompare*/ 0,
/*tp_weaklistoffset*/ 0,
/*tp_iter*/ 0,
/*tp_iternext*/ 0,
/*tp_methods*/ Sbk_QCursor_methods,
/*tp_members*/ 0,
/*tp_getset*/ 0,
/*tp_base*/ reinterpret_cast<PyTypeObject*>(&SbkObject_Type),
/*tp_dict*/ 0,
/*tp_descr_get*/ 0,
/*tp_descr_set*/ 0,
/*tp_dictoffset*/ 0,
/*tp_init*/ Sbk_QCursor_Init,
/*tp_alloc*/ 0,
/*tp_new*/ SbkObjectTpNew,
/*tp_free*/ 0,
/*tp_is_gc*/ 0,
/*tp_bases*/ 0,
/*tp_mro*/ 0,
/*tp_cache*/ 0,
/*tp_subclasses*/ 0,
/*tp_weaklist*/ 0
}, },
/*priv_data*/ 0
};
} //extern
// Type conversion functions.
// Python to C++ pointer conversion - returns the C++ object of the Python wrapper (keeps object identity).
static void QCursor_PythonToCpp_QCursor_PTR(PyObject* pyIn, void* cppOut) {
Shiboken::Conversions::pythonToCppPointer(&Sbk_QCursor_Type, pyIn, cppOut);
}
static PythonToCppFunc is_QCursor_PythonToCpp_QCursor_PTR_Convertible(PyObject* pyIn) {
if (pyIn == Py_None)
return Shiboken::Conversions::nonePythonToCppNullPtr;
if (PyObject_TypeCheck(pyIn, (PyTypeObject*)&Sbk_QCursor_Type))
return QCursor_PythonToCpp_QCursor_PTR;
return 0;
}
// C++ to Python pointer conversion - tries to find the Python wrapper for the C++ object (keeps object identity).
static PyObject* QCursor_PTR_CppToPython_QCursor(const void* cppIn) {
PyObject* pyOut = (PyObject*)Shiboken::BindingManager::instance().retrieveWrapper(cppIn);
if (pyOut) {
Py_INCREF(pyOut);
return pyOut;
}
const char* typeName = typeid(*((::QCursor*)cppIn)).name();
return Shiboken::Object::newObject(&Sbk_QCursor_Type, const_cast<void*>(cppIn), false, false, typeName);
}
// C++ to Python copy conversion.
static PyObject* QCursor_COPY_CppToPython_QCursor(const void* cppIn) {
return Shiboken::Object::newObject(&Sbk_QCursor_Type, new ::QCursor(*((::QCursor*)cppIn)), true, true);
}
// Python to C++ copy conversion.
static void QCursor_PythonToCpp_QCursor_COPY(PyObject* pyIn, void* cppOut) {
*((::QCursor*)cppOut) = *((::QCursor*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX], (SbkObject*)pyIn));
}
static PythonToCppFunc is_QCursor_PythonToCpp_QCursor_COPY_Convertible(PyObject* pyIn) {
if (PyObject_TypeCheck(pyIn, (PyTypeObject*)&Sbk_QCursor_Type))
return QCursor_PythonToCpp_QCursor_COPY;
return 0;
}
// Implicit conversions.
static void PySide_QtCore_Qt_CursorShape_PythonToCpp_QCursor(PyObject* pyIn, void* cppOut) {
::Qt::CursorShape cppIn = ((::Qt::CursorShape)0);
Shiboken::Conversions::pythonToCppCopy(SBK_CONVERTER(SbkPySide_QtCoreTypes[SBK_QT_CURSORSHAPE_IDX]), pyIn, &cppIn);
*((::QCursor*)cppOut) = ::QCursor(cppIn);
}
static PythonToCppFunc is_PySide_QtCore_Qt_CursorShape_PythonToCpp_QCursor_Convertible(PyObject* pyIn) {
if (SbkObject_TypeCheck(SbkPySide_QtCoreTypes[SBK_QT_CURSORSHAPE_IDX], pyIn))
return PySide_QtCore_Qt_CursorShape_PythonToCpp_QCursor;
return 0;
}
static void PySide_QtCore_Qt_HANDLE_PythonToCpp_QCursor(PyObject* pyIn, void* cppOut) {
::Qt::HANDLE cppIn = ::Qt::HANDLE();
Shiboken::Conversions::pythonToCppCopy(Shiboken::Conversions::PrimitiveTypeConverter<Qt::HANDLE>(), pyIn, &cppIn);
*((::QCursor*)cppOut) = ::QCursor(cppIn);
}
static PythonToCppFunc is_PySide_QtCore_Qt_HANDLE_PythonToCpp_QCursor_Convertible(PyObject* pyIn) {
if (PyLong_Check(pyIn))
return PySide_QtCore_Qt_HANDLE_PythonToCpp_QCursor;
return 0;
}
static void constQPixmapREF_PythonToCpp_QCursor(PyObject* pyIn, void* cppOut) {
*((::QCursor*)cppOut) = ::QCursor(*((::QPixmap*)Shiboken::Conversions::cppPointer(SbkPySide_QtGuiTypes[SBK_QPIXMAP_IDX], (SbkObject*)pyIn)));
}
static PythonToCppFunc is_constQPixmapREF_PythonToCpp_QCursor_Convertible(PyObject* pyIn) {
if (SbkObject_TypeCheck(SbkPySide_QtGuiTypes[SBK_QPIXMAP_IDX], pyIn))
return constQPixmapREF_PythonToCpp_QCursor;
return 0;
}
void init_QCursor(PyObject* module)
{
// type has number operators
memset(&Sbk_QCursor_TypeAsNumber, 0, sizeof(PyNumberMethods));
Sbk_QCursor_TypeAsNumber.nb_rshift = Sbk_QCursorFunc___rshift__;
Sbk_QCursor_TypeAsNumber.nb_lshift = Sbk_QCursorFunc___lshift__;
Sbk_QCursor_Type.super.ht_type.tp_as_number = &Sbk_QCursor_TypeAsNumber;
SbkPySide_QtGuiTypes[SBK_QCURSOR_IDX] = reinterpret_cast<PyTypeObject*>(&Sbk_QCursor_Type);
if (!Shiboken::ObjectType::introduceWrapperType(module, "QCursor", "QCursor",
&Sbk_QCursor_Type, &Shiboken::callCppDestructor< ::QCursor >)) {
return;
}
// Register Converter
SbkConverter* converter = Shiboken::Conversions::createConverter(&Sbk_QCursor_Type,
QCursor_PythonToCpp_QCursor_PTR,
is_QCursor_PythonToCpp_QCursor_PTR_Convertible,
QCursor_PTR_CppToPython_QCursor,
QCursor_COPY_CppToPython_QCursor);
Shiboken::Conversions::registerConverterName(converter, "QCursor");
Shiboken::Conversions::registerConverterName(converter, "QCursor*");
Shiboken::Conversions::registerConverterName(converter, "QCursor&");
Shiboken::Conversions::registerConverterName(converter, typeid(::QCursor).name());
// Add Python to C++ copy (value, not pointer neither reference) conversion to type converter.
Shiboken::Conversions::addPythonToCppValueConversion(converter,
QCursor_PythonToCpp_QCursor_COPY,
is_QCursor_PythonToCpp_QCursor_COPY_Convertible);
// Add implicit conversions to type converter.
Shiboken::Conversions::addPythonToCppValueConversion(converter,
PySide_QtCore_Qt_CursorShape_PythonToCpp_QCursor,
is_PySide_QtCore_Qt_CursorShape_PythonToCpp_QCursor_Convertible);
Shiboken::Conversions::addPythonToCppValueConversion(converter,
PySide_QtCore_Qt_HANDLE_PythonToCpp_QCursor,
is_PySide_QtCore_Qt_HANDLE_PythonToCpp_QCursor_Convertible);
Shiboken::Conversions::addPythonToCppValueConversion(converter,
constQPixmapREF_PythonToCpp_QCursor,
is_constQPixmapREF_PythonToCpp_QCursor_Convertible);
qRegisterMetaType< ::QCursor >("QCursor");
}
| [
"tryan.aditya@yahoo.com"
] | tryan.aditya@yahoo.com |
48ffe13e34e656abf6f32da0daf19ed473f1caf0 | 686c8866c52f2aba39152e046b6840c8bcdc981a | /basic_algo/rotate_sentence.cpp | 2ce3a0c65eb1273edf44231eae6c3b428bdd6699 | [] | no_license | supr/algorithms-old | 7bf940050228270d3b28c1e2b098ee110f1c5284 | c2f06205cdb1cc98e4bfdc9e06293e2c1b149db2 | refs/heads/master | 2021-05-29T13:09:54.353514 | 2015-07-04T22:52:27 | 2015-07-04T22:52:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,937 | cpp | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// methode wiht 2 parameter, 1 param: sentence, 2 param: rotate sentece by x
// Example: "This is a sentence", 2 -> "a sentence This is"
string rotate_sentence(string s, int num_rotation) {
int words_len = 0;
int count_space = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == ' ') {
count_space++;
if (count_space == num_rotation) {
words_len = s.size() - words_len;
break;
}
}
words_len++;
}
rotate(s.begin(), s.begin() + words_len, s.end());
s.insert(s.size() - words_len, " ");
return s;
}
void my_rotate(string &s, int number_of_rot) {
for (int i = 0; i < number_of_rot; i++) {
int tmp = s[0];
int j;
for (j = 1; j < s.size(); j++) {
s[j - 1] = s[j];
}
s[j - 1] = tmp;
}
}
void my_rotate2(string &s, int number_of_rot) {
string rotated_part = s.substr(0, number_of_rot);
s.erase(0, number_of_rot);
s += rotated_part;
}
string rotate_sentence2(string s, int num_rotation) {
int words_len = 0;
int count_space = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == ' ') {
count_space++;
if (count_space == num_rotation) {
words_len = s.size() - words_len;
break;
}
}
words_len++;
}
my_rotate(s, words_len);
s.insert(s.size() - words_len, " ");
return s;
}
string rotate_sentence3(string s, int num_rotation) {
int words_len = 0;
int count_space = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == ' ') {
count_space++;
if (count_space == num_rotation) {
words_len = s.size() - words_len;
break;
}
}
words_len++;
}
my_rotate2(s, words_len);
s.insert(s.size() - words_len, " ");
return s;
}
int main() {
// your code goes here
string s = "This is a sentence";
cout << rotate_sentence(s, 2) << endl;
cout << rotate_sentence2(s, 2) << endl;
cout << rotate_sentence3(s, 2) << endl;
return 0;
} | [
"Gerald.Stanje@gmail.com"
] | Gerald.Stanje@gmail.com |
81baefcb3e9cd2eb5e115aa27ca74036dd5e3fbd | b59cceebacb423b54f38775bd88a99f5a15d013b | /atcoder/others/jsc/2019/qual/a.cpp | 6cbe9eff7e1feecb0f324422589df3b13b4f7327 | [
"MIT"
] | permissive | yu3mars/proconVSCodeGcc | 5e434133d4e9edf80d02a8ca4b95ee77833fbee7 | fcf36165bb14fb6f555664355e05dd08d12e426b | refs/heads/master | 2021-06-06T08:32:06.122671 | 2020-09-13T05:49:32 | 2020-09-13T05:49:32 | 151,394,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main()
{
int mm,dd;
cin>>mm>>dd;
int ans=0;
for (int m = 1; m <= mm; m++)
{
for (int d = 1; d <= dd; d++)
{
int d1 = d%10;
int d10 = d/10;
if(d1>=2 && d10>=2 && d1*d10==m)
{
ans++;
}
}
}
cout<<ans<<endl;
return 0;
} | [
"yu3mars@users.noreply.github.com"
] | yu3mars@users.noreply.github.com |
04247a578a6dc9517fb93accf3e1750bcc80680a | fb20472e213c78abdd3f792b99db1a862c2108bd | /ConsoleApplication1/game1.cpp | f60b29dd01db7b4f2c7cd4693d359067d092929b | [] | no_license | fanghui12/ConsoleApplication1 | a1f4448cb030dc2b206cbd38d64ffd1a6815c11b | 5c6e364c6de5baac6bae3785fe96262639cddd4a | refs/heads/master | 2022-09-28T09:45:55.893890 | 2020-06-06T06:37:39 | 2020-06-06T06:37:39 | 269,907,096 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 188 | cpp | #include "game1.h"
void planning::show() {
cout << "我是planning show" << endl;
}
void planning::showa() {
cout << "我是planning命名空间的 a:"<< planning::c <<endl;
}
| [
"ahwx90@163.com"
] | ahwx90@163.com |
0a7a140f128e3b5968ce7f93b11c90762199fc19 | 650d9e78c645281ccb6258f262c7691981827769 | /week4assignment.cpp | 0210a99755221853f024f581465cd422c596f754 | [] | no_license | EmilyMet/College-Assignments | d934534c6030a2cbde19dd2930c9cce63be0301b | dbb2930751a0bd32596c1fd3256223aef50fb4a1 | refs/heads/master | 2020-09-13T23:43:09.672012 | 2019-11-25T13:46:13 | 2019-11-25T13:46:13 | 222,942,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,855 | cpp | //Program outputs the area of different 3d shapes
#include "stdio.h"
void main()
{
int choice = 0;
float base = 0;
float height = 0;
float area = 0;
float length = 0;
float width = 0;
float radius = 0;
float angle = 0;
printf("Area Calculator \n");
printf("1 <triangle> \n");
printf("2 <square> \n");
printf("3 <rectangle> \n");
printf("4 <parallelogram> \n");
printf("5 <trapezoid> \n");
printf("6 <circle> \n");
printf("7 <ellipse> \n");
printf("8 <sector> \n");
start:
printf("Enter Choice (1-8): ");
scanf_s("%d", &choice);
switch(choice)
{
case 1: printf("Choice is 1 \n");
printf("Enter triangle height: ");
scanf_s("%f", &height);
printf("Enter triangle base: ");
scanf_s("%f", &base);
area = 0.5 * base * height;
printf("Triangle area: %.2f \n", area);
break;
case 2: printf("Choice is 2 \n");
printf("Enter length of the square's side: ");
scanf_s("%f", &length);
area = length * length;
printf("Square area: %.2f \n", area);
break;
case 3: printf("Choice is 3 \n");
printf("Enter rectangle height: ");
scanf_s("%f", &height);
printf("Enter rectangle width: ");
scanf_s("%f", &width);
area = height * width;
printf("Rectangle area: %.2f \n", area);
break;
case 4: printf("Choice is 4 \n");
printf("Enter parallelogram height: ");
scanf_s("%f", &height);
printf("Enter parallelogram base: ");
scanf_s("%f", &base);
area = base * height;
printf("Parallelogram area: %.2f \n", area);
break;
case 5: printf("Choice is 5 \n");
printf("Enter length of the top of the trapezoid: ");
scanf_s("%f", &length);
printf("Enter trapezoid base: ");
scanf_s("%f", &base);
printf("Enter trapezoid height: ");
scanf_s("%f", &height);
area = 0.5 * (length + base) * height;
printf("Trapezoid area: %.2f \n", area);
break;
case 6: printf("Choice is 6 \n");
printf("Enter circle radius: ");
scanf_s("%f", &radius);
area = 3.1415 * radius * radius;
printf("Circle area: %.2f \n", area);
break;
case 7: printf("Choice is 7 \n");
printf("Enter half the height of the ellipse: ");
scanf_s("%f", &height);
printf("Enter half the width of the ellipse: ");
scanf_s("%f", &width);
area = 3.1415 * height * width;
printf("Ellipse area: %.2f \n", area);
break;
case 8: printf("Choice is 8 \n");
printf("Enter sector radius: ");
scanf_s("%f", &radius);
printf("Enter sector angle: ");
scanf_s("%f", &angle);
area = 5.5 * radius * radius * angle;
printf("Sector area: %.2f \n", area);
break;
default: printf("That is not one of the options \n");
goto start;
break;
}
} | [
"noreply@github.com"
] | noreply@github.com |
4e6fbecf1dd032bcafb65fc7589ae20150e9a0d5 | 60a4435076ca3e699de9b1c2803d10583984997a | /code/Code/chapter_2/Structure/Structure/Structure.cpp | 8409fee737034a40b558fd2583de7d621c8f85c2 | [] | no_license | jisiksoft/big_number_calculation | 2a5689549dcf581d1ef57b6e0e97c79329bb58bb | 19fe14042eddc186a1cbb181bc05044de9ed25ac | refs/heads/master | 2021-01-10T09:10:06.103422 | 2015-12-05T10:36:11 | 2015-12-05T10:36:11 | 47,451,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | cpp | #include <stdio.h>
struct Point {
int x;
int y;
};
struct Rect {
Point ptLeftTop;
Point ptRightBottom;
} rect, *ptrRect;
int main()
{
rect.ptLeftTop.x = 10;
rect.ptLeftTop.y = 20;
rect.ptRightBottom.x = 100;
rect.ptRightBottom.y = 200;
ptrRect = ▭
printf("x1:%d, y1:%d, x2:%d, y2:%d \n",
ptrRect->ptLeftTop.x, ptrRect->ptLeftTop.y,
ptrRect->ptRightBottom.x, ptrRect->ptRightBottom.y);
printf("size of rect : %d \n", sizeof(rect));
printf("size of ptrRect: %d \n\n\n", sizeof(ptrRect));
} | [
"shkim@jisiksoft.com"
] | shkim@jisiksoft.com |
9ee405f33545c1f58d0dcc07f988773fbc45b3e6 | c0a56b0699450f2e01b84fa849e9d7fc62dff494 | /SalaryCalculator/mainwindow.h | 71741d37db6b6e92692168d2aa4174b24b124572 | [] | no_license | FuelRod/SalaryCalculator | a68f6d86891e3d48edf04b4e80d28395369561c0 | e9b5e207f1c82b9c457ca42e12e109bf801da5f8 | refs/heads/main | 2023-07-20T13:52:35.791092 | 2021-08-31T15:16:26 | 2021-08-31T15:16:26 | 401,452,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,355 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
//时间
#include <ctime>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public:
//单例
static MainWindow* GetIns();
static MainWindow* instance;
//变量
//工资(月薪
int monthSalary;
//设置时间
int start_h;
int start_m;
int end_h;
int end_m;
//函数
void Init();
//读取并设置ini
bool ReadAndSetIni();
//初始化ini
void InitIni();
//每秒更新
void Update();
//校验数据
bool CheckSalary(int salary);
bool CheckTime(int start_h,int start_m,int end_h,int end_m);
int a=0;
QPoint M_point;
private slots:
void on_setting_Button_clicked();
void on_exit_Button_clicked();
//??
void on_Drop_Button_clicked();
void on_Drop_Button_pressed();
void on_Drop_Button_released();
//面板点击/移动事件
void mousePressEvent(QMouseEvent *e);
void mouseMoveEvent(QMouseEvent *e);
//键盘点击事件
void keyPressEvent(QKeyEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"noreply@github.com"
] | noreply@github.com |
ab3ed9d4eb920c397ced171e3811289bf0d805a9 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/121/925/CWE78_OS_Command_Injection__wchar_t_file_popen_83.h | ba06279c9af5de3cbc8d387e5f7095d36aca38b6 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | h | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_file_popen_83.h
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-83.tmpl.h
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: file Read input from a file
* GoodSource: Fixed string
* Sinks: popen
* BadSink : Execute command in data using popen()
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define FULL_COMMAND L"%WINDIR%\\system32\\cmd.exe /c dir "
#else
#include <unistd.h>
#define FULL_COMMAND L"/bin/sh ls -la "
#endif
namespace CWE78_OS_Command_Injection__wchar_t_file_popen_83
{
#ifndef OMITBAD
class CWE78_OS_Command_Injection__wchar_t_file_popen_83_bad
{
public:
CWE78_OS_Command_Injection__wchar_t_file_popen_83_bad(wchar_t * dataCopy);
~CWE78_OS_Command_Injection__wchar_t_file_popen_83_bad();
private:
wchar_t * data;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE78_OS_Command_Injection__wchar_t_file_popen_83_goodG2B
{
public:
CWE78_OS_Command_Injection__wchar_t_file_popen_83_goodG2B(wchar_t * dataCopy);
~CWE78_OS_Command_Injection__wchar_t_file_popen_83_goodG2B();
private:
wchar_t * data;
};
#endif /* OMITGOOD */
}
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
d2d8c630d96e22ae6cd725e241fab64b706dc333 | cdb9eccfa7df8030da3925debe534a6904d4348a | /_attic_/ThreadId.cpp | 46fb822759855aadf6a7ca495e3944d12ba599f2 | [
"BSD-3-Clause"
] | permissive | BigJoe01/libcatid | 0242940ebdadb95b9926bda3882056c0f2dbbcde | dc4f6c827f2b7381d8be225cb7e5fac05e1a6ba7 | refs/heads/master | 2021-01-09T05:59:07.047128 | 2017-02-06T08:31:07 | 2017-02-06T08:31:07 | 80,881,522 | 0 | 0 | null | 2017-02-04T00:36:57 | 2017-02-04T00:36:57 | null | UTF-8 | C++ | false | false | 205 | cpp | #include <cat/threads/ThreadId.hpp>
#if defined(CAT_OS_WINDOWS)
#include <windows.h>
namespace cat {
u32 GetThreadId()
{
return GetCurrentThreadId();
}
} // namespace cat
#endif
| [
"mrcatid@204b7394-75af-11de-9510-cf8a13bd668e"
] | mrcatid@204b7394-75af-11de-9510-cf8a13bd668e |
cc760dc162964857b87015aa17379e883127db90 | dbcae57ecc5f8d1f7ad2552465834da2784edd3f | /HDU/hdu_1061.cpp | a678b3c366670276d8b79a2bb925901d229fd519 | [] | no_license | AmazingCaddy/acm-codelab | 13ccb2daa249f8df695fac5b7890e3f17bb40bf5 | e22d732d468b748ff12885aed623ea3538058c68 | refs/heads/master | 2021-01-23T02:53:50.313479 | 2014-09-29T14:11:12 | 2014-09-29T14:11:12 | 14,780,683 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | #include<iostream>
using namespace std;
typedef __int64 LL;
int num[10][7]={{1,0},{1,1},{4,6,2,4,8},{4,1,3,9,7},{2,6,4},
{1,5},{1,6},{4,1,7,9,3},{4,6,8,4,2},{2,1,9}};
int main( )
{
int n,t,ans;
scanf("%d",&t);
while( t-- )
{
scanf("%d",&n);
ans = n % 10;
ans = num[ans][n%num[ans][0]+1];
printf("%d\n",ans);
}
return 0;
}
| [
"ecnuwbwang@gmail.com"
] | ecnuwbwang@gmail.com |
5ee4b6b01ab370a88ac5ed14816610d1e39a868d | fdd9305c1969b3c0b814ded7af120601d17c9521 | /src/filedlg.cpp | ef8aeb7f6ffa97ccc8080ebbc31aa73e56b65c20 | [] | no_license | hgh086/iupNode | 7c1a47d93f7a2eae22e9a6c8c2952cfc8c3039f7 | 27d6fe0356fe6808858dd489200e4892eebe6d19 | refs/heads/master | 2021-01-10T10:03:33.599017 | 2015-10-27T09:53:43 | 2015-10-27T09:53:43 | 45,024,410 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,269 | cpp | #include "filedlg.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iupim.h>
namespace iupnode {
using v8::Local;
using v8::Object;
using v8::Isolate;
using v8::String;
using v8::Integer;
using v8::Undefined;
using v8::FunctionTemplate;
IFileDlg::IFileDlg()
{
hwnd = NULL;
}
IFileDlg::~IFileDlg() {}
void IFileDlg::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "IFileDlg"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "init", _init);
NODE_SET_PROTOTYPE_METHOD(tpl, "popup", _popup);
NODE_SET_PROTOTYPE_METHOD(tpl, "getValue", _getValue);
NODE_SET_PROTOTYPE_METHOD(tpl, "destroy", _destroy);
NODE_SET_METHOD(tpl, "extend", extend);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "IFileDlg"),tpl->GetFunction());
}
void IFileDlg::_init(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
IFileDlg* obj = new IFileDlg();
// Create Filedlg
obj->hwnd = IupFileDlg();
if (args.Length()>=1 && args[0]->IsNumber()) {
int ty = args[0]->Int32Value();
switch(ty) {
case 1:
IupSetStrAttribute(obj->hwnd,"DIALOGTYPE", "SAVE");
break;
case 2:
IupSetStrAttribute(obj->hwnd,"DIALOGTYPE", "DIR");
break;
default:
IupSetStrAttribute(obj->hwnd,"DIALOGTYPE", "OPEN");
break;
}
}
if (args.Length()>=2 && args[1]->IsString()) {
Local<String> tt = Local<String>::Cast(args[1]);
String::Utf8Value str(tt);
IupSetStrAttribute(obj->hwnd,"TITLE", *str);
}
if (args.Length()>=3 && args[2]->IsString()) {
Local<String> tt = Local<String>::Cast(args[2]);
String::Utf8Value str(tt);
IupSetStrAttribute(obj->hwnd,"FILTER", *str);
}
obj->Wrap(args.This());
args.GetReturnValue().Set(Undefined(isolate));
}
void IFileDlg::_popup(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
IFileDlg* ifd = ObjectWrap::Unwrap<IFileDlg>(args.Holder());
if (ifd != NULL) {
if (ifd->hwnd != NULL) {
IupPopup(ifd->hwnd, IUP_CURRENT, IUP_CURRENT);
}
}
args.GetReturnValue().Set(Undefined(isolate));
}
void IFileDlg::_getValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
IFileDlg* ifd = ObjectWrap::Unwrap<IFileDlg>(args.Holder());
if (ifd != NULL) {
if (ifd->hwnd != NULL) {
if (IupGetInt(ifd->hwnd, "STATUS") == -1) {
args.GetReturnValue().Set(String::NewFromUtf8(isolate,""));
} else {
char* sRet = IupGetAttribute(ifd->hwnd,"VALUE");
args.GetReturnValue().Set(String::NewFromUtf8(isolate,sRet));
}
} else {
args.GetReturnValue().Set(String::NewFromUtf8(isolate,""));
}
} else {
args.GetReturnValue().Set(String::NewFromUtf8(isolate,""));
}
}
void IFileDlg::_destroy(const v8::FunctionCallbackInfo<v8::Value>& args)
{
Isolate* isolate = args.GetIsolate();
IFileDlg* ifd = ObjectWrap::Unwrap<IFileDlg>(args.Holder());
if (ifd != NULL) {
if (ifd->hwnd != NULL) {
IupDestroy(ifd->hwnd);
ifd->hwnd = NULL;
}
}
args.GetReturnValue().Set(Undefined(isolate));
}
}
| [
"guanghuan@msn.com"
] | guanghuan@msn.com |
fba01cab7329f16302ddd6cb67be1b2a492622fe | 2ff43b5f55285bd9f0bc243ed81bfda1d75bdc27 | /8.其他/机器人抓取/重构/NCC/squirrel_perception_backup-hydro_dev/v4r/v4r/KeypointBase/FeatureDetector_K_HARRIS.hh | cf735068c7fb80a6081228a62bdb88ee9ab72688 | [] | no_license | Ivan-VV/3D-ObjectDetection-and-Pose-Estimation | 876d343aa5011228e15a43cb999586b09bfa313d | 4fbe1c32fcd0618ab237eaa12931626c8d88c4ac | refs/heads/master | 2022-02-20T03:27:58.829378 | 2019-06-17T06:51:48 | 2019-06-17T06:51:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,689 | hh | /**
* $Id$
*
* Copyright (c) 2014, Johann Prankl
* @author Johann Prankl (prankl@acin.tuwien.ac.at)
*/
#ifndef KP_FEATURE_DETECTOR_HARRIS_HH
#define KP_FEATURE_DETECTOR_HARRIS_HH
#include <opencv2/features2d/features2d.hpp>
#include "FeatureDetector.hh"
#include "ComputeImGDescOrientations.hh"
namespace kp
{
class FeatureDetector_K_HARRIS : public FeatureDetector
{
public:
class Parameter
{
public:
int winSize; // e.g. 32*32 window + 2px border = 34
int maxCorners;
double qualityLevel; // 0.0001
double minDistance;
bool computeDesc;
bool uprightDesc;
ComputeImGDescOrientations::Parameter goParam;
Parameter(int _winSize=34, int _maxCorners=5000, const double &_qualityLevel=0.0002,
const double &_minDistance=1., bool _computeDesc=true, bool _uprightDesc=false,
const ComputeImGDescOrientations::Parameter &_goParam=ComputeImGDescOrientations::Parameter())
: winSize(_winSize), maxCorners(_maxCorners), qualityLevel(_qualityLevel),
minDistance(_minDistance), computeDesc(_computeDesc), uprightDesc(_uprightDesc),
goParam(_goParam) {}
};
private:
Parameter param;
cv::Mat_<unsigned char> im_gray;
std::vector<cv::Point2f> pts;
ComputeImGDescOrientations::Ptr imGOri;
public:
FeatureDetector_K_HARRIS(const Parameter &_p=Parameter());
~FeatureDetector_K_HARRIS();
virtual void detect(const cv::Mat &image, std::vector<cv::KeyPoint> &keys);
typedef SmartPtr< ::kp::FeatureDetector_K_HARRIS> Ptr;
typedef SmartPtr< ::kp::FeatureDetector_K_HARRIS const> ConstPtr;
};
/*************************** INLINE METHODES **************************/
} //--END--
#endif
| [
"1253703632@qq.com"
] | 1253703632@qq.com |
4a52be0f18af0a604c046d3ddd658a5dd1c11cdf | a06a9ae73af6690fabb1f7ec99298018dd549bb7 | /_Library/_Include/boost/fusion/include/vector.hpp | dd7eed8245ca978f0bbb8728eb2be6be8809bbab | [
"BSL-1.0"
] | permissive | longstl/mus12 | f76de65cca55e675392eac162dcc961531980f9f | 9e1be111f505ac23695f7675fb9cefbd6fa876e9 | refs/heads/master | 2021-05-18T08:20:40.821655 | 2020-03-29T17:38:13 | 2020-03-29T17:38:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | hpp | /*=============================================================================
Copyright (c) 2001-2007 Joel de Guzman
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)
==============================================================================*/
#if !defined(FUSION_INCLUDE_VECTOR)
#define FUSION_INCLUDE_VECTOR
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/container/vector.hpp>
#endif
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
| [
"adm.fael.hs@gmail.com"
] | adm.fael.hs@gmail.com |
1aae9f9d801fe3fd022484344a053f62e4da4714 | 96ef7957046bcc79ceba7f3782115cbf5c2708d7 | /framework/T120.h | 462e1cea1817fb0e1d8d6ae510b78140b686109a | [] | no_license | martinjlowm/02393_tile_ping_pong | 36488dbb99c714abca20641d1fdca45c71eb84c7 | 28c0db200850ca41ec4a4b3b17fe68738b036d9d | refs/heads/master | 2020-12-07T02:23:26.759103 | 2015-04-27T17:20:48 | 2015-04-27T17:20:48 | 34,526,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | h | // note that your header files must be protected against multiple inclusion using the definition of a special identifier
// note that you also need the #endif at the end of the file
#ifndef ____TT120____
#define ____TT120____
#include "game.h"
#include "field.h"
class T120: public Wall // if you implement a Floor tile, replace "Wall" with "Floor"
{
public:
T120(ISceneManager* smgr,
IVideoDriver* driver,
int x, int y, playground pg) ;
virtual fieldtype getFieldType();
// you need to declare here all (virtual) functions that change with respect to parent class
// see example in testfiled.h and testfield.cpp
};
#endif
| [
"christianlaustsen@gmail.com"
] | christianlaustsen@gmail.com |
28f1f0a77b00f0bfe10fa3ed742f818605de3593 | be1943a37274791d9fa4a26e64c4becec48a8096 | /routines/lineq/cond/pbcon.cc | 1ccc0203d53be214e0d90bfd3b2963a07e841c2e | [
"MIT"
] | permissive | luiscarbonell/nlapack | d986c1470bc2c67110e8cefd7d37097630690421 | 99d17f92f8f9bada17a89f72e8cc55486d848102 | refs/heads/master | 2020-05-16T17:17:23.653113 | 2019-03-17T01:46:52 | 2019-03-17T01:46:52 | 183,190,225 | 1 | 0 | NOASSERTION | 2019-04-24T09:00:05 | 2019-04-24T09:00:02 | null | UTF-8 | C++ | false | false | 1,227 | cc | #include "routines.h"
void dpbcon(const v8::FunctionCallbackInfo<v8::Value>& info) {
char uplo = info[0]->Uint32Value();
lapack_int n = info[1]->Uint32Value();
lapack_int kd = info[2]->Uint32Value();
double *ab = reinterpret_cast<double*>(GET_CONTENTS(info[3].As<v8::Float64Array>()));
lapack_int ldab = info[4]->Uint32Value();
double anorm = info[5]->NumberValue();
double *rcond = reinterpret_cast<double*>(GET_CONTENTS(info[6].As<v8::Float64Array>()));
lapack_int i = LAPACKE_dpbcon(LAPACK_ROW_MAJOR, uplo, n, kd, ab, ldab, anorm, rcond);
info.GetReturnValue().Set(
v8::Number::New(info.GetIsolate(), i)
);
}
void spbcon(const v8::FunctionCallbackInfo<v8::Value>& info) {
char uplo = info[0]->Uint32Value();
lapack_int n = info[1]->Uint32Value();
lapack_int kd = info[2]->Uint32Value();
float *ab = reinterpret_cast<float*>(GET_CONTENTS(info[3].As<v8::Float64Array>()));
lapack_int ldab = info[4]->Uint32Value();
float anorm = info[5]->NumberValue();
float *rcond = reinterpret_cast<float*>(GET_CONTENTS(info[6].As<v8::Float64Array>()));
lapack_int i = LAPACKE_spbcon(LAPACK_ROW_MAJOR, uplo, n, kd, ab, ldab, anorm, rcond);
info.GetReturnValue().Set(
v8::Number::New(info.GetIsolate(), i)
);
}
| [
"gianoliomateo@gmail.com"
] | gianoliomateo@gmail.com |
875dec2e6f7ce3e37a09caf09d5df9dcfc0bb70e | ad4545a66a38524baca88b78233aa537d495b110 | /hm_3/Map/Map.h | 8b27eb6483d3e3df575eb21abdd54293ffefaaa1 | [] | no_license | kmac3063/Cpp_hm | 57eeb2bf8869dc99958cedaf0bc504173d81ed57 | a3f0d3f9358d070d68d061dac8fb161ecd5eb977 | refs/heads/master | 2023-02-18T22:57:27.941383 | 2019-12-26T04:21:43 | 2019-12-26T04:21:43 | 218,732,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | h | #pragma once
#include <set>
#include <vector>
#include "../GameObject/GameObject.h"
namespace Map {
class Map {
public:
void readMapFromFile(const int& levelId, std::vector<std::shared_ptr<GameObject::GameObject>>& objects);
int getWidth();
int getHeight();
void drawMap();
void drawObjects(const std::vector<std::shared_ptr<GameObject::GameObject>>&);
std::pair<int, int> getYXForDrawing();
int getLevelRequiredScore();
private:
int width = 0;
int height = 0;
int levelRequiredScore = 0;
std::set<std::pair<int, int>> filledCells;
std::vector<std::vector<char>> map;
};
} // namespace Map | [
"lantcov.iiu@students.dvfu.ru"
] | lantcov.iiu@students.dvfu.ru |
bcb55bbf139d0e0d7602cb28e347d4f942c180d5 | b143209309207fc44d019b34cd4c4b81ca44a53c | /src/intel/compiler/test_fs_cmod_propagation.cpp | 4215af1fb02b693fe00e7f517f11205ad30abd55 | [] | no_license | angeleo126/mesa19 | fa4d8cf58b4206760d7f6a65f4b62bccc6a6b7ec | f4f43fbb7adfa8c0cc9e3360fe48a7d4b92846be | refs/heads/main | 2023-03-09T01:05:09.098185 | 2021-02-19T06:39:56 | 2021-02-19T06:39:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,580 | cpp | /*
* Copyright © 2015 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include "brw_fs.h"
#include "brw_cfg.h"
#include "program/program.h"
using namespace brw;
class cmod_propagation_test : public ::testing::Test {
virtual void SetUp();
public:
struct brw_compiler *compiler;
struct gen_device_info *devinfo;
struct gl_context *ctx;
struct brw_wm_prog_data *prog_data;
struct gl_shader_program *shader_prog;
fs_visitor *v;
};
class cmod_propagation_fs_visitor : public fs_visitor
{
public:
cmod_propagation_fs_visitor(struct brw_compiler *compiler,
struct brw_wm_prog_data *prog_data,
nir_shader *shader)
: fs_visitor(compiler, NULL, NULL, NULL,
&prog_data->base, (struct gl_program *) NULL,
shader, 8, -1) {}
};
void cmod_propagation_test::SetUp()
{
ctx = (struct gl_context *)calloc(1, sizeof(*ctx));
compiler = (struct brw_compiler *)calloc(1, sizeof(*compiler));
devinfo = (struct gen_device_info *)calloc(1, sizeof(*devinfo));
compiler->devinfo = devinfo;
prog_data = ralloc(NULL, struct brw_wm_prog_data);
nir_shader *shader =
nir_shader_create(NULL, MESA_SHADER_FRAGMENT, NULL, NULL);
v = new cmod_propagation_fs_visitor(compiler, prog_data, shader);
devinfo->gen = 4;
}
static fs_inst *
instruction(bblock_t *block, int num)
{
fs_inst *inst = (fs_inst *)block->start();
for (int i = 0; i < num; i++) {
inst = (fs_inst *)inst->next;
}
return inst;
}
static bool
cmod_propagation(fs_visitor *v)
{
const bool print = getenv("TEST_DEBUG");
if (print) {
fprintf(stderr, "= Before =\n");
v->cfg->dump(v);
}
bool ret = v->opt_cmod_propagation();
if (print) {
fprintf(stderr, "\n= After =\n");
v->cfg->dump(v);
}
return ret;
}
TEST_F(cmod_propagation_test, basic)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
bld.ADD(dest, src0, src1);
bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add(8) dest src0 src1
* 1: cmp.ge.f0(8) null dest 0.0f
*
* = After =
* 0: add.ge.f0(8) dest src0 src1
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod);
}
TEST_F(cmod_propagation_test, cmp_nonzero)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg nonzero(brw_imm_f(1.0f));
bld.ADD(dest, src0, src1);
bld.CMP(bld.null_reg_f(), dest, nonzero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add(8) dest src0 src1
* 1: cmp.ge.f0(8) null dest 1.0f
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod);
}
TEST_F(cmod_propagation_test, non_cmod_instruction)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::uint_type);
fs_reg src0 = v->vgrf(glsl_type::uint_type);
fs_reg zero(brw_imm_ud(0u));
bld.FBL(dest, src0);
bld.CMP(bld.null_reg_ud(), dest, zero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: fbl(8) dest src0
* 1: cmp.ge.f0(8) null dest 0u
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_FBL, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod);
}
TEST_F(cmod_propagation_test, intervening_flag_write)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg src2 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
bld.ADD(dest, src0, src1);
bld.CMP(bld.null_reg_f(), src2, zero, BRW_CONDITIONAL_GE);
bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add(8) dest src0 src1
* 1: cmp.ge.f0(8) null src2 0.0f
* 2: cmp.ge.f0(8) null dest 0.0f
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod);
}
TEST_F(cmod_propagation_test, intervening_flag_read)
{
const fs_builder &bld = v->bld;
fs_reg dest0 = v->vgrf(glsl_type::float_type);
fs_reg dest1 = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg src2 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
bld.ADD(dest0, src0, src1);
set_predicate(BRW_PREDICATE_NORMAL, bld.SEL(dest1, src2, zero));
bld.CMP(bld.null_reg_f(), dest0, zero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add(8) dest0 src0 src1
* 1: (+f0) sel(8) dest1 src2 0.0f
* 2: cmp.ge.f0(8) null dest0 0.0f
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_OPCODE_SEL, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod);
}
TEST_F(cmod_propagation_test, intervening_dest_write)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::vec4_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg src2 = v->vgrf(glsl_type::vec2_type);
fs_reg zero(brw_imm_f(0.0f));
bld.ADD(offset(dest, bld, 2), src0, src1);
bld.emit(SHADER_OPCODE_TEX, dest, src2)
->size_written = 4 * REG_SIZE;
bld.CMP(bld.null_reg_f(), offset(dest, bld, 2), zero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add(8) dest+2 src0 src1
* 1: tex(8) rlen 4 dest+0 src2
* 2: cmp.ge.f0(8) null dest+2 0.0f
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(SHADER_OPCODE_TEX, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod);
}
TEST_F(cmod_propagation_test, intervening_flag_read_same_value)
{
const fs_builder &bld = v->bld;
fs_reg dest0 = v->vgrf(glsl_type::float_type);
fs_reg dest1 = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg src2 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
set_condmod(BRW_CONDITIONAL_GE, bld.ADD(dest0, src0, src1));
set_predicate(BRW_PREDICATE_NORMAL, bld.SEL(dest1, src2, zero));
bld.CMP(bld.null_reg_f(), dest0, zero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add.ge.f0(8) dest0 src0 src1
* 1: (+f0) sel(8) dest1 src2 0.0f
* 2: cmp.ge.f0(8) null dest0 0.0f
*
* = After =
* 0: add.ge.f0(8) dest0 src0 src1
* 1: (+f0) sel(8) dest1 src2 0.0f
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_SEL, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate);
}
TEST_F(cmod_propagation_test, negate)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
bld.ADD(dest, src0, src1);
dest.negate = true;
bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add(8) dest src0 src1
* 1: cmp.ge.f0(8) null -dest 0.0f
*
* = After =
* 0: add.le.f0(8) dest src0 src1
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_LE, instruction(block0, 0)->conditional_mod);
}
TEST_F(cmod_propagation_test, movnz)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.CMP(dest, src0, src1, BRW_CONDITIONAL_GE);
set_condmod(BRW_CONDITIONAL_NZ,
bld.MOV(bld.null_reg_f(), dest));
/* = Before =
*
* 0: cmp.ge.f0(8) dest src0 src1
* 1: mov.nz.f0(8) null dest
*
* = After =
* 0: cmp.ge.f0(8) dest src0 src1
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod);
}
TEST_F(cmod_propagation_test, different_types_cmod_with_zero)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::int_type);
fs_reg src0 = v->vgrf(glsl_type::int_type);
fs_reg src1 = v->vgrf(glsl_type::int_type);
fs_reg zero(brw_imm_f(0.0f));
bld.ADD(dest, src0, src1);
bld.CMP(bld.null_reg_f(), retype(dest, BRW_REGISTER_TYPE_F), zero,
BRW_CONDITIONAL_GE);
/* = Before =
*
* 0: add(8) dest:D src0:D src1:D
* 1: cmp.ge.f0(8) null:F dest:F 0.0f
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod);
}
TEST_F(cmod_propagation_test, andnz_one)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::int_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
fs_reg one(brw_imm_d(1));
bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L);
set_condmod(BRW_CONDITIONAL_NZ,
bld.AND(bld.null_reg_d(), dest, one));
/* = Before =
* 0: cmp.l.f0(8) dest:F src0:F 0F
* 1: and.nz.f0(8) null:D dest:D 1D
*
* = After =
* 0: cmp.l.f0(8) dest:F src0:F 0F
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
EXPECT_TRUE(retype(dest, BRW_REGISTER_TYPE_F)
.equals(instruction(block0, 0)->dst));
}
TEST_F(cmod_propagation_test, andnz_non_one)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::int_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
fs_reg nonone(brw_imm_d(38));
bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L);
set_condmod(BRW_CONDITIONAL_NZ,
bld.AND(bld.null_reg_d(), dest, nonone));
/* = Before =
* 0: cmp.l.f0(8) dest:F src0:F 0F
* 1: and.nz.f0(8) null:D dest:D 38D
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_AND, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NZ, instruction(block0, 1)->conditional_mod);
}
TEST_F(cmod_propagation_test, andz_one)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::int_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg zero(brw_imm_f(0.0f));
fs_reg one(brw_imm_d(1));
bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L);
set_condmod(BRW_CONDITIONAL_Z,
bld.AND(bld.null_reg_d(), dest, one));
/* = Before =
* 0: cmp.l.f0(8) dest:F src0:F 0F
* 1: and.z.f0(8) null:D dest:D 1D
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_AND, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_EQ, instruction(block0, 1)->conditional_mod);
}
TEST_F(cmod_propagation_test, add_not_merge_with_compare)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.ADD(dest, src0, src1);
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* The addition and the implicit subtraction in the compare do not compute
* related values.
*
* = Before =
* 0: add(8) dest:F src0:F src1:F
* 1: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 1)->conditional_mod);
}
TEST_F(cmod_propagation_test, subtract_merge_with_compare)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.ADD(dest, src0, negate(src1));
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* = Before =
* 0: add(8) dest:F src0:F -src1:F
* 1: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* 0: add.l.f0(8) dest:F src0:F -src1:F
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
}
TEST_F(cmod_propagation_test, subtract_immediate_merge_with_compare)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg one(brw_imm_f(1.0f));
fs_reg negative_one(brw_imm_f(-1.0f));
bld.ADD(dest, src0, negative_one);
bld.CMP(bld.null_reg_f(), src0, one, BRW_CONDITIONAL_NZ);
/* = Before =
* 0: add(8) dest:F src0:F -1.0f
* 1: cmp.nz.f0(8) null:F src0:F 1.0f
*
* = After =
* 0: add.nz.f0(8) dest:F src0:F -1.0f
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NZ, instruction(block0, 0)->conditional_mod);
}
TEST_F(cmod_propagation_test, subtract_merge_with_compare_intervening_add)
{
const fs_builder &bld = v->bld;
fs_reg dest0 = v->vgrf(glsl_type::float_type);
fs_reg dest1 = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.ADD(dest0, src0, negate(src1));
bld.ADD(dest1, src0, src1);
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* = Before =
* 0: add(8) dest0:F src0:F -src1:F
* 1: add(8) dest1:F src0:F src1:F
* 2: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* 0: add.l.f0(8) dest0:F src0:F -src1:F
* 1: add(8) dest1:F src0:F src1:F
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 1)->conditional_mod);
}
TEST_F(cmod_propagation_test, subtract_not_merge_with_compare_intervening_partial_write)
{
const fs_builder &bld = v->bld;
fs_reg dest0 = v->vgrf(glsl_type::float_type);
fs_reg dest1 = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.ADD(dest0, src0, negate(src1));
set_predicate(BRW_PREDICATE_NORMAL, bld.ADD(dest1, src0, negate(src1)));
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* = Before =
* 0: add(8) dest0:F src0:F -src1:F
* 1: (+f0) add(8) dest1:F src0:F -src1:F
* 2: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 1)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 2)->conditional_mod);
}
TEST_F(cmod_propagation_test, subtract_not_merge_with_compare_intervening_add)
{
const fs_builder &bld = v->bld;
fs_reg dest0 = v->vgrf(glsl_type::float_type);
fs_reg dest1 = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.ADD(dest0, src0, negate(src1));
set_condmod(BRW_CONDITIONAL_EQ, bld.ADD(dest1, src0, src1));
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* = Before =
* 0: add(8) dest0:F src0:F -src1:F
* 1: add.z.f0(8) dest1:F src0:F src1:F
* 2: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_EQ, instruction(block0, 1)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 2)->conditional_mod);
}
TEST_F(cmod_propagation_test, add_merge_with_compare)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.ADD(dest, src0, src1);
bld.CMP(bld.null_reg_f(), src0, negate(src1), BRW_CONDITIONAL_L);
/* = Before =
* 0: add(8) dest:F src0:F src1:F
* 1: cmp.l.f0(8) null:F src0:F -src1:F
*
* = After =
* 0: add.l.f0(8) dest:F src0:F src1:F
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
}
TEST_F(cmod_propagation_test, negative_subtract_merge_with_compare)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
bld.ADD(dest, src1, negate(src0));
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* The result of the subtract is the negatiion of the result of the
* implicit subtract in the compare, so the condition must change.
*
* = Before =
* 0: add(8) dest:F src1:F -src0:F
* 1: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* 0: add.g.f0(8) dest:F src0:F -src1:F
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(0, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_G, instruction(block0, 0)->conditional_mod);
}
TEST_F(cmod_propagation_test, subtract_delete_compare)
{
const fs_builder &bld = v->bld;
fs_reg dest = v->vgrf(glsl_type::float_type);
fs_reg dest1 = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
fs_reg src2 = v->vgrf(glsl_type::float_type);
set_condmod(BRW_CONDITIONAL_L, bld.ADD(dest, src0, negate(src1)));
set_predicate(BRW_PREDICATE_NORMAL, bld.MOV(dest1, src2));
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* = Before =
* 0: add.l.f0(8) dest0:F src0:F -src1:F
* 1: (+f0) mov(0) dest1:F src2:F
* 2: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* 0: add.l.f0(8) dest:F src0:F -src1:F
* 1: (+f0) mov(0) dest1:F src2:F
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_MOV, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate);
}
TEST_F(cmod_propagation_test, subtract_delete_compare_derp)
{
const fs_builder &bld = v->bld;
fs_reg dest0 = v->vgrf(glsl_type::float_type);
fs_reg dest1 = v->vgrf(glsl_type::float_type);
fs_reg src0 = v->vgrf(glsl_type::float_type);
fs_reg src1 = v->vgrf(glsl_type::float_type);
set_condmod(BRW_CONDITIONAL_L, bld.ADD(dest0, src0, negate(src1)));
set_predicate(BRW_PREDICATE_NORMAL, bld.ADD(dest1, negate(src0), src1));
bld.CMP(bld.null_reg_f(), src0, src1, BRW_CONDITIONAL_L);
/* = Before =
* 0: add.l.f0(8) dest0:F src0:F -src1:F
* 1: (+f0) add(0) dest1:F -src0:F src1:F
* 2: cmp.l.f0(8) null:F src0:F src1:F
*
* = After =
* 0: add.l.f0(8) dest0:F src0:F -src1:F
* 1: (+f0) add(0) dest1:F -src0:F src1:F
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(2, block0->end_ip);
EXPECT_TRUE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod);
EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate);
}
TEST_F(cmod_propagation_test, signed_unsigned_comparison_mismatch)
{
const fs_builder &bld = v->bld;
fs_reg dest0 = v->vgrf(glsl_type::int_type);
fs_reg src0 = v->vgrf(glsl_type::int_type);
src0.type = BRW_REGISTER_TYPE_W;
bld.ASR(dest0, negate(src0), brw_imm_d(15));
bld.CMP(bld.null_reg_ud(), retype(dest0, BRW_REGISTER_TYPE_UD),
brw_imm_ud(0u), BRW_CONDITIONAL_LE);
/* = Before =
* 0: asr(8) dest:D -src0:W 15D
* 1: cmp.le.f0(8) null:UD dest:UD 0UD
*
* = After =
* (no changes)
*/
v->calculate_cfg();
bblock_t *block0 = v->cfg->blocks[0];
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_FALSE(cmod_propagation(v));
EXPECT_EQ(0, block0->start_ip);
EXPECT_EQ(1, block0->end_ip);
EXPECT_EQ(BRW_OPCODE_ASR, instruction(block0, 0)->opcode);
EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode);
EXPECT_EQ(BRW_CONDITIONAL_LE, instruction(block0, 1)->conditional_mod);
}
| [
"angeleo@126.com"
] | angeleo@126.com |
82b984c2d069138d3101a582fcc6a6a8ec9bcb16 | a436ce09ad45aba66f29093f09bd046e6f2b1dc4 | /Troubleshooting/MaxDuino_v1.35s/menu.ino | 10f4649c6e96b276f0fda464f8f371ecf4b96808 | [] | no_license | rcmolina/MaxDuino_BETA | 12de7d9479c798a178e68af39086806ab75142ae | 781aab0899ee26bcd9259a5c1f7788a283111045 | refs/heads/master | 2023-09-03T22:32:40.799909 | 2023-08-23T10:50:19 | 2023-08-23T10:50:19 | 128,559,979 | 2 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 11,148 | ino | /*
void menuMode()
{
//Return to root of the SD card.
sd.chdir(true);
getMaxFile();
currentFile=1;
seekFile(currentFile);
while(digitalRead(btnMselect)==LOW) {
//prevent button repeats by waiting until the button is released.
delay(50);
}
}
*/
/**************************************************************
* Casduino Menu Code:
* Menu Button (was motor controll button) opens menu
* up/down move through menu, play select, stop back
* Menu Options:
* Baud:
* 1200
* 2400
* 3600
* 3850
*
* MotorControl:
* On
* Off
*
* Save settings to eeprom on exit.
*/
void menuMode()
{
byte lastbtn=true;
byte menuItem=0;
byte subItem=0;
byte updateScreen=true;
while(digitalRead(btnStop)==HIGH || lastbtn)
{
if(updateScreen) {
printtextF(PSTR("Menu"),0);
switch(menuItem) {
case 0:
printtextF(PSTR("Baud Rate ?"),lineaxy);
break;
// #ifndef Use_UEF
case 1:
printtextF(PSTR("Motor Ctrl ?"),lineaxy);
break;
case 2:
printtextF(PSTR("TSXspeedup ?"),lineaxy);
break;
case 3:
printtextF(PSTR("Skip BLK:2A ?"),lineaxy);
break;
// #endif
}
updateScreen=false;
}
if(digitalRead(btnDown)==LOW && !lastbtn){
#ifndef Use_UEF
if(menuItem<3) menuItem+=1;
#endif
#ifdef Use_UEF
if(menuItem<2) menuItem+=1;
#endif
lastbtn=true;
updateScreen=true;
}
if(digitalRead(btnUp)==LOW && !lastbtn) {
if(menuItem>0) menuItem+=-1;
lastbtn=true;
updateScreen=true;
}
if(digitalRead(btnPlay)==LOW && !lastbtn) {
switch(menuItem){
case 0:
subItem=0;
updateScreen=true;
lastbtn=true;
while(digitalRead(btnStop)==HIGH || lastbtn) {
if(updateScreen) {
printtextF(PSTR("Baud Rate"),0);
switch(subItem) {
case 0:
printtextF(PSTR("1200"),lineaxy);
if(BAUDRATE==1200) printtextF(PSTR("1200 *"),lineaxy);
break;
case 1:
printtextF(PSTR("2400"),lineaxy);
if(BAUDRATE==2400) printtextF(PSTR("2400 *"),lineaxy);
break;
case 2:
printtextF(PSTR("3600"),lineaxy);
if(BAUDRATE==3600) printtextF(PSTR("3600 *"),lineaxy);
break;
case 3:
printtextF(PSTR("3850"),lineaxy);
if(BAUDRATE==3850) printtextF(PSTR("3850 *"),lineaxy);
break;
}
updateScreen=false;
}
if(digitalRead(btnDown)==LOW && !lastbtn){
if(subItem<3) subItem+=1;
lastbtn=true;
updateScreen=true;
}
if(digitalRead(btnUp)==LOW && !lastbtn) {
if(subItem>0) subItem+=-1;
lastbtn=true;
updateScreen=true;
}
if(digitalRead(btnPlay)==LOW && !lastbtn) {
switch(subItem) {
case 0:
BAUDRATE=1200;
break;
case 1:
BAUDRATE=2400;
break;
case 2:
BAUDRATE=3600;
break;
case 3:
BAUDRATE=3850;
break;
}
updateScreen=true;
#ifdef OLED1306
OledStatusLine();
#endif
lastbtn=true;
}
if(digitalRead(btnDown) && digitalRead(btnUp) && digitalRead(btnPlay) && digitalRead(btnStop)) lastbtn=false;
}
lastbtn=true;
updateScreen=true;
break;
case 1:
subItem=0;
updateScreen=true;
lastbtn=true;
while(digitalRead(btnStop)==HIGH || lastbtn) {
if(updateScreen) {
printtextF(PSTR("Motor Ctrl"),0);
if(mselectMask==0) printtextF(PSTR("off *"),lineaxy);
else printtextF(PSTR("ON *"),lineaxy);
/* switch(subItem) {
case 0:
printtextF(PSTR("off"),lineaxy);
if(mselectMask==0) printtextF(PSTR("off *"),lineaxy);
break;
case 1:
printtextF(PSTR("ON"),lineaxy);
if(mselectMask==1) printtextF(PSTR("ON *"),lineaxy);
break;
} */
updateScreen=false;
}
/*
if(digitalRead(btnDown)==LOW && !lastbtn){
if(subItem<1) subItem+=1;
lastbtn=true;
updateScreen=true;
}
if(digitalRead(btnUp)==LOW && !lastbtn) {
if(subItem>0) subItem+=-1;
lastbtn=true;
updateScreen=true;
} */
if(digitalRead(btnPlay)==LOW && !lastbtn) {
mselectMask= !mselectMask;
/* switch(subItem) {
case 0:
mselectMask=0;
break;
case 1:
mselectMask=1;
break;
} */
lastbtn=true;
updateScreen=true;
#ifdef OLED1306
OledStatusLine();
#endif
}
if(digitalRead(btnDown) && digitalRead(btnUp) && digitalRead(btnPlay) && digitalRead(btnStop)) lastbtn=false;
}
lastbtn=true;
updateScreen=true;
break;
case 2:
subItem=0;
updateScreen=true;
lastbtn=true;
while(digitalRead(btnStop)==HIGH || lastbtn) {
if(updateScreen) {
printtextF(PSTR("TSXspeedup"),0);
if(TSXspeedup==0) printtextF(PSTR("off *"),lineaxy);
else printtextF(PSTR("ON *"),lineaxy);
/* switch(subItem) {
case 0:
printtextF(PSTR("off"),1);
if(TSXspeedup==0) printtextF(PSTR("off *"),1);
break;
case 1:
printtextF(PSTR("ON"),1);
if(TSXspeedup==1) printtextF(PSTR("ON *"),1);
break;
} */
updateScreen=false;
}
/*
if(digitalRead(btnDown)==LOW && !lastbtn){
if(subItem<1) subItem+=1;
lastbtn=true;
updateScreen=true;
}
if(digitalRead(btnUp)==LOW && !lastbtn) {
if(subItem>0) subItem+=-1;
lastbtn=true;
updateScreen=true;
} */
if(digitalRead(btnPlay)==LOW && !lastbtn) {
TSXspeedup = !TSXspeedup;
/* switch(subItem) {
case 0:
TSXspeedup=0;
break;
case 1:
TSXspeedup=1;
break;
} */
lastbtn=true;
updateScreen=true;
#ifdef OLED1306
OledStatusLine();
#endif
}
if(digitalRead(btnDown) && digitalRead(btnUp) && digitalRead(btnPlay) && digitalRead(btnStop)) lastbtn=false;
}
lastbtn=true;
updateScreen=true;
break;
#ifndef Use_UEF
case 3:
subItem=0;
updateScreen=true;
lastbtn=true;
while(digitalRead(btnStop)==HIGH || lastbtn) {
if(updateScreen) {
printtextF(PSTR("Skip BLK:2A"),0);
if(skip2A==0) printtextF(PSTR("off *"),lineaxy);
else printtextF(PSTR("ON *"),lineaxy);
/* switch(subItem) {
case 0:
printtextF(PSTR("off"),lineaxy);
if(skip2A==0) printtextF(PSTR("off *"),lineaxy);
break;
case 1:
printtextF(PSTR("ON"),lineaxy);
if(skip2A==1) printtextF(PSTR("ON *"),lineaxy);
break;
} */
updateScreen=false;
}
/*
if(digitalRead(btnDown)==LOW && !lastbtn){
if(subItem<1) subItem+=1;
lastbtn=true;
updateScreen=true;
}
if(digitalRead(btnUp)==LOW && !lastbtn) {
if(subItem>0) subItem+=-1;
lastbtn=true;
updateScreen=true;
} */
if(digitalRead(btnPlay)==LOW && !lastbtn) {
skip2A = !skip2A;
/* switch(subItem) {
case 0:
skip2A=0;
break;
case 1:
skip2A=1;
break;
} */
lastbtn=true;
updateScreen=true;
#ifdef OLED1306
// OledStatusLine();
#endif
}
if(digitalRead(btnDown) && digitalRead(btnUp) && digitalRead(btnPlay) && digitalRead(btnStop)) lastbtn=false;
}
lastbtn=true;
updateScreen=true;
break;
#endif
}
}
if(digitalRead(btnDown) && digitalRead(btnUp) && digitalRead(btnPlay) && digitalRead(btnStop)) lastbtn=false;
}
updateEEPROM();
debounce(btnStop);
/* while(digitalRead(btnStop)==LOW) {
//prevent button repeats by waiting until the button is released.
delay(50);
}
*/
}
void updateEEPROM()
{
/* Setting Byte:
* bit 0: 1200
* bit 1: 2400
* bit 2: 3600
* bit 3: 3850
* bit 4: n/a
* bit 5: BLK_2A control
* bit 6: TSXspeedup
* bit 7: Motor control
*/
byte settings=0;
switch(BAUDRATE) {
case 1200:
settings |=1;
break;
case 2400:
settings |=2;
break;
case 3600:
settings |=4;
break;
case 3850:
settings |=8;
break;
}
if(mselectMask) settings |=128;
if(TSXspeedup) settings |=64;
#ifndef Use_UEF
if(skip2A) settings |=32;
#endif
EEPROM.put(1023,settings);
setBaud();
}
void loadEEPROM()
{
byte settings=0;
EEPROM.get(1023,settings);
if(!settings) return;
if(bitRead(settings,7)) {
mselectMask=1;
} else {
mselectMask=0;
}
if(bitRead(settings,6)) {
TSXspeedup=1;
} else {
TSXspeedup=0;
}
#ifndef Use_UEF
if(bitRead(settings,5)) {
skip2A=1;
} else {
skip2A=0;
}
#endif
if(bitRead(settings,0)) {
BAUDRATE=1200;
}
if(bitRead(settings,1)) {
BAUDRATE=2400;
}
if(bitRead(settings,2)) {
BAUDRATE=3600;
}
if(bitRead(settings,3)) {
BAUDRATE=3850;
}
setBaud();
//UniSetup();
}
| [
"noreply@github.com"
] | noreply@github.com |
40262327b8ac86d2998c345c900c22f11e92b367 | 0bd1265abbec9fa8b1ecca2b2e9bd48572ffaffc | /include/llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h | af824694fd6dc9ca2ad2e014a106e225039cac6b | [] | no_license | BenQuickDeNN/Kaleidoscope | 2daa74aaa1ec82866d4c4e8b72c68dd5a7ce803a | 573b769ecc1b78f1ad9d2fd0a68978028b528e14 | refs/heads/master | 2022-10-06T21:51:10.741879 | 2020-06-11T02:19:48 | 2020-06-11T02:19:48 | 208,954,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,261 | h | //===- JITTargetMachineBuilder.h - Build TargetMachines for JIT -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// A utitily for building TargetMachines for JITs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_EXECUTIONENGINE_ORC_JITTARGETMACHINEBUILDER_H
#define LLVM_EXECUTIONENGINE_ORC_JITTARGETMACHINEBUILDER_H
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Error.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <memory>
#include <string>
#include <vector>
namespace llvm {
namespace orc {
/// A utility class for building TargetMachines for JITs.
class JITTargetMachineBuilder {
public:
/// Create a JITTargetMachineBuilder based on the given triple.
///
/// Note: TargetOptions is default-constructed, then EmulatedTLS and
/// ExplicitEmulatedTLS are set to true. If EmulatedTLS is not
/// required, these values should be reset before calling
/// createTargetMachine.
JITTargetMachineBuilder(Triple TT);
/// Create a JITTargetMachineBuilder for the host system.
///
/// Note: TargetOptions is default-constructed, then EmulatedTLS and
/// ExplicitEmulatedTLS are set to true. If EmulatedTLS is not
/// required, these values should be reset before calling
/// createTargetMachine.
static Expected<JITTargetMachineBuilder> detectHost();
/// Create a TargetMachine.
///
/// This operation will fail if the requested target is not registered,
/// in which case see llvm/Support/TargetSelect.h. To JIT IR the Target and
/// the target's AsmPrinter must both be registered. To JIT assembly
/// (including inline and module level assembly) the target's AsmParser must
/// also be registered.
Expected<std::unique_ptr<TargetMachine>> createTargetMachine();
/// Get the default DataLayout for the target.
///
/// Note: This is reasonably expensive, as it creates a temporary
/// TargetMachine instance under the hood. It is only suitable for use during
/// JIT setup.
Expected<DataLayout> getDefaultDataLayoutForTarget() {
auto TM = createTargetMachine();
if (!TM)
return TM.takeError();
return (*TM)->createDataLayout();
}
/// Set the CPU string.
JITTargetMachineBuilder &setCPU(std::string CPU) {
this->CPU = std::move(CPU);
return *this;
}
/// Set the relocation model.
JITTargetMachineBuilder &setRelocationModel(Optional<Reloc::Model> RM) {
this->RM = std::move(RM);
return *this;
}
/// Set the code model.
JITTargetMachineBuilder &setCodeModel(Optional<CodeModel::Model> CM) {
this->CM = std::move(CM);
return *this;
}
/// Set the LLVM CodeGen optimization level.
JITTargetMachineBuilder &setCodeGenOptLevel(CodeGenOpt::Level OptLevel) {
this->OptLevel = OptLevel;
return *this;
}
/// Add subtarget features.
JITTargetMachineBuilder &
addFeatures(const std::vector<std::string> &FeatureVec);
/// Access subtarget features.
SubtargetFeatures &getFeatures() { return Features; }
/// Access subtarget features.
const SubtargetFeatures &getFeatures() const { return Features; }
/// Access TargetOptions.
TargetOptions &getOptions() { return Options; }
/// Access TargetOptions.
const TargetOptions &getOptions() const { return Options; }
/// Access Triple.
Triple &getTargetTriple() { return TT; }
/// Access Triple.
const Triple &getTargetTriple() const { return TT; }
private:
Triple TT;
std::string CPU;
SubtargetFeatures Features;
TargetOptions Options;
Optional<Reloc::Model> RM;
Optional<CodeModel::Model> CM;
CodeGenOpt::Level OptLevel = CodeGenOpt::None;
};
} // end namespace orc
} // end namespace llvm
#endif // LLVM_EXECUTIONENGINE_ORC_JITTARGETMACHINEBUILDER_H
| [
"benquickdenn@foxmail.com"
] | benquickdenn@foxmail.com |
ddd2e26f166b0a73ad50dac55dda27a1e87b2504 | 8c76bae46db42fa6c282fa591f1072b204b8e536 | /dep/tclap/tclap/CmdLineOutput.h | c0262784201d0051c4b53d2a68c29a44068a3c69 | [
"MIT"
] | permissive | cantordust/cortex | 77acde5423c861bd27d090f67d100e4d1842a07c | 0afe4b8c8c3e1b103541188301c3f445ee5d165d | refs/heads/master | 2023-04-11T15:35:52.514106 | 2017-11-30T06:04:52 | 2017-11-30T06:04:52 | 61,293,678 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,924 | h |
/******************************************************************************
*
* file: CmdLineOutput.h
*
* Copyright (c) 2004, Michael E. Smoot
* All rights reverved.
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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 State 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 TCLAP_CMDLINEOUTPUT_H
#define TCLAP_CMDLINEOUTPUT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <algorithm>
namespace TCLAP {
class CmdLineInterface;
class ArgException;
/**
* The interface that any output object must implement.
*/
class CmdLineOutput
{
public:
/**
* Virtual destructor.
*/
virtual ~CmdLineOutput() {}
/**
* Generates some sort of output for the USAGE.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c)=0;
/**
* Generates some sort of output for the version.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c)=0;
/**
* Generates some sort of output for a failure.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure( CmdLineInterface& c,
ArgException& e )=0;
};
} //namespace TCLAP
#endif
| [
"1425730-cantordust@users.noreply.gitlab.com"
] | 1425730-cantordust@users.noreply.gitlab.com |
fe97abcd0d1f61b6f3b40a078ddcdd3fbae58cbe | 946e7a10da7406f8719de0011f300b5da86ffece | /Breakout/Breakout/Main_Menu.cpp | 6a31833ded953f7cd6347c0fcf8ca32e3829cae0 | [] | no_license | JacquesJnr/GAME-230-Breakout | 8af2cea836cae94b5466a61f50fcd9842ff9b96a | b074dc9bc4fd5075c1c4170d30d5e6115a16e8e5 | refs/heads/master | 2023-02-03T16:17:13.604935 | 2020-12-22T00:05:46 | 2020-12-22T00:05:46 | 322,798,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23 | cpp | #include "Main_Menu.h"
| [
"jacquesvisserjnr@gmail.com"
] | jacquesvisserjnr@gmail.com |
645ad9c2230bf001dc49cf22a5f4ffb3fdded81b | 5a9b14b0335c540e09fbb98f9c22a43622fd720d | /CSE 335/SouthParkAnimationUI/Part2/CanadianExperience/Testing/CPolyDrawableTest.cpp | b236d0c176a66ea32ff601a03053a821e9920bf9 | [] | no_license | chas-bean/SchoolRepo | fc16ae06663afd2d94465f1fa1c96703475dddf7 | bb29ed7a808655a7d1137aafd90a0497ddaee373 | refs/heads/master | 2023-01-11T19:56:00.912595 | 2015-10-13T13:54:39 | 2015-10-13T13:54:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,762 | cpp | #include "stdafx.h"
#include "CppUnitTest.h"
#include "Actor.h"
#include "Picture.h"
#include "PolyDrawable.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
using namespace Gdiplus;
namespace Testing
{
TEST_CLASS(CPolyDrawableTest)
{
public:
/** \brief Function for determining if two colors are the same */
bool ColorsAreEqual(Color color1, Color color2)
{
return (color1.GetValue() == color2.GetValue());
}
TEST_METHOD(TestCPolyDrawableConstructor)
{
CPolyDrawable drawable(wstring(L"Box"));
Assert::AreEqual(wstring(L"Box"), drawable.GetName());
}
TEST_METHOD(TestCPolyDrawableColor)
{
CPolyDrawable drawable(wstring(L"Tripoint"));
Assert::IsTrue(ColorsAreEqual(Color::Black, drawable.GetColor()));
drawable.SetColor(Color::Purple);
Assert::IsTrue(ColorsAreEqual(Color::Purple, drawable.GetColor()));
}
/** This tests that the animation of the rotation of a drawable works */
TEST_METHOD(TestCPolyDrawableAnimation)
{
// Create a picture object
auto picture = make_shared<CPicture>();
// Create an actor and add it to the picture
auto actor = make_shared<CActor>(L"Actor");
// Create a drawable for the actor
auto drawable = make_shared<CPolyDrawable>(L"Drawable");
actor->SetRoot(drawable);
actor->AddDrawable(drawable);
picture->AddActor(actor);
auto channel = drawable->GetAngleChannel();
// First we will ensure it works with no keyframes set
picture->SetAnimationTime(0);
drawable->SetRotation(1.33);
// The channel should not be valid
Assert::IsFalse(channel->IsValid());
// Getting a keyframe should not chpoint the point
actor->GetKeyframe();
Assert::AreEqual(1.33, drawable->GetRotation(), 0.00001);
// Now we'll set one keyframe and see if that works
picture->SetAnimationTime(1.5);
drawable->SetRotation(2.7);
actor->SetKeyframe();
// Change point
drawable->SetRotation(0.3);
Assert::AreEqual(0.3, drawable->GetRotation(), 0.00001);
// Wherever we move, now, the keyframe point should be used
picture->SetAnimationTime(0);
Assert::AreEqual(2.7, drawable->GetRotation(), 0.00001);
drawable->SetRotation(0.3);
picture->SetAnimationTime(1.5);
Assert::AreEqual(2.7, drawable->GetRotation(), 0.00001);
drawable->SetRotation(0.3);
picture->SetAnimationTime(3);
Assert::AreEqual(2.7, drawable->GetRotation(), 0.00001);
// We'll set a second keyframe and see if that works
picture->SetAnimationTime(3.0);
drawable->SetRotation(-1.8);
actor->SetKeyframe();
// Test before the keyframes
drawable->SetRotation(0.3);
picture->SetAnimationTime(0);
Assert::AreEqual(2.7, drawable->GetRotation(), 0.00001);
// Test at first keyframe
drawable->SetRotation(0.3);
picture->SetAnimationTime(1.5);
Assert::AreEqual(2.7, drawable->GetRotation(), 0.00001);
// Test at second keyframe
drawable->SetRotation(0.3);
picture->SetAnimationTime(3.0);
Assert::AreEqual(-1.8, drawable->GetRotation(), 0.00001);
// Test after second keyframe
drawable->SetRotation(0.3);
picture->SetAnimationTime(4);
Assert::AreEqual(-1.8, drawable->GetRotation(), 0.00001);
// Test between the two keyframs
drawable->SetRotation(0.3);
picture->SetAnimationTime(2.25); // Halfway between the two keyframes
Assert::AreEqual((2.7 + -1.8) / 2, drawable->GetRotation(), 0.00001);
drawable->SetRotation(0.3);
picture->SetAnimationTime(2.0); // 1/3 between the two keyframes
Assert::AreEqual(2.7 + 1.0 / 3.0 * (-1.8 - 2.7), drawable->GetRotation(), 0.00001);
}
};
} | [
"beanchar@msu.edu"
] | beanchar@msu.edu |
8a94aa4af98ab95f53ef3d6a07d17c73105613a8 | f8224bbff536e3de6bc0e6fac2d6f88e60a67851 | /shared/dumps/UnityEngine_GameObject.hpp | 5a9035c976299f8f74d6b077936d00b2cef53368 | [
"MIT"
] | permissive | zoller27osu/beatsaber-hook | 949dbf43cc43d36afbbc56f036e730e8b2ad7c06 | 83a4bb55ed8b2f9e4c977877bc1b0601fed36f39 | refs/heads/modSettings | 2021-07-21T12:53:33.280754 | 2020-07-09T22:23:23 | 2020-07-09T22:23:23 | 225,980,838 | 1 | 0 | MIT | 2020-05-22T01:34:39 | 2019-12-05T00:13:16 | C++ | UTF-8 | C++ | false | false | 7,932 | hpp | #ifndef UnityEngine_GameObject_DEFINED
#define UnityEngine_GameObject_DEFINED
// This .hpp file was compiled via beatsaber-hook/shared/helper.py's Parse Mode.
// Created by Sc2ad.
// Methods may not be valid!
#include <dlfcn.h>
#include <string_view>
#include "../utils/typedefs.h"
#include "../utils/il2cpp-functions.hpp"
#include "../utils/il2cpp-utils.hpp"
// Contains MethodInfo/Il2CppClass data for: UnityEngine.GameObject
namespace UnityEngine_GameObject {
// UnityEngine.GameObject
typedef struct Class : Il2CppObject {
} Class;
static bool __cached = false;
static Il2CppClass* klass;
static const MethodInfo* CreatePrimitive_PrimitiveType;
static const MethodInfo* GetComponent_generic;
static const MethodInfo* GetComponent_Type;
static const MethodInfo* GetComponentFastPath_Type_IntPtr;
static const MethodInfo* GetComponentByName_string;
static const MethodInfo* GetComponent_string;
static const MethodInfo* GetComponentInChildren_Type_bool;
static const MethodInfo* GetComponentInChildren_Type;
static const MethodInfo* GetComponentInChildren_generic;
static const MethodInfo* GetComponentInChildren_bool_generic;
static const MethodInfo* GetComponentInParent_Type;
static const MethodInfo* GetComponentsInternal_Type_bool_bool_bool_bool_object;
static const MethodInfo* GetComponents_Type;
static const MethodInfo* GetComponents;
static const MethodInfo* GetComponents_List1;
static const MethodInfo* GetComponentsInChildren_Type_bool;
static const MethodInfo* GetComponentsInChildren_bool;
static const MethodInfo* GetComponentsInChildren_bool_List1;
static const MethodInfo* GetComponentsInChildren;
static const MethodInfo* GetComponentsInParent_Type_bool;
static const MethodInfo* GetComponentsInParent_bool_List1;
static const MethodInfo* GetComponentsInParent_bool;
static const MethodInfo* Internal_AddComponentWithType_Type;
static const MethodInfo* AddComponent_Type;
static const MethodInfo* AddComponent_generic;
static const MethodInfo* get_transform;
static const MethodInfo* get_layer;
static const MethodInfo* set_layer;
static const MethodInfo* SetActive_bool;
static const MethodInfo* get_activeSelf;
static const MethodInfo* get_activeInHierarchy;
static const MethodInfo* get_tag;
static const MethodInfo* set_tag;
static const MethodInfo* FindGameObjectsWithTag_string;
static const MethodInfo* SendMessage_string_object_SendMessageOptions;
static const MethodInfo* BroadcastMessage_string_object_SendMessageOptions;
static const MethodInfo* Internal_CreateGameObject_GameObject_string;
static const MethodInfo* Find_string;
static const MethodInfo* get_scene;
static const MethodInfo* get_gameObject;
static const MethodInfo* get_scene_Injected_out_Scene;
// The Initialization function that must be called before using any of these definitions
static void Init() {
if (!__cached) {
klass = il2cpp_utils::GetClassFromName("UnityEngine", "GameObject");
CreatePrimitive_PrimitiveType = il2cpp_functions::class_get_method_from_name(klass, "CreatePrimitive", 1);
GetComponent_generic = il2cpp_functions::class_get_method_from_name(klass, "GetComponent", 0);
GetComponent_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponent", 1);
GetComponentFastPath_Type_IntPtr = il2cpp_functions::class_get_method_from_name(klass, "GetComponentFastPath", 2);
GetComponentByName_string = il2cpp_functions::class_get_method_from_name(klass, "GetComponentByName", 1);
GetComponent_string = il2cpp_functions::class_get_method_from_name(klass, "GetComponent", 1);
GetComponentInChildren_Type_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 2);
GetComponentInChildren_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 1);
GetComponentInChildren_generic = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 0);
GetComponentInChildren_bool_generic = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 1);
GetComponentInParent_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInParent", 1);
GetComponentsInternal_Type_bool_bool_bool_bool_object = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInternal", 6);
GetComponents_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponents", 1);
GetComponents = il2cpp_functions::class_get_method_from_name(klass, "GetComponents", 0);
GetComponents_List1 = il2cpp_functions::class_get_method_from_name(klass, "GetComponents", 1);
GetComponentsInChildren_Type_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 2);
GetComponentsInChildren_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 1);
GetComponentsInChildren_bool_List1 = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 2);
GetComponentsInChildren = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 0);
GetComponentsInParent_Type_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInParent", 2);
GetComponentsInParent_bool_List1 = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInParent", 2);
GetComponentsInParent_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInParent", 1);
Internal_AddComponentWithType_Type = il2cpp_functions::class_get_method_from_name(klass, "Internal_AddComponentWithType", 1);
AddComponent_Type = il2cpp_functions::class_get_method_from_name(klass, "AddComponent", 1);
AddComponent_generic = il2cpp_functions::class_get_method_from_name(klass, "AddComponent", 0);
get_transform = il2cpp_functions::class_get_method_from_name(klass, "get_transform", 0);
get_layer = il2cpp_functions::class_get_method_from_name(klass, "get_layer", 0);
set_layer = il2cpp_functions::class_get_method_from_name(klass, "set_layer", 1);
SetActive_bool = il2cpp_functions::class_get_method_from_name(klass, "SetActive", 1);
get_activeSelf = il2cpp_functions::class_get_method_from_name(klass, "get_activeSelf", 0);
get_activeInHierarchy = il2cpp_functions::class_get_method_from_name(klass, "get_activeInHierarchy", 0);
get_tag = il2cpp_functions::class_get_method_from_name(klass, "get_tag", 0);
set_tag = il2cpp_functions::class_get_method_from_name(klass, "set_tag", 1);
FindGameObjectsWithTag_string = il2cpp_functions::class_get_method_from_name(klass, "FindGameObjectsWithTag", 1);
SendMessage_string_object_SendMessageOptions = il2cpp_functions::class_get_method_from_name(klass, "SendMessage", 3);
BroadcastMessage_string_object_SendMessageOptions = il2cpp_functions::class_get_method_from_name(klass, "BroadcastMessage", 3);
Internal_CreateGameObject_GameObject_string = il2cpp_functions::class_get_method_from_name(klass, "Internal_CreateGameObject", 2);
Find_string = il2cpp_functions::class_get_method_from_name(klass, "Find", 1);
get_scene = il2cpp_functions::class_get_method_from_name(klass, "get_scene", 0);
get_gameObject = il2cpp_functions::class_get_method_from_name(klass, "get_gameObject", 0);
get_scene_Injected_out_Scene = il2cpp_functions::class_get_method_from_name(klass, "get_scene_Injected", 1);
__cached = true;
}
}
}
#endif /* UnityEngine_GameObject_DEFINED */ | [
"adamznow@gmail.com"
] | adamznow@gmail.com |
11563f864f3f834772709835afed9470169e719c | b4ad8495d6e353ec1dd75503da06e27c04c9e89d | /src/simulations/genetics_warped/clothosim/ClothoInitializerManager.h | 811977a73e625964a4338a714e9daf5678b99fa8 | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | putnampp/clotho-dev | a0efc5346c051460abab336c783a3977dbc26bf1 | dd6ffdb549f6669236745bbf80be6b12392ecc00 | refs/heads/master | 2021-01-25T06:36:32.056942 | 2014-09-15T14:28:17 | 2014-09-15T14:28:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,356 | h | /*******************************************************************************
* Copyright (c) 2013, Patrick P. Putnam (putnampp@gmail.com)
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
******************************************************************************/
#ifndef CLOTHOINITIALIZERMANAGER_H_
#define CLOTHOINITIALIZERMANAGER_H_
#include "common.h"
#include "SimulationObject.h"
#include <unordered_map>
#include <vector>
using std::unordered_map;
using std::vector;
static const string INITIALIZER_K = "initializer";
struct initializer_creator {
virtual const string & name() = 0;
};
template < class P >
struct InitializerCreator : virtual public initializer_creator {
virtual void initialize( const P &, shared_ptr< vector< SimulationObject * > > ) = 0;
};
template < class PARAMS >
class ClothoInitializerManager {
public:
typedef InitializerCreator< PARAMS > object_creator_t;
typedef std::unordered_map< string, object_creator_t * > ManagedInitializers;
typedef typename ManagedInitializers::iterator miterator;
static shared_ptr< ClothoInitializerManager< PARAMS > > getInstance() {
static shared_ptr< ClothoInitializerManager< PARAMS > > inst( new ClothoInitializerManager<PARAMS>() );
return inst;
}
void registerInitializer( object_creator_t * soc ) {
m_creators[ soc->name() ] = soc;
}
void initialize( const string & name, const PARAMS & p, shared_ptr< vector< SimulationObject * > > objs ) {
miterator it = m_creators.find( name );
if( it == m_creators.end() )
return;
it->second->initialize( p, objs );
}
virtual ~ClothoInitializerManager() {
m_creators.clear();
}
protected:
ClothoInitializerManager() {}
ManagedInitializers m_creators;
};
#endif // CLOTHOINITIALIZERMANAGER_H_
| [
"patrick.putnam@cchmc.org"
] | patrick.putnam@cchmc.org |
2c3b9ae9534d0c70c15222cd2f8461ce6f55fe93 | 8508ba9a7150ea261d23eb387fb2b2a046255077 | /VTK/Course2/mainwindow.h | 41e26e133cdc173dccceb81dff91d828eb4c1ec9 | [] | no_license | ronblog/QTblog | 3d8f879c5141025596ec2e4a00360bf8daa5f0c3 | e7ebd2037afc5f9a2e51cb9d6ff88ba417a0c209 | refs/heads/main | 2023-07-15T15:50:43.077820 | 2021-09-05T03:13:58 | 2021-09-05T03:13:58 | 395,857,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"huang.rong.bj@gmail.com"
] | huang.rong.bj@gmail.com |
8737db96e2852b7355c8a08a6d9da1b64080d186 | 2b23944ed854fe8d2b2e60f8c21abf6d1cfd42ac | /HDU/4810/6889651_WA_0ms_0kB.cpp | 63f4943d96763254aa33d4b51c7b683196b8a41d | [] | no_license | weakmale/hhabb | 9e28b1f2ed34be1ecede5b34dc2d2f62588a5528 | 649f0d2b5796ec10580428d16921879aa380e1f2 | refs/heads/master | 2021-01-01T20:19:08.062232 | 2017-07-30T17:23:21 | 2017-07-30T17:23:21 | 98,811,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,995 | cpp | #include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
typedef long long LL;
const int mod=1000003;
int n;
LL num[1050];
LL ans[1050];
LL f[1050][1050];
bool cmp(int a,int b)
{
return a>b;
}
/*LL Qpow(LL n,LL m){
LL ans=1; LL base=n;
while(m){
if(m&1)
ans=(ans*base)%mod;
base=(base*base)%mod;
m>>=1;
}
return ans;
}
LL C(LL a,LL b)
{
return f[b]*Qpow(f[a]*f[b-a]%mod,mod-2)%mod;
}*/
void init()
{
memset(f,0,sizeof(f));
for(int i=0;i<1050;i++)
f[i][0]=f[i][i]=1;
for(int i=1;i<1050;i++)
for(int j=1;j<i;j++)
f[i][j] = (f[i-1][j]+f[i-1][j-1])%mod;
}
int main(){
// fac[0]=1;
// for(int i=1;i<1010;i++)
// fac[i]=fac[i-1]*i%mod;
init();
while(~scanf("%d",&n)){
memset(ans,0,sizeof(ans));
for(int i=1;i<=n;i++){
scanf("%lld",&num[i]);
ans[1]+=num[i];
if(i==1)
ans[n]=num[i];
else
ans[n]^=num[i];
}
sort(num+1,num+n+1,cmp);
LL ml=1;
while(num[1]){
LL cnt1=0,cnt2=n;
for(int i=1;i<=n;i++){
if(!num[i])
break;
if(num[i]&1)
cnt1++;
// cout<<num[i]<<"~~~"<<i<<endl;
num[i]>>=1;
}
cnt2-=cnt1;
for(int i=2;i<n;i++){
for(int j=1;j<=cnt1&&j<=i;j+=2){
// LL a=C(j,cnt1);
// LL b=C(i-j,cnt2);
ans[i]+=f[cnt1][j]*f[cnt2][i-j]*ml%mod;
// cout<<C(j,cnt1)<<"----"<<j<<"~~~~"<<i<<"~~~~~~"<<C(i-j,cnt2)<<"____"<<ml<<")))))"<<cnt1<<">>>>:"<<ans[i]<<endl;
}
}
ml<<=1;
}
for(int i=1;i<n;i++)
printf("%lld ",ans[i]);
printf("%lld\n",ans[n]);
}
return 0;
}
| [
"wuweak@gmail.com"
] | wuweak@gmail.com |
4533748c8f663b88f6629b434e1dc56a315c09be | b575933c01b603f30cb6e9fbcbe77462c13dc646 | /problemset/1431. 拥有最多糖果的孩子/solution.cpp | 0c5e40c18fd9917847719e23b01b612f0422ced6 | [] | no_license | KevenGe/LeetCode-Solutions | 23950a84e347032db637a3c5b0aa97eb12727321 | c7becb56e207ee2de6dbf662c98db7eb5b9471ff | refs/heads/master | 2023-09-04T07:40:05.185619 | 2023-08-21T15:09:49 | 2023-08-21T15:09:49 | 250,487,996 | 1 | 1 | null | 2023-08-16T13:58:19 | 2020-03-27T09:06:32 | Python | UTF-8 | C++ | false | false | 41 | cpp | //
// Created by lenovo on 2020/6/1.
//
| [
"1985996902@qq.com"
] | 1985996902@qq.com |
f3790167ab909f41d66f024029759c244bba9842 | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_EngramEntry_WoodPillar_functions.cpp | 27448fd0827b63045cad4c211e8dd551ed46a0e0 | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | cpp | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_EngramEntry_WoodPillar_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function EngramEntry_WoodPillar.EngramEntry_WoodPillar_C.ExecuteUbergraph_EngramEntry_WoodPillar
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UEngramEntry_WoodPillar_C::ExecuteUbergraph_EngramEntry_WoodPillar(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function EngramEntry_WoodPillar.EngramEntry_WoodPillar_C.ExecuteUbergraph_EngramEntry_WoodPillar");
UEngramEntry_WoodPillar_C_ExecuteUbergraph_EngramEntry_WoodPillar_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 |
430f5c64e3b9062508823d5723e5ee59efe33245 | fd2dd0d57920497b738c8b1b57c404d13fb6430d | /src/JSONNumber.cpp | 1f846f0503d05cb3b07ceaad4de7c2f6d77d05e3 | [] | no_license | ayoubserti/DiffBot-Client-Cpp | c90fb5476573ed78cc1db17689bf706b57c7f757 | 5be918f801551e03fbfb5c7cf37f4a30ec772e5e | refs/heads/master | 2021-01-24T19:12:45.914960 | 2014-01-10T16:51:23 | 2014-01-10T16:51:23 | 52,693,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,337 | cpp | /*
This file is part of the Quickson project
Copyright 2010 Seok Lee <ddoman@iused.net>
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 <cstdlib>
#include <cstdio>
#include <cmath>
#include "JSONNumber.h"
// RFC 4627 application/json
//
// * Octal and hex forms are not allowed. Leading zeros are not allowed.
// * A fraction part is a decimal point followed by one or more digits.
// * An exponent part begins with the letter E in upper or lowercase,
// which may be followed by a plus or minus sign. The E and optional
// sign are followed by one or more digits.
//
// * number = [ minus ] int [ frac ] [ exp ]
size_t JSONNumber::parse( const char* buf, size_t len )
{
char ch;
size_t pos = 0;
if( status != INCOMPLETE )
return 0;
if( buf == NULL || len == 0 )
return 0;
// SIGN & INT indicates the coming one is the first letter
if( (lexis & SIGN) && (lexis & INT) )
{
// skip whitespaces
ch = *( buf + pos );
while( ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' )
{
if( ++pos == len )
return pos;
ch = *( buf + pos );
}
if( ch == '-' )
{
pos++;
lexis |= NEGATIVE;
}
// the first letter can only be either - or digit
else if( ch > '9' || ch < '0' )
{
status = ERROR;
return pos;
}
lexis = lexis & ~SIGN;
}
for( ; pos < len ; pos++ )
{
ch = *( buf + pos );
if( lexis & INT )
{
switch( ch )
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
data = data * 10 + ch - '0';
lexis &= ~NUM; // set NUM_MUST_COME(off)
break;
case '.':
if( lexis & NUM )
{
status = ERROR;
return pos;
}
// get into FRAC
// set NUM_MUST_COME(on)
lexis |= NUM;
lexis = (( lexis & ~INT ) & ~EXP) | FRAC;
break;
case 'e':
case 'E':
if( lexis & NUM )
{
status = ERROR;
return pos;
}
// get into EXP!
// set SIGN_OR_NUM_MUST_COME(on)
// In fact, there is no such a case that SIGN is on, but NUM is off.
// if SIGN is on, NUM is also always on in JSON NUM Syntax.
lexis |= SIGN;
lexis = (( lexis & ~INT ) & ~FRAC) | EXP;
break;
default:
finalize();
return pos;
}
}
else if( lexis & FRAC )
{
switch( ch )
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
data = data * 10 + ch - '0';
lexis &= ~NUM; // set NUM_MUST_COME(off)
fraction--;
break;
case 'e':
case 'E':
if( lexis & NUM )
{
status = ERROR;
return pos;
}
// get into EXP!
// set SIGN_OR_NUM_MUST_COME(on)
lexis |= SIGN;
lexis = (lexis & ~FRAC) | EXP;
break;
default:
finalize();
return pos;
}
}
else if( lexis & EXP )
{
switch( ch )
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
if( lexis & SIGN )
lexis &= ~SIGN;
if( lexis & NUM )
lexis &= ~NUM;
exponent = exponent * 10 + ch - '0';
break;
case '-':
case '+':
if( lexis & SIGN )
{
if( ch == '-' )
lexis |= EXP_NEGATIVE;
// the next must be a num
lexis = (lexis & ~SIGN) | NUM;
}
else
{
status = ERROR;
return pos;
}
break;
default:
finalize();
return pos;
}
}
}
return pos;
}
void JSONNumber::dump() const
{
if( status != COMPLETE )
return;
fprintf( stdout, "%.20g", get() );
}
// Weak implementation.
// This logic assumes that the type of variable data is int and
// the size is always 32 bits.
// Since C++ 98 does not support byte-specified types, such as uint32_t
// and int64_t, this implementation was chosen and may have to be improved later.
//
// The point of this design - stores a number as an integer, but applies the fraction
// value into the number when returning the actual double number - is related to serializing issues.
//
// To convert a double value into a string, we need to count the number of significant digits
// in a given number. Otherwise, a parser, like itoa(), sprintf(), should take a fixed-precision value,
// which may bring trailing zeroes or discard some digits. It is OK if the number is only used as a number,
// but trailing zeroes increase the length of each number string by a serializer.
//
// printf() with %g may avoid "trailing zero" problem, but cannot avoid "discarding digit" problem
// since it has to know the number of significant digits.
//
// Thus, to get the optimal size of a number string, counting the number of significant digits is needed
// and seperation of significant digits and fraction value helps solving this issue.
//
// For more information, read the code part of JSONSerializer::serialize( JSONNumber );
double JSONNumber::get() const
{
static const unsigned int powerArray[] =
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; // 10 digits are enough for uint32_t
double ret = data;
if( fraction > 0 )
ret *= powerArray[ (int)fraction ];
else if( fraction < 0 )
ret /= powerArray[ (int)fraction * -1 ];
return ret;
}
char JSONNumber::countSD() const
{
static const unsigned int powerArray[] =
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; // 10 digits are enough for uint32_t
short min = 0;
short max = sizeof( powerArray ) / sizeof( powerArray[0] );
short mid = max / 2;
while( min < max )
{
mid = (max + min) / 2;
if( data > powerArray[ mid ] )
min = mid + 1;
else if( data < powerArray[ mid ] )
max = mid - 1;
else
break;
};
if( fraction < 0 && mid <= fraction * -1 )
return fraction + 1;
else
return mid + fraction;
}
| [
"ayoub@4d.com"
] | ayoub@4d.com |
205c4a02c89e431b2b5d26d82424218201817e4a | 20369f44e3832b2553b5d180de4bf3d40dbb0b71 | /src/gpu/GrQuad.cpp | c741827fd6f3ab2bf30dad2404f5be9dbb01f971 | [
"BSD-3-Clause"
] | permissive | Samsomyajit/skia | 2b2ba85d4c4c49de1d02080368bc27c0106fa9e9 | b1cc013adf497a11b5b3c96cc733fc7d4c92741d | refs/heads/master | 2020-08-14T20:42:15.258203 | 2019-04-11T13:27:53 | 2019-04-11T14:03:55 | 215,229,069 | 0 | 0 | BSD-3-Clause | 2019-10-15T06:58:37 | 2019-10-15T06:58:37 | null | UTF-8 | C++ | false | false | 11,006 | cpp | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrQuad.h"
#include "GrTypesPriv.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
// Functions for identifying the quad type from its coordinates, which are kept debug-only since
// production code should rely on the matrix to derive the quad type more efficiently. These are
// useful in asserts that the quad type is as expected.
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef SK_DEBUG
// Allow some tolerance from floating point matrix transformations, but SkScalarNearlyEqual doesn't
// support comparing infinity, and coords_form_rect should return true for infinite edges
#define NEARLY_EQUAL(f1, f2) (f1 == f2 || SkScalarNearlyEqual(f1, f2, 1e-5f))
// Similarly, support infinite rectangles by looking at the sign of infinities
static bool dot_nearly_zero(const SkVector& e1, const SkVector& e2) {
static constexpr auto dot = SkPoint::DotProduct;
static constexpr auto sign = SkScalarSignAsScalar;
SkScalar dotValue = dot(e1, e2);
if (SkScalarIsNaN(dotValue)) {
// Form vectors from the signs of infinities, and check their dot product
dotValue = dot({sign(e1.fX), sign(e1.fY)}, {sign(e2.fX), sign(e2.fY)});
}
return SkScalarNearlyZero(dotValue, 1e-3f);
}
// This is not the most performance critical function; code using GrQuad should rely on the faster
// quad type from matrix path, so this will only be called as part of SkASSERT.
static bool coords_form_rect(const float xs[4], const float ys[4]) {
return (NEARLY_EQUAL(xs[0], xs[1]) && NEARLY_EQUAL(xs[2], xs[3]) &&
NEARLY_EQUAL(ys[0], ys[2]) && NEARLY_EQUAL(ys[1], ys[3])) ||
(NEARLY_EQUAL(xs[0], xs[2]) && NEARLY_EQUAL(xs[1], xs[3]) &&
NEARLY_EQUAL(ys[0], ys[1]) && NEARLY_EQUAL(ys[2], ys[3]));
}
static bool coords_rectilinear(const float xs[4], const float ys[4]) {
SkVector e0{xs[1] - xs[0], ys[1] - ys[0]}; // connects to e1 and e2(repeat)
SkVector e1{xs[3] - xs[1], ys[3] - ys[1]}; // connects to e0(repeat) and e3
SkVector e2{xs[0] - xs[2], ys[0] - ys[2]}; // connects to e0 and e3(repeat)
SkVector e3{xs[2] - xs[3], ys[2] - ys[3]}; // connects to e1(repeat) and e2
e0.normalize();
e1.normalize();
e2.normalize();
e3.normalize();
return dot_nearly_zero(e0, e1) && dot_nearly_zero(e1, e3) &&
dot_nearly_zero(e2, e0) && dot_nearly_zero(e3, e2);
}
GrQuadType GrQuad::quadType() const {
// Since GrQuad applies any perspective information at construction time, there's only two
// types to choose from.
if (coords_form_rect(fX, fY)) {
return GrQuadType::kRect;
} else if (coords_rectilinear(fX, fY)) {
return GrQuadType::kRectilinear;
} else {
return GrQuadType::kStandard;
}
}
GrQuadType GrPerspQuad::quadType() const {
if (this->hasPerspective()) {
return GrQuadType::kPerspective;
} else {
// Rect or standard quad, can ignore w since they are all ones
if (coords_form_rect(fX, fY)) {
return GrQuadType::kRect;
} else if (coords_rectilinear(fX, fY)) {
return GrQuadType::kRectilinear;
} else {
return GrQuadType::kStandard;
}
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
static bool aa_affects_rect(float ql, float qt, float qr, float qb) {
return !SkScalarIsInt(ql) || !SkScalarIsInt(qr) || !SkScalarIsInt(qt) || !SkScalarIsInt(qb);
}
static void map_rect_translate_scale(const SkRect& rect, const SkMatrix& m,
Sk4f* xs, Sk4f* ys) {
SkMatrix::TypeMask tm = m.getType();
SkASSERT(tm <= (SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask));
Sk4f r = Sk4f::Load(&rect);
if (tm > SkMatrix::kIdentity_Mask) {
const Sk4f t(m.getTranslateX(), m.getTranslateY(), m.getTranslateX(), m.getTranslateY());
if (tm <= SkMatrix::kTranslate_Mask) {
r += t;
} else {
const Sk4f s(m.getScaleX(), m.getScaleY(), m.getScaleX(), m.getScaleY());
r = r * s + t;
}
}
*xs = SkNx_shuffle<0, 0, 2, 2>(r);
*ys = SkNx_shuffle<1, 3, 1, 3>(r);
}
static void map_quad_general(const Sk4f& qx, const Sk4f& qy, const SkMatrix& m,
Sk4f* xs, Sk4f* ys, Sk4f* ws) {
static constexpr auto fma = SkNx_fma<4, float>;
*xs = fma(m.getScaleX(), qx, fma(m.getSkewX(), qy, m.getTranslateX()));
*ys = fma(m.getSkewY(), qx, fma(m.getScaleY(), qy, m.getTranslateY()));
if (m.hasPerspective()) {
Sk4f w = fma(m.getPerspX(), qx, fma(m.getPerspY(), qy, m.get(SkMatrix::kMPersp2)));
if (ws) {
// Output the calculated w coordinates
*ws = w;
} else {
// Apply perspective division immediately
Sk4f iw = w.invert();
*xs *= iw;
*ys *= iw;
}
} else if (ws) {
*ws = 1.f;
}
}
static void map_rect_general(const SkRect& rect, const SkMatrix& matrix,
Sk4f* xs, Sk4f* ys, Sk4f* ws) {
Sk4f rx(rect.fLeft, rect.fLeft, rect.fRight, rect.fRight);
Sk4f ry(rect.fTop, rect.fBottom, rect.fTop, rect.fBottom);
map_quad_general(rx, ry, matrix, xs, ys, ws);
}
// Rearranges (top-left, top-right, bottom-right, bottom-left) ordered skQuadPts into xs and ys
// ordered (top-left, bottom-left, top-right, bottom-right)
static void rearrange_sk_to_gr_points(const SkPoint skQuadPts[4], Sk4f* xs, Sk4f* ys) {
*xs = Sk4f(skQuadPts[0].fX, skQuadPts[3].fX, skQuadPts[1].fX, skQuadPts[2].fX);
*ys = Sk4f(skQuadPts[0].fY, skQuadPts[3].fY, skQuadPts[1].fY, skQuadPts[2].fY);
}
template <typename Q>
void GrResolveAATypeForQuad(GrAAType requestedAAType, GrQuadAAFlags requestedEdgeFlags,
const Q& quad, GrQuadType knownType,
GrAAType* outAAType, GrQuadAAFlags* outEdgeFlags) {
// Most cases will keep the requested types unchanged
*outAAType = requestedAAType;
*outEdgeFlags = requestedEdgeFlags;
switch (requestedAAType) {
// When aa type is coverage, disable AA if the edge configuration doesn't actually need it
case GrAAType::kCoverage:
if (requestedEdgeFlags == GrQuadAAFlags::kNone) {
// Turn off anti-aliasing
*outAAType = GrAAType::kNone;
} else {
// For coverage AA, if the quad is a rect and it lines up with pixel boundaries
// then overall aa and per-edge aa can be completely disabled
if (knownType == GrQuadType::kRect && !quad.aaHasEffectOnRect()) {
*outAAType = GrAAType::kNone;
*outEdgeFlags = GrQuadAAFlags::kNone;
}
}
break;
// For no or msaa anti aliasing, override the edge flags since edge flags only make sense
// when coverage aa is being used.
case GrAAType::kNone:
*outEdgeFlags = GrQuadAAFlags::kNone;
break;
case GrAAType::kMSAA:
*outEdgeFlags = GrQuadAAFlags::kAll;
break;
case GrAAType::kMixedSamples:
SK_ABORT("Should not use mixed sample AA with edge AA flags");
break;
}
};
// Instantiate GrResolve... for GrQuad and GrPerspQuad
template void GrResolveAATypeForQuad(GrAAType, GrQuadAAFlags, const GrQuad&, GrQuadType,
GrAAType*, GrQuadAAFlags*);
template void GrResolveAATypeForQuad(GrAAType, GrQuadAAFlags, const GrPerspQuad&, GrQuadType,
GrAAType*, GrQuadAAFlags*);
GrQuadType GrQuadTypeForTransformedRect(const SkMatrix& matrix) {
if (matrix.rectStaysRect()) {
return GrQuadType::kRect;
} else if (matrix.preservesRightAngles()) {
return GrQuadType::kRectilinear;
} else if (matrix.hasPerspective()) {
return GrQuadType::kPerspective;
} else {
return GrQuadType::kStandard;
}
}
GrQuadType GrQuadTypeForPoints(const SkPoint pts[4], const SkMatrix& matrix) {
if (matrix.hasPerspective()) {
return GrQuadType::kPerspective;
}
// If 'pts' was formed by SkRect::toQuad() and not transformed further, it is safe to use the
// quad type derived from 'matrix'. Otherwise don't waste any more time and assume kStandard
// (most general 2D quad).
if ((pts[0].fY == pts[3].fY && pts[1].fY == pts[2].fY) &&
(pts[0].fX == pts[1].fX && pts[2].fX == pts[3].fX)) {
return GrQuadTypeForTransformedRect(matrix);
} else {
return GrQuadType::kStandard;
}
}
GrQuad GrQuad::MakeFromRect(const SkRect& rect, const SkMatrix& m) {
Sk4f x, y;
SkMatrix::TypeMask tm = m.getType();
if (tm <= (SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask)) {
map_rect_translate_scale(rect, m, &x, &y);
} else {
map_rect_general(rect, m, &x, &y, nullptr);
}
return GrQuad(x, y);
}
GrQuad GrQuad::MakeFromSkQuad(const SkPoint pts[4], const SkMatrix& matrix) {
Sk4f xs, ys;
rearrange_sk_to_gr_points(pts, &xs, &ys);
if (matrix.isIdentity()) {
return GrQuad(xs, ys);
} else {
Sk4f mx, my;
map_quad_general(xs, ys, matrix, &mx, &my, nullptr);
return GrQuad(mx, my);
}
}
bool GrQuad::aaHasEffectOnRect() const {
SkASSERT(this->quadType() == GrQuadType::kRect);
return aa_affects_rect(fX[0], fY[0], fX[3], fY[3]);
}
// Private constructor used by GrQuadList to quickly fill in a quad's values from the channel arrays
GrPerspQuad::GrPerspQuad(const float* xs, const float* ys, const float* ws) {
memcpy(fX, xs, 4 * sizeof(float));
memcpy(fY, ys, 4 * sizeof(float));
memcpy(fW, ws, 4 * sizeof(float));
}
GrPerspQuad GrPerspQuad::MakeFromRect(const SkRect& rect, const SkMatrix& m) {
Sk4f x, y, w;
SkMatrix::TypeMask tm = m.getType();
if (tm <= (SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask)) {
map_rect_translate_scale(rect, m, &x, &y);
w = 1.f;
} else {
map_rect_general(rect, m, &x, &y, &w);
}
return GrPerspQuad(x, y, w);
}
GrPerspQuad GrPerspQuad::MakeFromSkQuad(const SkPoint pts[4], const SkMatrix& matrix) {
Sk4f xs, ys;
rearrange_sk_to_gr_points(pts, &xs, &ys);
if (matrix.isIdentity()) {
return GrPerspQuad(xs, ys, 1.f);
} else {
Sk4f mx, my, mw;
map_quad_general(xs, ys, matrix, &mx, &my, &mw);
return GrPerspQuad(mx, my, mw);
}
}
bool GrPerspQuad::aaHasEffectOnRect() const {
SkASSERT(this->quadType() == GrQuadType::kRect);
// If rect, ws must all be 1s so no need to divide
return aa_affects_rect(fX[0], fY[0], fX[3], fY[3]);
}
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
80ed9a52c41f3c9a83921bc9633d9d12990c54e0 | 4005686b3965177bad74b4185335422578833fb0 | /SP1Framework/gym_1.h | 78fe7da85e77421d5bb4fe6034a046264170f475 | [] | no_license | ihsfeo/yay | 7e43eed67172e687fd590346c56697af2c78b520 | 1edcd0e4d2777a48e5b2644e0222db3623d13927 | refs/heads/main | 2023-07-13T04:43:06.206151 | 2021-08-20T06:53:51 | 2021-08-20T06:53:51 | 398,183,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 95 | h | #pragma once
#include "gym.h"
class gym_1 : public gym
{
public:
gym_1();
~gym_1();
}; | [
"kahjinqkj@gmail.com"
] | kahjinqkj@gmail.com |
e1f32eb2b974aaa0ef2dfb0171a41c042542d39d | 5704ae9ebce8468451712afa57fb3a60e822f790 | /contrib/brl/bseg/bvpl/bvpl_octree/pro/processes/pca/bvpl_compute_pca_test_error_process.cxx | ee996c35b9f4c894e0c61f8bb2bc3d9f06aabd7b | [] | no_license | liuxinren456852/vxl | 2f65fcb3189674c299b1dd7a9ea3a9490017ea1d | fdc95966a88ee011e74f1878d0555108ab809867 | refs/heads/master | 2020-12-11T03:40:32.805779 | 2016-03-09T05:01:22 | 2016-03-09T05:01:22 | 53,484,067 | 1 | 0 | null | 2016-03-09T09:12:08 | 2016-03-09T09:12:08 | null | UTF-8 | C++ | false | false | 1,512 | cxx | //:
// \file
// \brief A process to compute reconstruction error over all samples in a scene (test + train)
// \author Isabel Restrepo
// \date 13-Jan-2011
#include <bprb/bprb_func_process.h>
#include <bprb/bprb_parameters.h>
#include <brdb/brdb_value.h>
#include <bvpl/bvpl_octree/bvpl_discover_pca_kernels.h>
//:global variables
namespace bvpl_compute_pca_test_error_process_globals
{
const unsigned n_inputs_ = 1; //directory path, where pca_info.xml is
const unsigned n_outputs_ = 1; //error file
}
//:sets input and output types
bool bvpl_compute_pca_test_error_process_cons(bprb_func_process& pro)
{
using namespace bvpl_compute_pca_test_error_process_globals ;
vcl_vector<vcl_string> input_types_(n_inputs_);
input_types_[0] = "vcl_string" ;
vcl_vector<vcl_string> output_types_(n_outputs_);
output_types_[0] = " vcl_string";
return pro.set_input_types(input_types_) && pro.set_output_types(output_types_);
}
//:the process
bool bvpl_compute_pca_test_error_process(bprb_func_process& pro)
{
using namespace bvpl_compute_pca_test_error_process_globals;
//get inputs
vcl_string pca_dir = pro.get_input<vcl_string>(0);
bvpl_discover_pca_kernels pca_extractor(pca_dir);
vnl_vector<double> t_error;
pca_extractor.compute_testing_error(t_error);
vcl_ofstream error_ofs((pca_dir+ "/test_error.txt").c_str());
if (error_ofs)
error_ofs << t_error;
//store output
pro.set_output_val<vcl_string>(0, pca_dir+ "/test_error.txt");
return true;
}
| [
"isabel_restrepo@users.sourceforge.net"
] | isabel_restrepo@users.sourceforge.net |
5751fdc8bf780433092af95c3cfffa3855ad31c0 | fc305c8b90483914a58ed2a018ff9af77548435b | /mainwindow.h | 184f2b8597a46ddab7e6bec09df8ae6caa476ac2 | [] | no_license | marianabritoazevedo/TestandoQT | b5919e67d2a6da5dad95472a9797e3037ff82709 | a4acdb26995dcabdcca55f852e21690617f36fd8 | refs/heads/main | 2023-04-10T02:13:17.489597 | 2021-04-26T12:04:54 | 2021-04-26T12:04:54 | 357,709,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void sair();
void copiaTexto();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"mari.brito.azevedo@gmail.com"
] | mari.brito.azevedo@gmail.com |
d36188ddaf059e3aa84ee8b4a45488186e30b97f | 4921712bff898e0e96ddd82f75aea1acc764aacf | /unnamed-project/src/GameLogic/Factories/PreconditionFactory.cpp | b7eac76c9771d5c92ad1cd64b3b2fce87f99df23 | [] | no_license | antielektron/shinyProjectGroup | ad0d6996dddea9b184909373f3d872d890f6b950 | 2fb38736bbc82670070253faf808912456e423c0 | refs/heads/master | 2020-03-16T08:43:59.682971 | 2016-03-29T20:32:53 | 2016-03-29T20:32:53 | 132,601,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,665 | cpp | #include "GameLogic/Factories/PreconditionFactory.h"
#include "GameLogic/Preconditions/IsEqualPrecondition.h"
#include "GameLogic/Preconditions/IsLessPrecondition.h"
#include "GameLogic/Preconditions/IsGreaterPrecondition.h"
template <typename ...Args>
struct CreatePreconditionHelper {};
template <typename T, typename ...Args>
struct CreatePreconditionHelper<T, Args...>
{
static std::unique_ptr<PreconditionBase> create(const QString &type)
{
if (type == traits::precondition_name<T>::value())
{
return std::unique_ptr<PreconditionBase>(new T());
}
else
{
return CreatePreconditionHelper<Args...>::create(type);
}
}
static std::unique_ptr<PreconditionBase> create(const QString &type, GlobalState *state, const QDomElement &domElement)
{
if (type == traits::precondition_name<T>::value())
{
return std::unique_ptr<PreconditionBase>(new T(state, domElement));
}
else
{
return CreatePreconditionHelper<Args...>::create(type, state, domElement);
}
}
static void getTypes(std::vector<QString> &types)
{
types.push_back(QString(traits::precondition_name<T>::value()));
CreatePreconditionHelper<Args...>::getTypes(types);
}
};
template <>
struct CreatePreconditionHelper<>
{
static std::unique_ptr<PreconditionBase> create(const QString &type)
{
throw std::runtime_error("Unknown precondition type: " + type.toStdString());
}
static std::unique_ptr<PreconditionBase> create(const QString &type, GlobalState *state, const QDomElement &domElement)
{
throw std::runtime_error("Unknown precondition type: " + type.toStdString());
}
static void getTypes(std::vector<QString> &types)
{
}
};
typedef CreatePreconditionHelper<
IsEqualPrecondition<int>,
IsEqualPrecondition<double>,
IsEqualPrecondition<bool>,
IsGreaterPrecondition<int>,
IsGreaterPrecondition<double>,
IsLessPrecondition<int>,
IsLessPrecondition<double>
> HelperType;
std::unique_ptr<PreconditionBase> Factory::createPreconditionFromType(const QString &type)
{
return HelperType::create(type);
}
std::unique_ptr<PreconditionBase> Factory::createPreconditionFromDomElement(GlobalState *state, const QDomElement &domElement)
{
auto type = domElement.attribute("type");
return HelperType::create(type, state, domElement);
}
std::vector<QString> Factory::getKnownPreconditionTypes()
{
std::vector<QString> types;
HelperType::getTypes(types);
return std::move(types);
}
| [
"tomkneiphof@gmail.com"
] | tomkneiphof@gmail.com |
9940f82ee11c278818e0370a87143b68c8cd2374 | c10650383e9bb52ef8b0c49e21c10d9867cb033c | /c++/Win32MFC/Win32MFC.h | c1e0ee50112ff4ef5d6840f49eb807d8ad90e7d2 | [] | 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 | GB18030 | C++ | false | false | 349 | h | #include <afxwin.h>
class CMyApp : public CWinApp
{
public:
virtual BOOL InitInstance();
};
class CMyWnd : public CFrameWnd
{
public:
CMyWnd();
protected:
afx_msg void OnPaint(); //手工声明消息响应函数
afx_msg void OnCreate();
afx_msg void OnDestroy();
afx_msg void OnTimer();
DECLARE_MESSAGE_MAP() //手工声明消息映射
};
| [
"76275381@qq.com"
] | 76275381@qq.com |
d05ab89c44a0753bc97bcebae5da5ff8ad33061f | 03df8063d74c07015526260faf1efaeb78289a0c | /src/click/elements/apps/snort.cc | 939c47a271857960853d5292225462a52152bf85 | [] | no_license | ianrose14/argos | 6ed5bf94a97d4b48fdcdde66108df8c97ca051bd | b540fb93062cd566a2f148c5d429f66fbff74444 | refs/heads/master | 2016-09-05T22:18:57.988099 | 2012-06-28T14:30:36 | 2012-06-28T14:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,081 | cc | /*
* snort.{cc,hh}
* Ian Rose <ianrose@eecs.harvard.edu>
*/
#include <click/config.h>
#include "snort.hh"
#include <click/confparse.hh>
#include <click/packet_anno.hh>
#include <click/straccum.hh>
#include <clicknet/ether.h>
#include <clicknet/ip.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include "snort/spo_alert_unixsock.h"
#include "../setsniffer.hh"
CLICK_DECLS
// from libpcap/savefile.c
#ifndef TCPDUMP_MAGIC
#define TCPDUMP_MAGIC 0xa1b2c3d4
#endif
Snort::Snort()
: _snort_pid(0), _snort_stdin(-1), _snort_stdout(NULL), _snort_stderr(NULL),
_dlt(-1), _snaplen(4096), _next_packet(NULL),
_sockfile(""), _sock(0), _portscan_window(60*60),
_task(this), _timer(this), _end_h(NULL), _db(NULL), _log(NULL)
{
}
Snort::~Snort()
{
if (_end_h != NULL) delete _end_h;
if (_log != NULL) delete _log;
}
enum { H_CLOSE, H_KILL, H_QUIT, H_STOP };
void
Snort::add_handlers()
{
add_write_handler("close", write_handler, (void*)H_CLOSE, 0);
add_write_handler("kill", write_handler, (void*)H_KILL, 0);
add_write_handler("quit", write_handler, (void*)H_QUIT, 0);
add_write_handler("stop", write_handler, (void*)H_STOP, 0);
add_task_handlers(&_task);
}
void
Snort::cleanup(CleanupStage)
{
if (_sock > 0)
(void) close(_sock);
// if we got far enough into the initialization for _sockfile to have a
// value, try to unlink the file in case it was created
if (_sockfile.length() > 0)
(void) unlink(_sockfile.c_str());
if (_snort_pid > 0) {
StoredErrorHandler errh = StoredErrorHandler();
if (signal_snort_proc(SIGTERM, &errh) < 0) {
if (errh.has_error())
click_chatter("%{element}: %s", this, errh.get_last_error().c_str());
}
}
}
int
Snort::configure(Vector<String> &conf, ErrorHandler *errh)
{
bool stop = false;
String logdir = ".", config;
String dlt_name = "EN10MB";
Element *elt = NULL;
String loglevel, netlog;
String logelt = "loghandler";
String snort_argstr = "";
if (cp_va_kparse(conf, this, errh,
"EXE", cpkP+cpkM, cpString, &_snort_exe,
"CONF", cpkP+cpkM, cpString, &config,
"LOGDIR", 0, cpFilename, &logdir,
"ADDL_ARGS", 0, cpString, &snort_argstr,
"DLT", 0, cpString, &dlt_name,
"SNAPLEN", 0, cpUnsigned, &_snaplen,
"PORTSCAN_WINDOW", 0, cpTimestamp, &_portscan_window,
"STOP", 0, cpBool, &stop,
"END_CALL", 0, cpHandlerCallPtrWrite, &_end_h,
"DB", 0, cpElement, &elt,
"LOGGING", 0, cpString, &loglevel,
"NETLOG", 0, cpString, &netlog,
"LOGGER", 0, cpString, &logelt,
cpEnd) < 0)
return -1;
// create log before anything else
_log = LogHandler::get_logger(this, NULL, loglevel.c_str(), netlog.c_str(),
logelt.c_str(), errh);
if (_log == NULL)
return -EINVAL;
// check that elt is a pointer to a PostgreSQL element (if specified at all)
if (elt != NULL) {
_db = (PostgreSQL*)elt->cast("PostgreSQL");
if (_db == NULL)
return errh->error("DB element is not an instance of type PostgreSQL");
}
_sockfile = logdir + "/snort_alert";
struct sockaddr_un addr;
if (_sockfile.length() >= (int)sizeof(addr.sun_path))
return errh->error("sock-file path too long: %s", _sockfile.c_str());
cp_spacevec(snort_argstr, _snort_args);
_snort_args.push_back("-c");
_snort_args.push_back(config);
_snort_args.push_back("-r");
_snort_args.push_back("-");
_snort_args.push_back("-A");
_snort_args.push_back("unsock");
_snort_args.push_back("-l");
_snort_args.push_back(logdir);
String s = "mkdir -p " + logdir;
int rv = system(s.c_str());
if (rv < 0)
return errh->error("mkdir failed (%d): %s", rv, s.c_str());
_dlt = pcap_datalink_name_to_val(dlt_name.c_str());
if (_dlt < 0)
return errh->error("bad datalink type");
if (stop && _end_h)
return errh->error("'END_CALL' and 'STOP' are mutually exclusive");
else if (stop)
_end_h = new HandlerCall(name() + ".quit");
return 0;
}
int
Snort::initialize(ErrorHandler *errh)
{
ScheduleInfo::initialize_task(this, &_task, true, errh);
_signal = Notifier::upstream_empty_signal(this, 0, &_task);
_timer.initialize(this);
// check handler call
if (_end_h && _end_h->initialize_write(this, errh) < 0)
return -1;
// create the unix socket that snort will write alerts to
_sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (_sock < 0)
return errh->error("socket: %s", strerror(errno));
struct sockaddr_un addr;
assert(_sockfile.length() < (int)sizeof(addr.sun_path)); // already checked
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, _sockfile.c_str(), sizeof(addr.sun_path));
(void) unlink(addr.sun_path);
// NOTE: many socket guides use the following which does not work due to
// differences in the sockaddr_un definition between FreeBSD and Linux:
// "len = strlen(local.sun_path) + sizeof(local.sun_family);"
int len = sizeof(struct sockaddr_un);
if (bind(_sock, (struct sockaddr *)&addr, len) != 0)
return errh->error("bind: %s", strerror(errno));
_log->debug("unix socket bound to %s", addr.sun_path);
// create the snort command that we will exec to
String cmd = _snort_exe;
char **argv = (char**)malloc(sizeof(char*)*(2 + _snort_args.size()));
argv[0] = strdup(_snort_exe.c_str());
for (int i=0; i < _snort_args.size(); i++) {
argv[i+1] = strdup(_snort_args[i].c_str());
cmd = cmd + " " + String(argv[i+1]);
}
argv[1 + _snort_args.size()] = NULL;
_log->debug("forking: %s", cmd.c_str());
add_select(_sock, SELECT_READ);
// create pipes and then fork a Snort process
int stdin_pipe[2];
int stdout_pipe[2];
int stderr_pipe[2];
if ((pipe(stdin_pipe) != 0) || (pipe(stdout_pipe) != 0) ||
(pipe(stderr_pipe) != 0))
return errh->error("pipe: %s", strerror(errno));
int status = fcntl(stdin_pipe[1], F_GETFL, NULL);
if (status < 0)
return errh->error("fcntl(F_GETFL): %s", strerror(errno));
status |= O_NONBLOCK;
if (fcntl(stdin_pipe[1], F_SETFL, status) < 0)
return errh->error("fcntl(F_SETFL): %s", strerror(errno));
int pid = fork();
if (pid == -1)
return errh->error("fork: %s", strerror(errno));
if (pid == 0) {
// I am the child - copy pipes onto standard streams, then exec snort
close(stdin_pipe[1]); /* close write-end of stdin */
close(stdout_pipe[0]); /* close read-end of stdout */
close(stderr_pipe[0]); /* close read-end of stderr */
dup2(stdin_pipe[0], STDIN_FILENO); /* copy read-end of stdin */
dup2(stdout_pipe[1], STDOUT_FILENO); /* copy write-end of stdout */
dup2(stderr_pipe[1], STDERR_FILENO); /* copy write-end of stderr */
close(stdin_pipe[0]);
close(stdout_pipe[1]);
close(stderr_pipe[1]);
execv(_snort_exe.c_str(), argv);
// if execv returns, an error occurred (report to stderr)
int errnum = errno;
stderr = fdopen(STDERR_FILENO, "w");
if (stderr == NULL) {
fprintf(stderr, "fdopen: %s\n", strerror(errno));
_exit(1);
}
fprintf(stderr, "execv: %s\n", strerror(errnum));
fflush(stderr);
_exit(1);
}
// else, I am the parent
_log->info("snort pid %d forked", pid);
_snort_pid = pid;
close(stdin_pipe[0]); // close read-end of stdin
close(stdout_pipe[1]); // close write-end of stdout
close(stderr_pipe[1]); // close write-end of stderr
_snort_stdin = stdin_pipe[1];
_snort_stdout = fdopen(stdout_pipe[0], "r");
_snort_stderr = fdopen(stderr_pipe[0], "r");
if ((_snort_stdout == NULL) || (_snort_stderr == NULL))
return errh->error("fdopen of pipe to child: %s", strerror(errno));
add_select(_snort_stdin, SELECT_WRITE);
add_select(fileno(_snort_stdout), SELECT_READ);
add_select(fileno(_snort_stderr), SELECT_READ);
// write the file header to snort before any packets
struct pcap_file_header hdr;
hdr.magic = TCPDUMP_MAGIC;
hdr.version_major = PCAP_VERSION_MAJOR;
hdr.version_minor = PCAP_VERSION_MINOR;
hdr.thiszone = 0; // always 0
hdr.sigfigs = 0; // always 0
hdr.snaplen = _snaplen;
// Technically this is supposed to be a LINKTYPE value, NOT a DLT value;
// libpcap goes through some hijinx mapping between these 2 sets of
// constants to try to deal with platform differences in the DLT values and
// such. But for most values they are the same so we just use the DLT value
// and call it a day (this is what Click's ToDump element does too).
hdr.linktype = _dlt;
size_t l = 0;
while (l < sizeof(hdr)) {
int rv = write(_snort_stdin, (char*)&hdr + l, sizeof(hdr) - l);
if (rv < 0) {
if (errno == EAGAIN) {
// hackish, but should never happen in practice
usleep(10*1000);
}
return errh->error("write of pcap file header to child: %s",
strerror(errno));
} else {
l += rv;
}
}
return 0;
}
bool
Snort::run_task(Task*)
{
bool did_work = false;
// it is possible (through race conditions) for this task to be run after
// Snort's stdin has already been closed, so check for that
if (_snort_stdin == -1)
return false;
if (_next_packet == NULL) {
_next_packet = input(0).pull();
if (_next_packet != NULL) {
_next_pkthdr.ts = _next_packet->timestamp_anno().timeval();
_next_pkthdr.len = _next_packet->length() + EXTRA_LENGTH_ANNO(_next_packet);
_next_pkthdr.caplen = _next_packet->length();
_header_written = 0;
_body_written = 0;
const struct click_ether *ether = (const struct click_ether*)_next_packet->data();
if (_next_packet->length() < sizeof(*ether)) {
// bad packet
_log->error("bad ethernet packet received (len=%d)", _next_packet->length());
_next_packet->kill();
_next_packet = NULL;
return true;
}
if (ether->ether_type == ETHERTYPE_IP) {
const struct click_ip *ip = (const struct click_ip*)(_next_packet->data() + sizeof(*ether));
if (_next_packet->length() < (sizeof(*ether) + sizeof(*ip))) {
// bad packet
_log->error("bad IP packet received (len=%d)", _next_packet->length());
_next_packet->kill();
_next_packet = NULL;
return true;
}
IPAddress src_ip = IPAddress(ip->ip_src);
IPAddress dst_ip = IPAddress(ip->ip_dst);
EtherAddress src_ether = EtherAddress(ether->ether_shost);
// todo: run_timer -> clean out old entries of _src_info
StoredErrorHandler errh;
int32_t sniffer_id = 0;
if (SetSniffer::parse_sniffer_id(_next_packet, &sniffer_id, &errh) != 0)
_log->error("parse_sniffer_id failed: %s", errh.get_last_error().c_str());
IPDuo key = IPDuo(src_ip, dst_ip);
SrcInfo *infop = _src_info.findp(key);
if (infop == NULL) {
SrcInfo info = SrcInfo();
info.ether = src_ether;
info.capt_node_id = sniffer_id;
info.last_updated = _next_packet->timestamp_anno();
_src_info.insert(key, info);
} else {
if (infop->ether != src_ether) {
// todo - change to debug level?
_log->warning("%s assignment changed from %s to %s",
key.unparse().c_str(),
infop->ether.unparse_colon().c_str(),
src_ether.unparse_colon().c_str());
infop->ether = src_ether;
}
infop->capt_node_id = sniffer_id;
infop->last_updated = _next_packet->timestamp_anno();
}
}
did_work = true;
} else {
// no packet available
if (_signal)
_task.fast_reschedule();
// else, wait for upstream notifier to reschedule this task
return false;
}
}
int rv = 0;
// first send pcap packet header
while (_header_written < sizeof(_next_pkthdr)) {
rv = write(_snort_stdin, (&_next_pkthdr) + _header_written,
sizeof(_next_pkthdr) - _header_written);
if (rv < 0) {
if (errno != EAGAIN) {
_log->error("write to snort failed: %s", strerror(errno));
close_snort_input();
}
// get notified when snort's stdin is writable again
add_select(_snort_stdin, SELECT_WRITE);
return did_work;
} else {
_header_written += rv;
did_work = true;
}
}
// now send the packet body itself
while (_body_written < _next_packet->length()) {
rv = write(_snort_stdin, _next_packet->data() + _body_written,
_next_packet->length() - _body_written);
if (rv < 0) {
if (errno != EAGAIN) {
_log->error("write to snort failed: %s", strerror(errno));
close_snort_input();
}
// get notified when snort's stdin is writable again
add_select(_snort_stdin, SELECT_WRITE);
return did_work;
} else {
_body_written += rv;
did_work = true;
}
}
if (_signal)
_task.fast_reschedule();
// done with packet!
_next_packet->kill();
_next_packet = NULL;
return true;
}
void
Snort::run_timer(Timer*)
{
if (!check_snort_proc(0, false)) {
// if process is dead then do not reschedule timer
return;
}
Timestamp thresh = Timestamp::now() - Timestamp(24*60*60); // 1 day
// delete old source-info entries to prevent memory usage creep
HashMap<IPDuo, SrcInfo>::iterator iter = _src_info.begin();
for (; iter != _src_info.end(); iter++) {
if (iter.value().last_updated < thresh) {
// todo - change to debug after testing
_log->warning("expiring SrcInfo for %s", iter.key().unparse().c_str());
_src_info.remove(iter.key());
}
}
if ((_snort_stdout == NULL) && (_snort_stderr == NULL)) {
// process appears to be shutting down so reschedule timer with a short
// interval so we can quickly detect when the process ends
_timer.reschedule_after_msec(100);
} else {
// reschedule timer with a more leisurely interval
_timer.reschedule_after_sec(60);
}
}
void
Snort::selected(int fd)
{
if (fd == _sock) {
char cbuf[4096];
ssize_t rlen = recv(_sock, cbuf, sizeof(cbuf), 0);
if (rlen == -1) {
_log->strerror("recv");
return;
}
if (rlen == 0) {
_log->warning("UNIX socket recv() returned 0");
return;
}
if (rlen < (int)sizeof(Alertpkt)) {
_log->error("Alertpkt received from Snort too small (%d)", rlen);
return;
}
Alertpkt *alert = (Alertpkt*)cbuf;
Timestamp ts = Timestamp(alert->pkth.ts);
// as a special case, portscan detections create pseudo-packets as a
// means of reporting alerts - these are normal IP packets with
// ipproto=255 and the payload containing text describing the portscan
if ((alert->event.sig_id == SNORT_PORTSCAN_SIG) &&
(alert->event.classification == SNORT_PORTSCAN_CLASSIFICATION)) {
const struct click_ip *ip = (const struct click_ip*)(alert->pkt + sizeof(struct click_ether));
if (ip->ip_p != 255)
_log->warning("Portscan packet has ip-proto %d (expected 255)", ip->ip_p);
EtherAddress *src_ether = NULL;
int *capt_node_id = NULL;
IPAddress src_ip = IPAddress(ip->ip_src);
IPAddress dst_ip = IPAddress(ip->ip_dst);
IPDuo key = IPDuo(src_ip, dst_ip);
SrcInfo *infop = _src_info.findp(key);
if (infop != NULL) {
src_ether = &infop->ether;
capt_node_id = &infop->capt_node_id;
// suppress duplicate portscan alerts
Timestamp *last_scan = _last_portscan_alert.findp(*src_ether);
if ((last_scan != NULL) && (ts < (*last_scan + _portscan_window))) {
// todo - change to debug level?
_log->info("suppressing repeated portscan alert for %s",
src_ether->unparse_colon().c_str());
return;
}
} else {
_log->warning("Snort portscan packet has unknown IPDuo %s",
key.unparse().c_str());
}
int32_t priority_count = -1, connection_count = -1, ip_count = -1,
port_count = -1, port_range_low = -1, port_range_high = -1;
IPAddress ip_range_low, ip_range_high;
size_t offset = sizeof(struct click_ether) + ip->ip_hl*4;
char *txt = (char*)(alert->pkt + offset);
char *start = txt;
size_t len = alert->pkth.caplen - offset;
for (size_t i=0; i < len; i++) {
if (txt[i] != '\n')
continue;
txt[i] = '\0';
char *line = start;
start = txt + i + 1;
const char *prefix = "Priority Count:";
if (strncmp(line, prefix, strlen(prefix)) == 0) {
priority_count = (int32_t)strtol(line + strlen(prefix), NULL, 10);
continue;
}
prefix = "Connection Count:";
if (strncmp(line, prefix, strlen(prefix)) == 0) {
connection_count = (int32_t)strtol(line + strlen(prefix), NULL, 10);
continue;
}
prefix = "IP Count:";
if (strncmp(line, prefix, strlen(prefix)) == 0) {
ip_count = (int32_t)strtol(line + strlen(prefix), NULL, 10);
continue;
}
prefix = "Scanned IP Range:";
if (strncmp(line, prefix, strlen(prefix)) == 0) {
char *field = line + strlen(prefix);
while (isspace(field[0])) field++;
char *cp = strchr(field, ':');
if (cp == NULL) {
_log->error("invalid '%s' value from Snort portscan alert", prefix);
continue;
}
cp[0] = '\0';
ip_range_low = IPAddress(field);
ip_range_high = IPAddress(cp + 1);
continue;
}
prefix = "Port/Proto Count:";
if (strncmp(line, prefix, strlen(prefix)) == 0) {
port_count = (int32_t)strtol(line + strlen(prefix), NULL, 10);
continue;
}
prefix = "Port/Proto Range:";
if (strncmp(line, prefix, strlen(prefix)) == 0) {
char *field = line + strlen(prefix);
while (isspace(field[0])) field++;
char *cp = strchr(field, ':');
if (cp == NULL) {
_log->error("invalid '%s' value from Snort portscan alert", prefix);
continue;
}
cp[0] = '\0';
port_range_low = (int32_t)strtol(field, NULL, 10);
port_range_high = (int32_t)strtol(cp + 1, NULL, 10);
continue;
}
}
_log->data("Snort portscan alert: ts=%d.%06u sig=%d msg=\"%s\" src=%s port-range=%d:%d",
alert->pkth.ts.tv_sec, alert->pkth.ts.tv_usec, alert->event.sig_id,
alert->alertmsg, src_ip.unparse().c_str(), port_range_low, port_range_high);
if (_db)
db_insert_portscan(ts, (char*)alert->alertmsg,
alert->event.sig_id, priority_count, connection_count,
src_ip, ip_count, ip_range_low, ip_range_high, port_count,
port_range_low, port_range_high, src_ether, capt_node_id);
} else {
_log->data("Snort alert: ts=%d.%06u sig=%d msg=\"%s\"",
alert->pkth.ts.tv_sec, alert->pkth.ts.tv_usec, alert->event.sig_id,
alert->alertmsg);
if (_db)
db_insert_alert(ts, (char*)alert->alertmsg,
alert->event.sig_id, alert->event.sig_rev,
alert->event.classification, alert->event.priority);
WritablePacket *p;
try {
p = Packet::make(alert->pkt, alert->pkth.caplen);
}
catch (std::bad_alloc &ex) {
// warning - could be quite spammy
_log->warning("Packet::make() failed for len=%d", alert->pkth.caplen);
return;
}
p->set_timestamp_anno(ts);
p->set_mac_header(p->data());
output(0).push(p);
}
return;
}
else if (fd == _snort_stdin) {
// stop selecting until a write() call fails due to EAGAIN (in run_task)
remove_select(_snort_stdin, SELECT_WRITE);
// if there is a (previously pulled) packet ready and waiting to be
// written to snort, then schedule the task to make this happen
if (_next_packet != NULL)
_task.reschedule();
// else, no need to do anything - the task will be scheduled
// automatically by the NotifierSignal when upstream packets are
// available to be pulled
return;
}
FILE **streamp;
char line[1024];
const char *src;
line[0] = '\0';
if ((_snort_stdout != NULL) && (fd == fileno(_snort_stdout))) {
streamp = &_snort_stdout;
src = "stdout";
}
else if ((_snort_stderr != NULL) && (fd == fileno(_snort_stderr))) {
streamp = &_snort_stderr;
src = "stderr";
}
else {
// bad fd! programming error?
_log->critical("select for unknown fd: %d", fd);
return;
}
// this is sloppy - we assume that Snort will only output complete lines
// which may not be the case
if (fgets(line, sizeof(line), *streamp) == NULL) {
if (ferror(*streamp)) {
assert(ferror(*streamp));
_log->warning("error reading from Snort's %s", src);
}
remove_select(fd, SELECT_READ);
(void) fclose(*streamp);
*streamp = NULL;
// if both stdout and stderr have hit EOF, then the process has
// probably quit (or is doing so), so check it
if ((_snort_stdout == NULL) && (_snort_stderr == NULL))
_timer.schedule_now();
return;
}
// strip leading and trailing spaces
char *c = line;
while (isspace(*c))
c++;
char *end = c + strlen(c) - 1;
while ((end > c) && isspace(*end)) {
*end = '\0';
end--;
}
if (strlen(c) > 0)
_log->info("Snort %s: %s", src, c);
}
bool
Snort::check_snort_proc(int sig, bool blocking)
{
if (_snort_pid == 0) return false; // process is not running
int status;
int options = blocking ? 0 : WNOHANG;
pid_t rv = waitpid(_snort_pid, &status, options);
if (rv == 0) {
assert(!blocking);
return true; // process is still alive
}
if (rv == -1) {
_log->warning("waitpid failed for snort pid %d: %s", _snort_pid,
strerror(errno));
return false; // assume process is dead
}
// make sure that waitpid's status is what we expect
assert(WIFSIGNALED(status) || WIFEXITED(status));
if (WIFEXITED(status)) {
_log->info("snort pid %d exitted normally with status %d",
_snort_pid, WEXITSTATUS(status));
}
else if (WIFSIGNALED(status)) {
if (WTERMSIG(status) == sig) {
// ok great - this is what we expect
_log->debug("snort pid %d terminated by signal %d as expected",
_snort_pid, sig);
} else {
_log->warning("snort pid %d terminated by signal %d", _snort_pid,
WTERMSIG(status));
}
}
_snort_pid = 0;
if (_snort_stdin != -1) {
remove_select(_snort_stdin, SELECT_WRITE);
(void) close(_snort_stdin);
}
if (_snort_stdout != NULL) {
remove_select(fileno(_snort_stdout), SELECT_READ);
(void) fclose(_snort_stdout);
}
if (_snort_stderr != NULL) {
remove_select(fileno(_snort_stderr), SELECT_READ);
(void) fclose(_snort_stderr);
}
// now that the process has quit, perform the END_CALL if one was specified
if (_end_h != NULL) {
StoredErrorHandler errh = StoredErrorHandler();
if (_end_h->call_write(&errh) < 0)
if (errh.has_error())
_log->error("END_CALL handler: %s", errh.get_last_error().c_str());
}
return false; // process is now dead
}
void
Snort::close_snort_input()
{
if (_snort_stdin == -1) return; // ignore repeated calls
remove_select(_snort_stdin, SELECT_WRITE);
_task.unschedule();
if (close(_snort_stdin) != 0)
_log->error("close(stdin) to snort: %s", strerror(errno));
_snort_stdin = -1;
}
void
Snort::db_insert_alert(const Timestamp &ts, const char *msg, uint32_t sig_id,
uint32_t sig_rev, uint32_t classification, uint32_t priority)
{
Vector<const char*> values;
// note - neither raw_node_id nor agg_node_id columns are used because we
// currently have no way to know the sniffer-id from packets spit out by
// Snort
static const String query = String("INSERT INTO snort_alerts"
" (timestamp, message, sig_id, sig_rev, classification, priority)"
" VALUES"
" (timestamptz 'epoch' + $1 * interval '1 second', $2, $3, $4, $5, $6);");
String ts_str = ts.unparse();
String sig_id_str = String(sig_id);
String sig_rev_str = String(sig_rev);
String classification_str = String(classification);
String priority_str = String(priority);
values.push_back(ts_str.c_str());
values.push_back(msg);
values.push_back(sig_id_str.c_str());
values.push_back(sig_rev_str.c_str());
values.push_back(classification_str.c_str());
values.push_back(priority_str.c_str());
StoredErrorHandler errh = StoredErrorHandler();
int rv = _db->db_execute(query, values, &errh);
if (rv < 0) {
StringAccum sa;
for (int i=0; i < values.size(); i++)
sa << String(values[i]) << " | ";
_log->error("db_insert_alert failed: %s (args: %s)",
errh.get_last_error().c_str(), sa.take_string().c_str());
}
else if (rv == 1)
_log->debug("1 row inserted for sig_id %d", sig_id);
else
// should never affect 0 or >1 rows
_log->error("%d rows inserted for dig_id %d", rv, sig_id);
}
void
Snort::db_insert_portscan(const Timestamp &ts, const char *msg, uint32_t sig_id,
int32_t priority_count, int32_t connection_count, IPAddress src_ip,
int32_t ip_count, IPAddress ip_range_low, IPAddress ip_range_high,
int32_t port_count, int32_t port_range_low, int32_t port_range_high,
EtherAddress *src_ether, int *capt_node_id)
{
Vector<const char*> values;
static const String query = String("INSERT INTO snort_portscans"
" (timestamp, message, sig_id, priority_count, connection_count, src_ip"
", ip_count, ip_range_low, ip_range_high, port_count, port_range_low"
", port_range_high, src_ether, capt_node_id)"
" VALUES"
" (timestamptz 'epoch' + $1 * interval '1 second', $2, $3, $4, $5, $6"
", $7, $8, $9, $10, $11, $12, $13, $14);");
String ts_str = ts.unparse();
String sig_id_str = String(sig_id);
String priority_count_str = String(priority_count);
String connection_count_str = String(connection_count);
String src_ip_str = src_ip.unparse();
String ip_count_str = String(ip_count);
String ip_range_low_str = ip_range_low.unparse();
String ip_range_high_str = ip_range_high.unparse();
String port_count_str = String(port_count);
String port_range_low_str = String(port_range_low);
String port_range_high_str = String(port_range_high);
String src_ether_str;
String capt_node_id_str;
values.push_back(ts_str.c_str());
values.push_back(msg);
values.push_back(sig_id_str.c_str());
values.push_back(priority_count_str.c_str());
values.push_back(connection_count_str.c_str());
values.push_back(src_ip_str.c_str());
values.push_back(ip_count_str.c_str());
values.push_back(ip_range_low_str.c_str());
values.push_back(ip_range_high_str.c_str());
values.push_back(port_count_str.c_str());
values.push_back(port_range_low_str.c_str());
values.push_back(port_range_high_str.c_str());
if (src_ether == NULL) {
values.push_back(NULL);
} else {
src_ether_str = src_ether->unparse_colon();
values.push_back(src_ether_str.c_str());
}
if (capt_node_id == NULL) {
values.push_back(NULL);
} else {
capt_node_id_str = String(*capt_node_id);
values.push_back(capt_node_id_str.c_str());
}
StoredErrorHandler errh = StoredErrorHandler();
int rv = _db->db_execute(query, values, &errh);
if (rv < 0) {
StringAccum sa;
for (int i=0; i < values.size(); i++)
sa << String(values[i]) << " | ";
_log->error("db_insert_portscan failed: %s (args: %s)",
errh.get_last_error().c_str(), sa.take_string().c_str());
}
else if (rv == 1)
_log->debug("1 row inserted for sig_id %d", sig_id);
else
// should never affect 0 or >1 rows
_log->error("%d rows inserted for dig_id %d", rv, sig_id);
}
int
Snort::signal_snort_proc(int sig, ErrorHandler *errh)
{
if (_snort_pid == 0) return errh->error("snort process already dead");
if (kill(_snort_pid, sig) != 0)
return errh->error("kill(%d, %d): %s", _snort_pid, sig, strerror(errno));
_log->debug("signal %d sent to snort pid %d", sig, _snort_pid);
return 0;
}
int
Snort::write_handler(const String &, Element *e, void *thunk,
ErrorHandler *errh)
{
Snort *elt = static_cast<Snort *>(e);
int which = reinterpret_cast<intptr_t>(thunk);
switch (which) {
case H_CLOSE:
elt->close_snort_input();
return 0;
case H_KILL:
return elt->signal_snort_proc(SIGKILL, errh);
case H_QUIT:
// it doesn't make much sense to include this handler on this element,
// except that it allows easy implementation of the 'STOP true'
// configuration option
elt->router()->please_stop_driver();
return 0;
case H_STOP:
return elt->signal_snort_proc(SIGTERM, errh);
default:
return errh->error("internal error (bad thunk value)");
}
}
CLICK_ENDDECLS
ELEMENT_REQUIRES(userlevel)
EXPORT_ELEMENT(Snort)
| [
"ianrose14@gmail.com"
] | ianrose14@gmail.com |
e3fde5f200fbadfcc5cbb5cb73f3f615f7a6da62 | ff69e57cfc17fcca6eb2a299eecfd7f46260470f | /rdPhysicS/rdPhysicS/src/rdps-frwk/base/Actor.cpp | 7e7364c28c500e05c15b85f355c47b6d53576324 | [
"MIT"
] | permissive | rdPhysicS-framework/rdPhysicalS | 890b19a65d48e8c455e56f948d7e3d94f08c803f | 0c4cd477169f2a573b1130f5d2867c04ce139368 | refs/heads/master | 2023-01-01T12:26:23.476934 | 2020-10-26T01:41:59 | 2020-10-26T01:41:59 | 103,205,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,138 | cpp | #include "Actor.h"
#include "..\Util\Transform.h"
USING_RDPS
USING_FRWK
Actor::Actor() :
transform(new Transform),
tag()
{}
//Actor::Actor(Transform *_transform) :
// transform(_transform),
// tag()
//{}
/*Actor::Actor(const RT::Vec3f &position,
const RT::Vec3f &rotation,
const RT::Vec3f &scale) :
transform(new Transform(position,
rotation,
scale))
{}*/
/*Actor::Actor(const RT::Vec3f &position) :
transform(new Transform(position))
{}*/
Actor::Actor(const Actor &other) :
transform(other.transform->Clone()),
tag(other.tag)
{}
Actor::~Actor()
{
if (transform)
delete transform;
}
Actor *Actor::Clone() const
{
return new Actor(*this);
}
Actor &Actor::operator=(const Actor &other)
{
*transform = *other.transform;
tag = other.tag;
return (*this);
}
Transform *Actor::GetTransform() const
{
return transform;
}
const std::string &Actor::GetTag() const
{
return tag;
}
Actor &Actor::SetTansform(const Transform &_transform)
{
*transform = _transform;
return (*this);
}
Actor &Actor::SetTag(const std::string _tag)
{
tag = _tag;
return (*this);
}
| [
"alisson.silva@pucpr.edu.br"
] | alisson.silva@pucpr.edu.br |
f79e1869618ad4628b046be13dc0445a51569e8b | 7b1e19e69dec1f81e49abf37e0813998e6a6bc88 | /Hello_World/main_from_sml.cpp | 4b729b856680a9c6bc41bd14e4556dbeacc1d73f | [] | no_license | gitJaesik/cpp | 68a1d5b7600e9d6da0cbba3caf49801d41bef233 | ea29d5e4655b42c650be5e60d299488b8cc9b267 | refs/heads/master | 2020-03-16T23:56:11.242154 | 2018-05-22T06:57:09 | 2018-05-22T06:57:09 | 133,096,732 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 2,346 | cpp | #include<iostream>
#include<windows.h>
using namespace std;
#define BOARD_X 10
#define BOARD_Y 20
int board[BOARD_Y][BOARD_X];
//7개 4,4 배열
int block[7][4][4] = {
{
{ 0,0,0,0 },
{ 0,1,1,0 },
{ 0,1,1,0 },
{ 0,0,0,0 }
},
{
{ 0,1,0,0 },
{ 0,1,0,0 },
{ 0,1,0,0 },
{ 0,1,0,0 }
},
{
{ 0,1,0,0 },
{ 0,1,0,0 },
{ 0,1,1,0 },
{ 0,0,0,0 }
},
{
{ 0,0,1,0 },
{ 0,0,1,0 },
{ 0,1,1,0 },
{ 0,0,0,0 }
},
{
{ 0,0,0,0 },
{ 0,0,1,0 },
{ 0,1,1,0 },
{ 0,1,0,0 }
},
{
{ 0,0,0,0 },
{ 0,1,0,0 },
{ 0.1,1,0 },
{ 0,0,1,0 }
},
{
{ 0,1,0,0 },
{ 0,1,1,0 },
{ 0,1,0,0 },
{ 0,0,0,0 }
}
};
void ioSetCursorPosition(int x, int y) {
COORD pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void clearBoard() {
ioSetCursorPosition(0, 0);
for (int i = 0; i < BOARD_Y; ++i)
{
for (int j = 0; j < BOARD_X; ++j) {
cout << " "; //cout[i][j];
}
cout << "\n";
}
ioSetCursorPosition(0, 0);
}
void printBoard() {
ioSetCursorPosition(0, 0);
for (int y = 0; y < BOARD_Y; ++y) {
for (int x = 0; x < BOARD_X; ++x) {
if (board[y][x] == 1) {
cout << "■";
}
else
cout << " ";
}
cout << '\n';
}
}
void render(int x, int y) { // 첫번째 블럭 출력
ioSetCursorPosition(x, y);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (block[0][i][j] == 1) {
cout << "■";
}
else
cout << " ";
}
cout << '\n';
}
}
bool checkBlock(int x, int y) {
bool check = false;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (board[y + i][x + j] == 1 && block[0][i][j] == 1) {
check = true;
break;
}
}
if (true == check) break;
}
if (false == check) return false;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
board[y - 1 + i][x+j] == block[0][i][i];
}
}
return true;
}
int main() {
for (int i = 0; i < BOARD_X; i++) {
board[BOARD_Y - 1][i] = 1;
}
while (true) {
int x = 5;
int y = 0;
while (true) {
printBoard();
render(x, y);
Sleep(600);
clearBoard();
y++;
if (checkBlock(x, y)) {
y--;
break;
}
}
}
getchar();
getchar();
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
63660764e8f6e037cd35448c0ced1a73ec535b10 | c4eaa3e6cdca0ef6eea9487735369fb4d215949f | /2DAE07_Geers_Pieter_digdug/Minigin/SMState.h | a75769f2a9ae15d3d99bcb7106e931d3d609cfce | [] | no_license | PieterGeers/DigDug | 483fc09f6425501aea7e690831517d695c56bea2 | b69e05ca025558a089d1d10bda1ee01677292a54 | refs/heads/master | 2022-02-26T02:42:53.016532 | 2019-10-31T15:37:02 | 2019-10-31T15:37:02 | 175,878,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,087 | h | #pragma once
#include <vector>
class GameObject;
class SMAction;
class SMTransition;
class SMState final
{
public:
SMState(std::vector<SMAction*> entryActions, std::vector<SMAction*> actions,
std::vector<SMAction*> exitActions, std::vector<SMTransition*> transitions);
SMState() = default;
~SMState();
void SetEntryActions(std::vector<SMAction*> entryActions);
void SetEntryAction(SMAction* entryAction);
void SetActions(std::vector<SMAction*> actions);
void SetAction(SMAction* action);
void SetExitActions(std::vector<SMAction*> exitActions);
void SetExitAction(SMAction* exitAction);
void SetTransitions(std::vector<SMTransition*> transitions);
void SetTransition(SMTransition* transition);
void RunAction(int idx) const;
void RunEntryActions(int idx) const;
void RunExitActions(int idx) const;
std::vector<SMTransition*> GetTransition() const { return m_Transitions; }
private:
std::vector<SMAction*> m_EntryActions = {};
std::vector<SMAction*> m_Actions = {};
std::vector<SMAction*> m_ExitActions = {};
std::vector<SMTransition*> m_Transitions = {};
};
| [
"48602601+PieterGeers@users.noreply.github.com"
] | 48602601+PieterGeers@users.noreply.github.com |
f0d9fd310da0333e79f64434be99d034a8c97393 | 482ec3480e8418dda62f85a5359e70c89256f1a8 | /cpp/BOOST/mpl/eval_if.cpp | 7486de3b90e7e5d8c61b417f027ab98755bf0036 | [] | no_license | rajatgirotra/study | 84d319968f31f78798a56362546f21d22abd7ae7 | acbb6d21a8182feabcb3329e17c76ac3af375255 | refs/heads/master | 2023-09-01T20:48:31.137541 | 2023-08-29T01:41:17 | 2023-08-29T01:41:17 | 85,041,241 | 6 | 1 | null | 2023-05-01T19:25:38 | 2017-03-15T07:17:24 | C++ | UTF-8 | C++ | false | false | 261 | cpp | #include <boost/mpl/eval_if.hpp>
#include <boost/mpl/bool.hpp>
/* Usage:
mpl::eval_if<C, f1, f2>
C is a type. if C::value == true, then
mpl::eval_if<>::type is same as f1, else
mpl::eval_if<>::type is same as f2
*/
int main() {
return 0;
}
| [
"rajatgirotra@yahoo.com"
] | rajatgirotra@yahoo.com |
f80cbe6b8e78a9838889008a21fe2bc32af124ba | 8607c9280f255091e4d96f2bb231723261e20cc9 | /任务管理器/ModuleDlg.h | 8f926fa94940cd0e33db4daabd3dc59589a8e640 | [] | no_license | hhjstill/taskmanager | 444503d1e9ee3f10531c2ad5d3e88ee10264f359 | dbc0aa14993be616c4c238232bc30511e148840c | refs/heads/master | 2020-04-02T08:27:15.342101 | 2018-10-23T01:59:21 | 2018-10-23T01:59:21 | 154,245,417 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 578 | h | #pragma once
#include "afxcmn.h"
// CModuleDlg 对话框
class CModuleDlg : public CDialogEx
{
DECLARE_DYNAMIC(CModuleDlg)
public:
CModuleDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~CModuleDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG2 };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
void showAllModule();
DECLARE_MESSAGE_MAP()
public:
CListCtrl m_moduleList;
virtual BOOL OnInitDialog();
afx_msg void OnBnClickedButton1();
int m_edit;
afx_msg void OnBnClickedButton2();
};
| [
"496358226@qq.com"
] | 496358226@qq.com |
afb14793909587a7af7c4e085355bb404942f8d1 | 52505166e409b44caf7a0b144ef0c453b586fcee | /bug-detection/flex-nlp/sim/sim_model/src/idu_PE1_core_run_mac_out_4.cc | ef87acd72f9b24c85be6332a911b2ef12c120780 | [] | no_license | yuex1994/ASPDAC-tandem | fb090975c65edbdda68c19a8d7e7a5f0ff96bcb8 | decdabc5743c2116d1fc0e339e434b9e13c430a8 | refs/heads/master | 2023-08-28T04:37:30.011721 | 2021-08-07T13:19:23 | 2021-08-07T13:19:30 | 419,089,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | cc | #include <flex.h>
bool flex::decode_PE1_CORE_RUN_MAC_CHILD_PE1_core_run_mac_out_4() {
sc_biguint<1> local_var_1 = 1;
bool local_var_2 = (PE1_CORE_CHILD_pe1_core_child_run_mac_flag == local_var_1);
sc_biguint<5> local_var_4 = 16;
bool local_var_5 = (PE1_CORE_CHILD_pe1_core_child_run_mac_cntr < local_var_4);
bool local_var_6 = (local_var_2 & local_var_5);
sc_biguint<4> local_var_8 = 3;
bool local_var_9 = (PE1_CORE_CHILD_pe1_core_run_mac_child_state == local_var_8);
bool local_var_10 = (local_var_6 & local_var_9);
sc_biguint<5> local_var_11 = 4;
bool local_var_12 = (PE1_CORE_CHILD_pe1_core_child_run_mac_cntr == local_var_11);
bool local_var_13 = (local_var_10 & local_var_12);
auto& univ_var_49 = local_var_13;
return univ_var_49;
}
void flex::update_PE1_CORE_RUN_MAC_CHILD_PE1_core_run_mac_out_4() {
auto local_var_2 = AccumAdd2(PE1_CORE_CHILD_PE1_core_accum_vector_4, PE1_CORE_RUN_MAC_CHILD_pe1_core_run_mac_child_result_temp);
auto local_var_2_nxt_holder = local_var_2;
sc_biguint<5> local_var_4 = 1;
sc_biguint<5> local_var_5 = (PE1_CORE_CHILD_pe1_core_child_run_mac_cntr + local_var_4);
auto local_var_5_nxt_holder = local_var_5;
sc_biguint<5> local_var_6 = 15;
bool local_var_7 = (PE1_CORE_CHILD_pe1_core_child_run_mac_cntr == local_var_6);
bool local_var_8 = (PE1_CORE_CHILD_pe1_core_child_run_mac_cntr > local_var_6);
bool local_var_9 = (local_var_7 | local_var_8);
sc_biguint<1> local_var_10 = 0;
sc_biguint<1> local_var_11 = 1;
auto local_var_12 = (local_var_9) ? local_var_10 : local_var_11;
auto local_var_12_nxt_holder = local_var_12;
sc_biguint<1> local_var_14 = 1;
bool local_var_15 = (flex_pe1_rnn_layer_sizing_is_cluster == local_var_14);
sc_biguint<4> local_var_16 = 1;
sc_biguint<4> local_var_17 = 0;
auto local_var_18 = (local_var_15) ? local_var_16 : local_var_17;
auto local_var_18_nxt_holder = local_var_18;
PE1_CORE_CHILD_PE1_core_accum_vector_4 = local_var_2_nxt_holder;
PE1_CORE_CHILD_pe1_core_child_run_mac_cntr = local_var_5_nxt_holder;
PE1_CORE_CHILD_pe1_core_child_run_mac_flag = local_var_12_nxt_holder;
PE1_CORE_CHILD_pe1_core_run_mac_child_state = local_var_18_nxt_holder;
}
| [
"anonymizeddac2020submission@gmail.com"
] | anonymizeddac2020submission@gmail.com |
0d9a08437249bae3b66deb7d39403b0e4f121ccd | 87043710768ab029c749d8d816d3ff01a759ed07 | /Project1/sse.h | 34d2b8bf04c02177b710e4b9f0612e34831739ef | [] | no_license | dorodnic/simd_tests | 57ac9dab64376e46763303a872c50889d4196c59 | ce5cef6a7c32a7b7860add0d593bed01eeb56ca4 | refs/heads/master | 2020-03-07T06:18:39.099544 | 2018-04-03T12:09:16 | 2018-04-03T12:09:16 | 127,318,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,573 | h | #pragma once
#include "core.h"
#include "sse_shuffle.h"
#include "sse_operators.h"
namespace simd
{
template<>
struct fallback_engine<DEFAULT> { static const engine_type FT = NAIVE; };
template<>
struct engine<DEFAULT>
{
static bool can_run() { return true; }
template<typename T, typename Dummy = int>
struct native_simd {};
template<typename Dummy>
struct native_simd<float, Dummy>
{
public:
typedef __m128 underlying_type;
typedef native_simd<float> representation_type;
typedef native_simd<float> this_type;
FORCEINLINE static void load(representation_type& target, const underlying_type* other)
{
target._data = _mm_castsi128_ps(_mm_loadu_si128((const __m128i*)other));
}
FORCEINLINE static void store(const representation_type& src, underlying_type* target)
{
_mm_storeu_ps((float*)target, src._data);
}
FORCEINLINE static underlying_type vectorize(float x)
{
return _mm_set_ps1(x);
}
FORCEINLINE native_simd(underlying_type data) : _data(data) {}
FORCEINLINE native_simd(const underlying_type* data) : _data(_mm_castsi128_ps(_mm_loadu_si128((const __m128i*)data))) {}
FORCEINLINE native_simd() : _data(_mm_set_ps1(0)) {}
FORCEINLINE native_simd(const native_simd& data) { _data = data._data; }
FORCEINLINE native_simd operator+(const native_simd& y) const
{
return native_simd(_mm_add_ps(_data, y._data));
}
FORCEINLINE native_simd operator-(const native_simd& y) const
{
return native_simd(_mm_sub_ps(_data, y._data));
}
FORCEINLINE native_simd operator/(const native_simd& y) const
{
return native_simd(_mm_div_ps(_data, y._data));
}
FORCEINLINE native_simd operator*(const native_simd& y) const
{
return native_simd(_mm_mul_ps(_data, y._data));
}
FORCEINLINE void store(underlying_type* ptr) const
{
_mm_storeu_ps((float*)ptr, _data);
}
FORCEINLINE operator underlying_type() const { return _data; }
private:
underlying_type _data;
};
static __m128i load_mask(unsigned int x)
{
return _mm_set_epi32(
(x & 0xff000000) ? 0xffffffff : 0,
(x & 0x00ff0000) ? 0xffffffff : 0,
(x & 0x0000ff00) ? 0xffffffff : 0,
(x & 0x000000ff) ? 0xffffffff : 0);
}
template<class T, unsigned int START, unsigned int GAP>
struct gather_utils {};
template<unsigned int START, unsigned int GAP>
struct gather_utils<float, START, GAP>
{
template<class GT, class QT, unsigned int J>
static void do_gather(const QT& res, GT& result)
{
const auto shuf = sse::gather_shuffle<GAP, START, J>::shuffle();
const auto mask = sse::gather_shuffle<GAP, START, J>::mask();
auto s1 = res.fetch(J);
auto res1 = _mm_shuffle_ps(s1, s1, shuf);
auto res1i = _mm_castps_si128(res1);
res1i = _mm_and_si128(res1i, load_mask(mask));
res1 = _mm_castsi128_ps(res1i);
auto so_far = result.fetch(0);
result.assign(0, _mm_or_ps(res1, so_far));
}
template<class GT, class QT, unsigned int J>
struct gather_loop
{
static void gather(const QT& res, GT& result)
{
do_gather<GT, QT, J - 1>(res, result);
gather_loop<GT, QT, J - 1>::gather(res, result);
}
};
template<class GT, class QT>
struct gather_loop<GT, QT, 0>
{
static void gather(const QT& res, GT& result) {}
};
template<class GT, class QT>
static void gather(const QT& res, GT& result)
{
// Go over every block of QT
// Do gather on it
// Merge everything into block GT[I]
gather_loop<GT, QT, QT::blocks>::gather(res, result);
}
};
template<class T, unsigned int START, unsigned int GAP>
struct scatter_utils {};
template<unsigned int START, unsigned int GAP>
struct scatter_utils<float, START, GAP>
{
template<class OT, class ST, unsigned int LINE>
static void do_scatter(OT& output_block, const ST& curr_var)
{
const auto gap = GAP;
const auto start = START;
const auto line = LINE;
const auto shuf = sse::scatter_shuffle<GAP, START, LINE>::shuffle();
const auto mask = sse::scatter_shuffle<GAP, START, LINE>::mask();
// Take the value from curr_var[0],
// (being var with offset START and GAP)
// and scatter it over output_block[LINE]
auto s1 = curr_var.fetch(0);
auto res1 = _mm_shuffle_ps(s1, s1, shuf);
auto res1i = _mm_castps_si128(res1);
res1i = _mm_and_si128(res1i, load_mask(mask));
res1 = _mm_castsi128_ps(res1i);
auto so_far = output_block.fetch(LINE);
output_block.assign(LINE, _mm_or_ps(res1, so_far));
}
template<class OT, class ST, unsigned int J>
struct scatter_loop
{
static void scatter(OT& output_block, const ST& curr_var)
{
do_scatter<OT, ST, J - 1>(output_block, curr_var);
scatter_loop<OT, ST, J - 1>::scatter(output_block, curr_var);
}
};
template<class OT, class ST>
struct scatter_loop<OT, ST, 0>
{
static void scatter(OT& output_block, const ST& curr_var) {}
};
template<class OT, class ST>
static void scatter(OT& output_block, const ST& curr_var)
{
scatter_loop<OT, ST, OT::blocks>::scatter(output_block, curr_var);
}
};
};
}
| [
"sergey.dorodnicov@intel.com"
] | sergey.dorodnicov@intel.com |
109cd4676fc0163740821185be660c3666b69342 | 7920e4e0504b5faa6d93a8a4fe0c8ccd4924d16d | /components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.cc | ae158e4f98a7b004d86d946e2ecdf3bc32d756e8 | [
"BSD-3-Clause"
] | permissive | rudolfcn/chromium | 36362302b0030a220f4d53e0df6d24d677e20caa | 194f67a5a8dddfcd8594d471e30ea6b4e32f0c34 | refs/heads/master | 2023-01-14T14:15:39.016017 | 2017-06-23T16:10:47 | 2017-06-23T17:55:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,271 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.h"
#include <stddef.h>
#include <utility>
#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/time/tick_clock.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_mutable_config_values.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params_test_utils.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::_;
namespace net {
class NetworkQualityEstimator;
}
namespace data_reduction_proxy {
TestDataReductionProxyConfig::TestDataReductionProxyConfig(
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
net::NetLog* net_log,
DataReductionProxyConfigurator* configurator,
DataReductionProxyEventCreator* event_creator)
: TestDataReductionProxyConfig(
base::MakeUnique<TestDataReductionProxyParams>(),
io_task_runner,
net_log,
configurator,
event_creator) {}
TestDataReductionProxyConfig::TestDataReductionProxyConfig(
std::unique_ptr<DataReductionProxyConfigValues> config_values,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
net::NetLog* net_log,
DataReductionProxyConfigurator* configurator,
DataReductionProxyEventCreator* event_creator)
: DataReductionProxyConfig(io_task_runner,
net_log,
std::move(config_values),
configurator,
event_creator),
tick_clock_(nullptr),
network_quality_prohibitively_slow_set_(false),
network_quality_prohibitively_slow_(false),
lofi_accuracy_recording_intervals_set_(false),
is_captive_portal_(false) {
network_interfaces_.reset(new net::NetworkInterfaceList());
}
TestDataReductionProxyConfig::~TestDataReductionProxyConfig() {
}
bool TestDataReductionProxyConfig::IsNetworkQualityProhibitivelySlow(
const net::NetworkQualityEstimator* network_quality_estimator) {
if (network_quality_prohibitively_slow_set_)
return network_quality_prohibitively_slow_;
return DataReductionProxyConfig::IsNetworkQualityProhibitivelySlow(
network_quality_estimator);
}
void TestDataReductionProxyConfig::GetNetworkList(
net::NetworkInterfaceList* interfaces,
int policy) {
for (size_t i = 0; i < network_interfaces_->size(); ++i)
interfaces->push_back(network_interfaces_->at(i));
}
void TestDataReductionProxyConfig::ResetParamFlagsForTest() {
config_values_ = base::MakeUnique<TestDataReductionProxyParams>();
}
TestDataReductionProxyParams* TestDataReductionProxyConfig::test_params() {
return static_cast<TestDataReductionProxyParams*>(config_values_.get());
}
DataReductionProxyConfigValues* TestDataReductionProxyConfig::config_values() {
return config_values_.get();
}
void TestDataReductionProxyConfig::ResetLoFiStatusForTest() {
lofi_off_ = false;
}
void TestDataReductionProxyConfig::SetNetworkProhibitivelySlow(
bool network_quality_prohibitively_slow) {
network_quality_prohibitively_slow_set_ = true;
network_quality_prohibitively_slow_ = network_quality_prohibitively_slow;
}
void TestDataReductionProxyConfig::SetLofiAccuracyRecordingIntervals(
const std::vector<base::TimeDelta>& lofi_accuracy_recording_intervals) {
lofi_accuracy_recording_intervals_set_ = true;
lofi_accuracy_recording_intervals_ = lofi_accuracy_recording_intervals;
}
const std::vector<base::TimeDelta>&
TestDataReductionProxyConfig::GetLofiAccuracyRecordingIntervals() const {
if (lofi_accuracy_recording_intervals_set_)
return lofi_accuracy_recording_intervals_;
return DataReductionProxyConfig::GetLofiAccuracyRecordingIntervals();
}
void TestDataReductionProxyConfig::SetTickClock(base::TickClock* tick_clock) {
tick_clock_ = tick_clock;
}
base::TimeTicks TestDataReductionProxyConfig::GetTicksNow() const {
if (tick_clock_)
return tick_clock_->NowTicks();
return DataReductionProxyConfig::GetTicksNow();
}
bool TestDataReductionProxyConfig::WasDataReductionProxyUsed(
const net::URLRequest* request,
DataReductionProxyTypeInfo* proxy_info) const {
if (was_data_reduction_proxy_used_ &&
!was_data_reduction_proxy_used_.value()) {
return false;
}
bool was_data_reduction_proxy_used =
DataReductionProxyConfig::WasDataReductionProxyUsed(request, proxy_info);
if (proxy_info && was_data_reduction_proxy_used && proxy_index_)
proxy_info->proxy_index = proxy_index_.value();
return was_data_reduction_proxy_used;
}
void TestDataReductionProxyConfig::SetWasDataReductionProxyNotUsed() {
was_data_reduction_proxy_used_ = false;
}
void TestDataReductionProxyConfig::SetWasDataReductionProxyUsedProxyIndex(
int proxy_index) {
proxy_index_ = proxy_index;
}
void TestDataReductionProxyConfig::ResetWasDataReductionProxyUsed() {
was_data_reduction_proxy_used_.reset();
proxy_index_.reset();
}
void TestDataReductionProxyConfig::SetIsCaptivePortal(bool is_captive_portal) {
is_captive_portal_ = is_captive_portal;
}
bool TestDataReductionProxyConfig::GetIsCaptivePortal() const {
return is_captive_portal_;
}
MockDataReductionProxyConfig::MockDataReductionProxyConfig(
std::unique_ptr<DataReductionProxyConfigValues> config_values,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
net::NetLog* net_log,
DataReductionProxyConfigurator* configurator,
DataReductionProxyEventCreator* event_creator)
: TestDataReductionProxyConfig(std::move(config_values),
io_task_runner,
net_log,
configurator,
event_creator) {}
MockDataReductionProxyConfig::~MockDataReductionProxyConfig() {
}
void MockDataReductionProxyConfig::ResetLoFiStatusForTest() {
lofi_off_ = false;
}
} // namespace data_reduction_proxy
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
faec1602fc90f9ee80ae2edb27b4ec1b3ca35400 | f96a82384e4999143c749e4994b9ce49cf2c5a75 | /Homework/Chapter 3/Chap3_Prob1_Miles per Gallon/main.cpp | a34fa2824b8a81510160f52d0d245c6115010ea7 | [] | no_license | charleechaps/CSC5---RCC | da1966b3fe34dd94dbe4a0bb8ac4ba3b840bb17b | 9dc905d59f1acf8c38a4d3a32e2636de8a3da767 | refs/heads/master | 2022-04-24T03:56:10.011737 | 2020-04-28T22:19:51 | 2020-04-28T22:19:51 | 259,762,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,052 | cpp | //Diana "Charlie" Cardenas CSC5 Chapter 3, P. 143, #1
//
/*******************************************************************************
*
* COMPUTE CAR GAS MILEAGE (MPG)
* _____________________________________________________________________________
* This program computes the distance (in miles) a car can travel per one gallon
* of gas (MPG) based on gas tank capacity and the amount of miles the car can
* travel on a full tank of gas.
*
* Computation is based on the formula:
* Miles Per Gallon = Miles Per Tank of Gas / Max Gallons of Gas for Car
* _____________________________________________________________________________
* INPUT
* carGallonLimit : MAX gallons of gas the car can hold
* milesPerTank : Miles car can go on full tank of gas
*
* OUTPUT
* MPG : Miles car can drive per gallon of gas
*
******************************************************************************/
//System Libraries
#include <iostream> //Input/Output objects
using namespace std; //Name-space used in the System Library
int main() {
//Declaration of Variables
float carGallonLimit; //INPUT - MAX gallons of gas the car can hold
float milesPerTank; //INPUT - Miles car can go on full tank of gas
float MPG; //OUTPUT - Miles car can drive per gallon of gas
//Input values
cout<<"This program will calculate the MPG of a car \n";
cout<<"_____________________________________________________________"<<endl;
cout<<"Enter the Following . . . \n";
cout<<"Number of Gallons of Gas the Car Can Hold: ";
cin>>carGallonLimit;
cout<<"Number of Miles the Car Can Be Driven on a Full Tank: ";
cin>>milesPerTank;
//Process values -> Map inputs to Outputs
MPG = milesPerTank / carGallonLimit;
//Display Output
cout<<"_____________________________________________________________"<<endl;
cout<<"THE MPG OF THE CAR IS "<<MPG<<" MILES PER GALLON";
//Exit Program
return 0;
} | [
"64440601+charleechaps@users.noreply.github.com"
] | 64440601+charleechaps@users.noreply.github.com |
cf39b4f5ca07298900337b5d8c965094c1c67546 | 863e214dac1f68737dcea09df08e699de3040746 | /friendtracker/src/App.hpp | ef31dc355b17d6309e6205db84bfb12b55a71e6c | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | yf3chen/friendtracker | 74a06fa6e440fe0a7841021eaccbc6fd74d6b8d7 | b0cf29306ee8e94262f156048507bc3718241d3c | refs/heads/master | 2020-04-02T15:05:09.315710 | 2013-02-22T03:29:46 | 2013-02-22T03:29:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,881 | hpp | /* Copyright (c) 2012 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef APP_HPP
#define APP_HPP
#include <QtCore/QObject>
#include <bb/cascades/AbstractPane>
#include <bb/platform/bbm/UserProfile>
#include <bb/platform/bbm/Context>
#include <bb/system/SystemUiResult>
#include <bb/system/SystemDialog>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkAccessManager>
/**
* The main business logic object in the application.
*
* This object normally provides signals, slots and properties
* that are accessed by the main page of the application's UI.
*/
//! [0]
class App : public QObject
{
Q_OBJECT
// Add your Q_PROPERTY declarations here.
public:
App(bb::platform::bbm::Context * ctx = 0, QObject *parent = 0);
private:
bb::platform::bbm::Context * m_contextPtr;
void sendHttpRequest(QString url);
QNetworkReply * requestApi();
bb::cascades::AbstractPane *m_root;
QString m_ppid;
QNetworkAccessManager * m_nwam;
public Q_SLOTS:
void show();
private Q_SLOTS:
void dialogFinished(bb::system::SystemUiResult::Type value);
void requestFinished(QNetworkReply* reply);
// Add your slot declarations here.
void errors(QNetworkReply* reply, const QList<QSslError> & errors);
Q_SIGNALS:
void bob();
// Add your signal declarations here.
};
//! [0]
#endif
| [
"yf3chen@uwaterloo.ca"
] | yf3chen@uwaterloo.ca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.