blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2515c2a60170fb439091ad3ada60b45b8c816771 | 72a48d0be4a1257c6270f60a5f7afd9cb55eee67 | /sources/shader.cpp | d8d3fe8fa5709c690502bf8235bfec1ef12a49f7 | [] | no_license | AdamBusch/Hello-OpenGL | a0f338efc8dce47c8cb9c6e145a08f5f0bb135b3 | b5613d4a7a0d11257edc609527f0f7a63799f97c | refs/heads/master | 2020-04-14T02:08:43.144916 | 2018-12-31T08:52:12 | 2018-12-31T08:52:12 | 163,576,985 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,060 | cpp | #include "shader.h"
#include <iostream>
#include <fstream>
// TODO: Implement
// 1. Load shader source (.txt file) into memory.
// 2. Compile shader source with GLEW
// 3. Save compiled ref to memory
// 4. Bind and unbind
static void CheckShaderError(GLuint shader, GLuint flag, bool isProgram, const std::string &errorMessage);
static std::string LoadShader(const std::string &fileName);
static GLuint CreateShader(const std::string &text, GLenum shaderType);
Shader::Shader(const std::string &fileName)
{
m_program = glCreateProgram();
m_shaders[0] = CreateShader(LoadShader(fileName + ".vert"), GL_VERTEX_SHADER);
m_shaders[1] = CreateShader(LoadShader(fileName + ".frag"), GL_FRAGMENT_SHADER);
for (unsigned int i = 0; i < NUM_SHADERS; i++)
{
glAttachShader(m_program, m_shaders[i]);
}
glBindAttribLocation(m_program, 0, "position");
glLinkProgram(m_program);
CheckShaderError(m_program, GL_LINK_STATUS, true, "Error: Unable to link Shader program: " + fileName + "\n");
glValidateProgram(m_program);
CheckShaderError(m_program, GL_VALIDATE_STATUS, true, "Error: Unable to validate Shader program \"" + fileName + "\" : ");
}
Shader::~Shader()
{
for (unsigned int i = 0; i < NUM_SHADERS; i++)
{
glDetachShader(m_program, m_shaders[i]);
glDeleteShader(m_shaders[i]);
}
glDeleteProgram(m_program);
}
void Shader::Bind()
{
glUseProgram(m_program);
}
GLuint CreateShader(const std::string &text, GLenum shaderType)
{
GLuint shader = glCreateShader(shaderType);
if (shader == 0)
{
std::cerr << "Error: Unable to create shader!" << std::endl;
}
const GLchar *shaderSourceStrings[1];
GLint shaderSourceLengths[1];
shaderSourceStrings[0] = text.c_str();
shaderSourceLengths[0] = text.length();
glShaderSource(shader, 1, shaderSourceStrings, shaderSourceLengths);
glCompileShader(shader);
CheckShaderError(shader, GL_COMPILE_STATUS, false, "Error: Unable to compile Shader source: ");
return shader;
}
std::string LoadShader(const std::string &fileName)
{
std::ifstream file;
file.open((fileName).c_str());
std::string output;
std::string line;
if (file.is_open())
{
while (file.good())
{
getline(file, line);
output.append(line + "\n");
}
}
else
{
std::cerr << "Unable to load shader: " << fileName << std::endl;
}
return output;
}
void CheckShaderError(GLuint shader, GLuint flag, bool isProgram, const std::string &errorMessage)
{
GLint success = 0;
GLchar error[1024] = {0};
if (isProgram)
glGetProgramiv(shader, flag, &success);
else
glGetShaderiv(shader, flag, &success);
if (success == GL_FALSE)
{
if (isProgram)
glGetProgramInfoLog(shader, sizeof(error), NULL, error);
else
glGetShaderInfoLog(shader, sizeof(error), NULL, error);
std::cerr << errorMessage << ": '" << error << "'" << std::endl;
}
} | [
"[email protected]"
] | |
2ac989ec7ce94f7e2afe560d6ad5d049228c9e82 | 961812a6234683a6a73df817719ad7784bb7deda | /dataSets/data315.cpp | 50ed6d01c354eb7a7f26686f24dbe8e9b6254b0f | [] | no_license | galElmalah/securityProject | dc53f5a16c9f3807002523482b6b6ea8761c368b | 716a518b9f028e676162e6b0973c9c8d70443882 | refs/heads/master | 2020-04-29T11:28:49.115992 | 2019-05-19T14:43:19 | 2019-05-19T14:43:19 | 176,099,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,331 | cpp | #include <stdio.h>
int main(){
220 + 413;
173 + 325;
189 + 1804;
976 + 1083;
132 + 442;
printf("%d", 802);
printf("%d", 575);
511 + 349;
307 + 1061;
696 + 1929;
417 + 730;
printf("%d", 28);
291 + 1069;
printf("%d", 15);
printf("%d", 659);
922 + 866;
759 + 1638;
printf("%d", 877);
printf("%d", 658);
printf("%d", 178);
printf("%d", 352);
printf("%d", 950);
613 + 151;
414 + 460;
printf("%d", 718);
printf("%d", 460);
195 + 1810;
printf("%d", 728);
printf("%d", 690);
printf("%d", 169);
359 + 1259;
printf("%d", 340);
657 + 1668;
printf("%d", 510);
printf("%d", 616);
printf("%d", 674);
printf("%d", 732);
839 + 1949;
822 + 1821;
printf("%d", 823);
582 + 28;
1 + 764;
printf("%d", 573);
446 + 1600;
printf("%d", 650);
164 + 581;
91 + 491;
624 + 221;
510 + 1612;
printf("%d", 777);
776 + 447;
967 + 995;
printf("%d", 439);
printf("%d", 708);
printf("%d", 477);
printf("%d", 714);
635 + 57;
449 + 1836;
304 + 125;
printf("%d", 340);
226 + 1405;
564 + 647;
702 + 231;
559 + 1620;
printf("%d", 344);
printf("%d", 585);
787 + 1937;
printf("%d", 272);
760 + 232;
680 + 180;
printf("%d", 61);
printf("%d", 409);
206 + 1853;
68 + 6;
printf("%d", 698);
206 + 11;
printf("%d", 29);
87 + 1033;
printf("%d", 0);
155 + 540;
376 + 830;
printf("%d", 978);
975 + 246;
857 + 1841;
916 + 1737;
293 + 758;
817 + 617;
511 + 535;
97 + 1950;
printf("%d", 6);
printf("%d", 854);
246 + 395;
printf("%d", 908);
printf("%d", 58);
printf("%d", 589);
392 + 466;
printf("%d", 600);
108 + 1009;
9 + 546;
135 + 1225;
printf("%d", 840);
printf("%d", 777);
printf("%d", 721);
printf("%d", 990);
24 + 978;
733 + 163;
624 + 1149;
printf("%d", 919);
224 + 990;
printf("%d", 110);
printf("%d", 592);
printf("%d", 753);
13 + 1406;
printf("%d", 924);
548 + 271;
printf("%d", 398);
printf("%d", 510);
printf("%d", 155);
printf("%d", 824);
4 + 771;
987 + 413;
94 + 193;
140 + 1265;
441 + 1201;
printf("%d", 946);
548 + 1991;
761 + 311;
printf("%d", 801);
742 + 1006;
printf("%d", 893);
printf("%d", 670);
272 + 465;
811 + 1632;
320 + 1101;
printf("%d", 576);
573 + 1956;
printf("%d", 471);
printf("%d", 138);
printf("%d", 945);
341 + 1382;
printf("%d", 708);
printf("%d", 428);
printf("%d", 723);
866 + 135;
printf("%d", 894);
850 + 443;
762 + 806;
538 + 506;
printf("%d", 217);
printf("%d", 941);
619 + 1159;
751 + 727;
printf("%d", 300);
printf("%d", 907);
printf("%d", 679);
961 + 1993;
printf("%d", 978);
printf("%d", 762);
printf("%d", 712);
printf("%d", 242);
915 + 1125;
printf("%d", 628);
978 + 1411;
848 + 1347;
printf("%d", 906);
992 + 1348;
printf("%d", 631);
962 + 1948;
printf("%d", 236);
printf("%d", 584);
366 + 1677;
552 + 302;
800 + 62;
670 + 183;
619 + 1173;
printf("%d", 907);
printf("%d", 161);
728 + 497;
342 + 698;
printf("%d", 741);
printf("%d", 902);
702 + 1874;
784 + 1167;
376 + 1121;
printf("%d", 43);
printf("%d", 313);
printf("%d", 161);
288 + 1814;
printf("%d", 532);
842 + 1431;
940 + 423;
228 + 773;
618 + 1131;
printf("%d", 600);
printf("%d", 155);
printf("%d", 972);
printf("%d", 630);
printf("%d", 4);
474 + 533;
printf("%d", 13);
printf("%d", 980);
409 + 1604;
256 + 538;
printf("%d", 221);
printf("%d", 92);
printf("%d", 621);
printf("%d", 571);
527 + 1030;
printf("%d", 180);
printf("%d", 835);
printf("%d", 791);
22 + 1497;
printf("%d", 39);
55 + 708;
printf("%d", 947);
printf("%d", 743);
673 + 1742;
275 + 1433;
56 + 1078;
printf("%d", 668);
954 + 1272;
printf("%d", 156);
347 + 218;
printf("%d", 835);
638 + 1241;
586 + 634;
112 + 203;
printf("%d", 672);
printf("%d", 225);
printf("%d", 183);
printf("%d", 479);
435 + 1014;
162 + 1246;
882 + 1234;
114 + 441;
405 + 1910;
printf("%d", 220);
printf("%d", 129);
printf("%d", 817);
770 + 1796;
printf("%d", 312);
421 + 92;
printf("%d", 846);
printf("%d", 678);
printf("%d", 111);
512 + 851;
673 + 1900;
968 + 1948;
printf("%d", 719);
37 + 1301;
755 + 105;
619 + 668;
printf("%d", 338);
82 + 273;
626 + 1376;
printf("%d", 1);
435 + 877;
452 + 1434;
608 + 474;
printf("%d", 704);
printf("%d", 625);
printf("%d", 603);
350 + 460;
printf("%d", 785);
972 + 1588;
157 + 1935;
593 + 731;
800 + 950;
printf("%d", 866);
printf("%d", 823);
printf("%d", 619);
415 + 951;
742 + 455;
printf("%d", 41);
printf("%d", 763);
971 + 901;
printf("%d", 422);
printf("%d", 304);
400 + 443;
671 + 1475;
813 + 1569;
392 + 456;
printf("%d", 978);
370 + 1140;
824 + 995;
380 + 498;
printf("%d", 74);
printf("%d", 260);
printf("%d", 706);
892 + 1716;
printf("%d", 573);
798 + 8;
printf("%d", 275);
printf("%d", 300);
929 + 1654;
454 + 430;
178 + 591;
674 + 1776;
59 + 10;
printf("%d", 523);
364 + 622;
printf("%d", 731);
printf("%d", 528);
printf("%d", 990);
669 + 834;
916 + 666;
22 + 982;
printf("%d", 80);
404 + 383;
printf("%d", 723);
printf("%d", 235);
740 + 112;
6 + 249;
printf("%d", 4);
printf("%d", 545);
printf("%d", 681);
printf("%d", 620);
printf("%d", 684);
855 + 801;
312 + 1770;
printf("%d", 424);
512 + 351;
921 + 447;
printf("%d", 708);
450 + 1537;
printf("%d", 189);
printf("%d", 449);
printf("%d", 567);
printf("%d", 663);
14 + 1836;
937 + 205;
printf("%d", 702);
printf("%d", 796);
489 + 1794;
printf("%d", 857);
printf("%d", 94);
printf("%d", 872);
printf("%d", 307);
printf("%d", 494);
printf("%d", 959);
printf("%d", 587);
printf("%d", 564);
printf("%d", 923);
915 + 422;
printf("%d", 73);
printf("%d", 228);
printf("%d", 412);
printf("%d", 897);
933 + 1044;
834 + 249;
printf("%d", 870);
256 + 356;
26 + 449;
342 + 1072;
printf("%d", 54);
28 + 1972;
742 + 1384;
231 + 1739;
59 + 59;
printf("%d", 408);
340 + 741;
352 + 1282;
64 + 1426;
printf("%d", 90);
271 + 1906;
printf("%d", 829);
954 + 365;
printf("%d", 410);
469 + 718;
670 + 114;
printf("%d", 109);
printf("%d", 5);
582 + 152;
printf("%d", 640);
printf("%d", 138);
printf("%d", 144);
504 + 1074;
553 + 1399;
729 + 1064;
printf("%d", 218);
printf("%d", 629);
printf("%d", 791);
printf("%d", 920);
printf("%d", 169);
printf("%d", 914);
printf("%d", 588);
413 + 1648;
printf("%d", 601);
409 + 1709;
376 + 191;
printf("%d", 20);
printf("%d", 734);
108 + 939;
843 + 1176;
62 + 1462;
printf("%d", 563);
printf("%d", 256);
722 + 465;
448 + 495;
printf("%d", 706);
printf("%d", 789);
printf("%d", 935);
563 + 1920;
582 + 969;
printf("%d", 581);
651 + 1951;
printf("%d", 929);
824 + 701;
printf("%d", 800);
printf("%d", 510);
504 + 45;
992 + 1663;
650 + 811;
466 + 1886;
143 + 539;
760 + 886;
571 + 716;
printf("%d", 491);
printf("%d", 356);
614 + 1487;
78 + 1615;
printf("%d", 5);
printf("%d", 32);
printf("%d", 113);
157 + 1799;
printf("%d", 679);
printf("%d", 462);
printf("%d", 19);
496 + 600;
447 + 896;
724 + 75;
printf("%d", 481);
782 + 1693;
935 + 722;
printf("%d", 622);
118 + 279;
188 + 104;
134 + 895;
printf("%d", 420);
printf("%d", 20);
328 + 63;
174 + 1300;
printf("%d", 319);
printf("%d", 83);
372 + 1354;
599 + 1435;
333 + 1654;
printf("%d", 614);
printf("%d", 233);
645 + 537;
561 + 813;
532 + 1863;
916 + 879;
printf("%d", 917);
938 + 214;
printf("%d", 177);
344 + 1026;
printf("%d", 374);
954 + 841;
printf("%d", 920);
printf("%d", 477);
390 + 1112;
637 + 1444;
printf("%d", 614);
269 + 806;
printf("%d", 212);
printf("%d", 967);
printf("%d", 23);
printf("%d", 168);
printf("%d", 481);
71 + 1116;
615 + 994;
printf("%d", 979);
301 + 1785;
184 + 763;
printf("%d", 118);
printf("%d", 758);
6 + 1889;
printf("%d", 156);
695 + 234;
912 + 165;
printf("%d", 556);
628 + 182;
826 + 543;
124 + 892;
printf("%d", 718);
103 + 1686;
758 + 901;
printf("%d", 638);
935 + 544;
printf("%d", 534);
630 + 1421;
690 + 1045;
506 + 1151;
printf("%d", 796);
363 + 1355;
140 + 991;
printf("%d", 314);
619 + 389;
469 + 289;
999 + 1946;
586 + 1651;
248 + 1784;
printf("%d", 275);
808 + 892;
printf("%d", 296);
printf("%d", 944);
printf("%d", 572);
printf("%d", 393);
printf("%d", 456);
printf("%d", 435);
printf("%d", 414);
printf("%d", 928);
341 + 95;
printf("%d", 853);
66 + 1700;
printf("%d", 181);
printf("%d", 296);
printf("%d", 876);
417 + 1978;
printf("%d", 795);
printf("%d", 152);
printf("%d", 799);
913 + 1697;
printf("%d", 291);
892 + 1029;
printf("%d", 750);
213 + 541;
printf("%d", 176);
377 + 985;
93 + 667;
102 + 669;
622 + 1308;
printf("%d", 857);
printf("%d", 252);
286 + 198;
printf("%d", 360);
printf("%d", 502);
903 + 1585;
239 + 936;
printf("%d", 939);
printf("%d", 207);
293 + 1638;
printf("%d", 902);
801 + 63;
600 + 1866;
932 + 1842;
printf("%d", 110);
951 + 1248;
printf("%d", 376);
687 + 1750;
printf("%d", 352);
160 + 865;
printf("%d", 249);
491 + 1556;
printf("%d", 517);
73 + 1117;
printf("%d", 726);
printf("%d", 629);
printf("%d", 598);
845 + 1650;
printf("%d", 311);
850 + 1420;
281 + 752;
156 + 1064;
813 + 1828;
printf("%d", 418);
printf("%d", 533);
182 + 1694;
342 + 919;
printf("%d", 829);
8 + 1496;
991 + 491;
printf("%d", 56);
555 + 870;
printf("%d", 362);
508 + 1173;
556 + 1791;
printf("%d", 129);
944 + 1375;
printf("%d", 283);
813 + 673;
printf("%d", 127);
755 + 33;
11 + 1383;
printf("%d", 20);
printf("%d", 922);
printf("%d", 435);
646 + 516;
317 + 74;
255 + 1760;
884 + 572;
printf("%d", 857);
printf("%d", 54);
printf("%d", 130);
printf("%d", 328);
680 + 1893;
629 + 2;
printf("%d", 115);
555 + 294;
505 + 1159;
100 + 1429;
printf("%d", 718);
228 + 874;
printf("%d", 221);
633 + 1676;
printf("%d", 427);
printf("%d", 681);
printf("%d", 155);
printf("%d", 184);
90 + 948;
141 + 1900;
printf("%d", 746);
printf("%d", 539);
printf("%d", 130);
413 + 1918;
printf("%d", 804);
21 + 1424;
printf("%d", 577);
786 + 962;
855 + 1453;
745 + 1359;
543 + 1639;
996 + 322;
printf("%d", 158);
printf("%d", 810);
881 + 998;
132 + 596;
239 + 266;
747 + 1608;
printf("%d", 463);
786 + 1585;
59 + 94;
387 + 322;
printf("%d", 69);
283 + 1388;
printf("%d", 382);
864 + 1183;
923 + 561;
printf("%d", 338);
221 + 1537;
printf("%d", 928);
printf("%d", 312);
printf("%d", 948);
printf("%d", 83);
printf("%d", 789);
356 + 20;
printf("%d", 25);
printf("%d", 415);
894 + 1012;
printf("%d", 976);
printf("%d", 428);
printf("%d", 519);
268 + 393;
912 + 1123;
printf("%d", 335);
683 + 12;
67 + 656;
149 + 1249;
printf("%d", 162);
printf("%d", 503);
printf("%d", 206);
printf("%d", 367);
338 + 1292;
}
| [
"[email protected]"
] | |
65f2b82c74babffe474d335a944eb619ee3bc14c | b23d74c3f6725a9254ac0382fadf242a3aabb0e5 | /src/ui/light/drivers/aml-light/aml-light.h | 5abf7b9d1cb6de0222b418722d08ea7ff3928b03 | [
"BSD-3-Clause"
] | permissive | Eissen/fuchsia | dacd48dbfa50550d3ea34befdb536b5df5fed61d | 0df256e4ea207e2b83b11ba9c88fb1eca786a8bc | refs/heads/master | 2023-02-02T01:55:06.110096 | 2020-12-15T05:51:48 | 2020-12-15T05:51:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,611 | h | // Copyright 2019 The Fuchsia 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 SRC_UI_LIGHT_DRIVERS_AML_LIGHT_AML_LIGHT_H_
#define SRC_UI_LIGHT_DRIVERS_AML_LIGHT_AML_LIGHT_H_
#include <fuchsia/hardware/light/llcpp/fidl.h>
#include <threads.h>
#include <optional>
#include <string>
#include <vector>
#include <ddk/debug.h>
#include <ddktl/device.h>
#include <ddktl/protocol/empty-protocol.h>
#include <ddktl/protocol/gpio.h>
#include <ddktl/protocol/pwm.h>
#include <fbl/array.h>
#include <soc/aml-common/aml-pwm-regs.h>
namespace aml_light {
class AmlLight;
using AmlLightType = ddk::Device<AmlLight, ddk::Messageable>;
using ::llcpp::fuchsia::hardware::light::Capability;
using ::llcpp::fuchsia::hardware::light::Light;
using ::llcpp::fuchsia::hardware::light::LightError;
using ::llcpp::fuchsia::hardware::light::Rgb;
class LightDevice {
public:
LightDevice(std::string name, ddk::GpioProtocolClient gpio,
std::optional<ddk::PwmProtocolClient> pwm)
: name_(std::move(name)), gpio_(gpio), pwm_(pwm) {}
zx_status_t Init(bool init_on);
const std::string GetName() const { return name_; }
Capability GetCapability() const {
return pwm_.has_value() ? Capability::BRIGHTNESS : Capability::SIMPLE;
}
bool GetCurrentSimpleValue() const { return (value_ != 0); }
zx_status_t SetSimpleValue(bool value);
double GetCurrentBrightnessValue() const { return value_; }
zx_status_t SetBrightnessValue(double value);
private:
std::string name_;
ddk::GpioProtocolClient gpio_;
std::optional<ddk::PwmProtocolClient> pwm_;
double value_ = 0;
};
class AmlLight : public AmlLightType,
public Light::Interface,
public ddk::EmptyProtocol<ZX_PROTOCOL_LIGHT> {
public:
explicit AmlLight(zx_device_t* parent) : AmlLightType(parent) {}
static zx_status_t Create(void* ctx, zx_device_t* parent);
// Device protocol implementation.
zx_status_t DdkMessage(fidl_incoming_msg_t* msg, fidl_txn_t* txn);
void DdkRelease();
// FIDL messages.
void GetNumLights(GetNumLightsCompleter::Sync& completer);
void GetNumLightGroups(GetNumLightGroupsCompleter::Sync& completer);
void GetInfo(uint32_t index, GetInfoCompleter::Sync& completer);
void GetCurrentSimpleValue(uint32_t index, GetCurrentSimpleValueCompleter::Sync& completer);
void SetSimpleValue(uint32_t index, bool value, SetSimpleValueCompleter::Sync& completer);
void GetCurrentBrightnessValue(uint32_t index,
GetCurrentBrightnessValueCompleter::Sync& completer);
void SetBrightnessValue(uint32_t index, double value,
SetBrightnessValueCompleter::Sync& completer);
void GetCurrentRgbValue(uint32_t index, GetCurrentRgbValueCompleter::Sync& completer);
void SetRgbValue(uint32_t index, Rgb value, SetRgbValueCompleter::Sync& completer);
void GetGroupInfo(uint32_t group_id, GetGroupInfoCompleter::Sync& completer) {
completer.ReplyError(LightError::NOT_SUPPORTED);
}
void GetGroupCurrentSimpleValue(uint32_t group_id,
GetGroupCurrentSimpleValueCompleter::Sync& completer) {
completer.ReplyError(LightError::NOT_SUPPORTED);
}
void SetGroupSimpleValue(uint32_t group_id, ::fidl::VectorView<bool> values,
SetGroupSimpleValueCompleter::Sync& completer) {
completer.ReplyError(LightError::NOT_SUPPORTED);
}
void GetGroupCurrentBrightnessValue(uint32_t group_id,
GetGroupCurrentBrightnessValueCompleter::Sync& completer) {
completer.ReplyError(LightError::NOT_SUPPORTED);
}
void SetGroupBrightnessValue(uint32_t group_id, ::fidl::VectorView<double> values,
SetGroupBrightnessValueCompleter::Sync& completer) {
completer.ReplyError(LightError::NOT_SUPPORTED);
}
void GetGroupCurrentRgbValue(uint32_t group_id,
GetGroupCurrentRgbValueCompleter::Sync& completer) {
completer.ReplyError(LightError::NOT_SUPPORTED);
}
void SetGroupRgbValue(uint32_t group_id, ::fidl::VectorView<Rgb> values,
SetGroupRgbValueCompleter::Sync& completer) {
completer.ReplyError(LightError::NOT_SUPPORTED);
}
private:
DISALLOW_COPY_ASSIGN_AND_MOVE(AmlLight);
friend class FakeAmlLight;
zx_status_t Init();
static constexpr size_t kNameLength = ZX_MAX_NAME_LEN;
std::vector<LightDevice> lights_;
};
} // namespace aml_light
#endif // SRC_UI_LIGHT_DRIVERS_AML_LIGHT_AML_LIGHT_H_
| [
"[email protected]"
] | |
2d916a220fcf2c388e918b1fdd99c78d3d633947 | e4f93064a729d05ec4ae014038f59347ad191273 | /legacy/master-slave/slaves/slave_accelera.h | 086a23c3c96adf6460161478132bf0b3001d2d67 | [] | no_license | joschu/surgical | 221c349f8ba4e2c9c636931232821ce320004bac | 5b26795b0cc2cb8ba02e3a4a27d2c0568134d83e | refs/heads/master | 2021-01-17T22:52:12.573487 | 2011-07-19T00:56:31 | 2011-07-19T00:56:31 | 1,912,239 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,363 | h | #include "slave_mark1.h"
#include "accelera_geometry.h"
/** Identical base setup to the Slave_mark1. Using new end effector,
* so wrist kinematics are slightly different */
class Slave_accelera : public Slave_mark1 {
public:
Slave_accelera(int id, boost::shared_ptr<Controller> controller, boost::shared_ptr<System> sys);
~Slave_accelera();
Accelera_geometry* _geometry;
double* point_to_motors(double in[num_dof], double out[num_actuators], bool use_elbow_coor=false, bool use_kdl=false);
double* motors_to_point(double motor_pos[num_actuators], double out[num_dof], bool use_base_coor=false, bool use_kdl=false);
double* elbow_to_base(double in[3], double out[3]);
double* base_to_motor(double in[3], double out[3]);
double* elbow_tip_swap(double loc[3], double out[3]);
double* base_to_elbow(double in[3], double out[3]);
double* motor_to_base(double in[3], double out[3]);
double* wrist_to_tip(double in[num_dof], double out[num_actuators]);
double* point_to_tip(double in[num_dof], double out[num_dof], double* guess=NULL, bool called=false);
double* tip_to_point(double in[num_dof], double out[num_dof]);
double* CheckerboardToRobot(double in[num_dof], double out[num_dof]);
void reset_wrists();
void home();
};
| [
"[email protected]"
] | |
eb3de0c9eba4668cfe6c36566eb903f4d5dc8a63 | fb26a9bfc01a747ad8f293fbe04aeee08d699ad4 | /sensorhal/directchannel.cpp | 8d87782d4024d2248ddeed976e38ea85dcc5a4fd | [] | no_license | xorpad-og/google_device_contexthub | 0a2aa307fb23e5672bba37379103fa8699c82e62 | 3fac23e6893f15846a28852d13856f386bd64a62 | refs/heads/master | 2021-05-06T22:57:55.487166 | 2017-11-28T22:44:44 | 2017-11-28T22:44:44 | 112,890,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,755 | cpp | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "directchannel"
#include "directchannel.h"
#include <cutils/ashmem.h>
#include <hardware/sensors.h>
#include <utils/Log.h>
#include <sys/mman.h>
namespace android {
bool DirectChannelBase::isValid() {
return mBuffer != nullptr;
}
int DirectChannelBase::getError() {
return mError;
}
void DirectChannelBase::write(const sensors_event_t * ev) {
if (isValid()) {
mBuffer->write(ev, 1);
}
}
AshmemDirectChannel::AshmemDirectChannel(const struct sensors_direct_mem_t *mem) : mAshmemFd(0) {
mAshmemFd = mem->handle->data[0];
if (!::ashmem_valid(mAshmemFd)) {
mError = BAD_VALUE;
return;
}
if ((size_t)::ashmem_get_size_region(mAshmemFd) != mem->size) {
mError = BAD_VALUE;
return;
}
mSize = mem->size;
mBase = ::mmap(NULL, mem->size, PROT_WRITE, MAP_SHARED, mAshmemFd, 0);
if (mBase == nullptr) {
mError = NO_MEMORY;
return;
}
mBuffer = std::unique_ptr<LockfreeBuffer>(new LockfreeBuffer(mBase, mSize));
if (!mBuffer) {
mError = NO_MEMORY;
}
}
AshmemDirectChannel::~AshmemDirectChannel() {
if (mBase) {
mBuffer = nullptr;
::munmap(mBase, mSize);
mBase = nullptr;
}
::close(mAshmemFd);
}
ANDROID_SINGLETON_STATIC_INSTANCE(GrallocHalWrapper);
GrallocHalWrapper::GrallocHalWrapper()
: mError(NO_INIT), mVersion(-1),
mGrallocModule(nullptr), mAllocDevice(nullptr), mGralloc1Device(nullptr),
mPfnRetain(nullptr), mPfnRelease(nullptr), mPfnLock(nullptr), mPfnUnlock(nullptr),
mUnregisterImplyDelete(false) {
const hw_module_t *module;
status_t err = ::hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
ALOGE_IF(err, "couldn't load %s module (%s)", GRALLOC_HARDWARE_MODULE_ID, strerror(-err));
if (module == nullptr) {
mError = (err < 0) ? err : NO_INIT;
}
switch ((module->module_api_version >> 8) & 0xFF) {
case 0:
err = ::gralloc_open(module, &mAllocDevice);
if (err != NO_ERROR) {
ALOGE("cannot open alloc device (%s)", strerror(-err));
break;
}
if (mAllocDevice == nullptr) {
ALOGE("gralloc_open returns no error, but result is nullptr");
err = INVALID_OPERATION;
break;
}
// successfully initialized gralloc
mGrallocModule = (gralloc_module_t *)module;
mVersion = 0;
break;
case 1: {
err = ::gralloc1_open(module, &mGralloc1Device);
if (err != NO_ERROR) {
ALOGE("cannot open gralloc1 device (%s)", strerror(-err));
break;
}
if (mGralloc1Device == nullptr || mGralloc1Device->getFunction == nullptr) {
ALOGE("gralloc1_open returns no error, but result is nullptr");
err = INVALID_OPERATION;
break;
}
mPfnRetain = (GRALLOC1_PFN_RETAIN)(mGralloc1Device->getFunction(mGralloc1Device,
GRALLOC1_FUNCTION_RETAIN));
mPfnRelease = (GRALLOC1_PFN_RELEASE)(mGralloc1Device->getFunction(mGralloc1Device,
GRALLOC1_FUNCTION_RELEASE));
mPfnLock = (GRALLOC1_PFN_LOCK)(mGralloc1Device->getFunction(mGralloc1Device,
GRALLOC1_FUNCTION_LOCK));
mPfnUnlock = (GRALLOC1_PFN_UNLOCK)(mGralloc1Device->getFunction(mGralloc1Device,
GRALLOC1_FUNCTION_UNLOCK));
if (mPfnRetain == nullptr || mPfnRelease == nullptr
|| mPfnLock == nullptr || mPfnUnlock == nullptr) {
ALOGE("Function pointer for retain, release, lock and unlock are %p, %p, %p, %p",
mPfnRetain, mPfnRelease, mPfnLock, mPfnUnlock);
err = BAD_VALUE;
break;
}
int32_t caps[GRALLOC1_LAST_CAPABILITY];
uint32_t n_cap = GRALLOC1_LAST_CAPABILITY;
mGralloc1Device->getCapabilities(mGralloc1Device, &n_cap, caps);
for (size_t i = 0; i < n_cap; ++i) {
if (caps[i] == GRALLOC1_CAPABILITY_RELEASE_IMPLY_DELETE) {
mUnregisterImplyDelete = true;
}
}
ALOGI("gralloc hal %ssupport RELEASE_IMPLY_DELETE",
mUnregisterImplyDelete ? "" : "does not ");
// successfully initialized gralloc1
mGrallocModule = (gralloc_module_t *)module;
mVersion = 1;
break;
}
default:
ALOGE("Unknown version, not supported");
break;
}
mError = err;
}
GrallocHalWrapper::~GrallocHalWrapper() {
if (mAllocDevice != nullptr) {
::gralloc_close(mAllocDevice);
}
}
int GrallocHalWrapper::registerBuffer(const native_handle_t *handle) {
switch (mVersion) {
case 0:
return mGrallocModule->registerBuffer(mGrallocModule, handle);
case 1:
return mapGralloc1Error(mPfnRetain(mGralloc1Device, handle));
default:
return NO_INIT;
}
}
int GrallocHalWrapper::unregisterBuffer(const native_handle_t *handle) {
switch (mVersion) {
case 0:
return mGrallocModule->unregisterBuffer(mGrallocModule, handle);
case 1:
return mapGralloc1Error(mPfnRelease(mGralloc1Device, handle));
default:
return NO_INIT;
}
}
int GrallocHalWrapper::lock(const native_handle_t *handle,
int usage, int l, int t, int w, int h, void **vaddr) {
switch (mVersion) {
case 0:
return mGrallocModule->lock(mGrallocModule, handle, usage, l, t, w, h, vaddr);
case 1: {
const gralloc1_rect_t rect = {
.left = l,
.top = t,
.width = w,
.height = h
};
return mapGralloc1Error(mPfnLock(mGralloc1Device, handle,
GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN,
GRALLOC1_CONSUMER_USAGE_NONE,
&rect, vaddr, -1));
}
default:
return NO_INIT;
}
}
int GrallocHalWrapper::unlock(const native_handle_t *handle) {
switch (mVersion) {
case 0:
return mGrallocModule->unlock(mGrallocModule, handle);
case 1: {
int32_t dummy;
return mapGralloc1Error(mPfnUnlock(mGralloc1Device, handle, &dummy));
}
default:
return NO_INIT;
}
}
int GrallocHalWrapper::mapGralloc1Error(int grallocError) {
switch (grallocError) {
case GRALLOC1_ERROR_NONE:
return NO_ERROR;
case GRALLOC1_ERROR_BAD_DESCRIPTOR:
case GRALLOC1_ERROR_BAD_HANDLE:
case GRALLOC1_ERROR_BAD_VALUE:
return BAD_VALUE;
case GRALLOC1_ERROR_NOT_SHARED:
case GRALLOC1_ERROR_NO_RESOURCES:
return NO_MEMORY;
case GRALLOC1_ERROR_UNDEFINED:
case GRALLOC1_ERROR_UNSUPPORTED:
return INVALID_OPERATION;
default:
return UNKNOWN_ERROR;
}
}
GrallocDirectChannel::GrallocDirectChannel(const struct sensors_direct_mem_t *mem)
: mNativeHandle(nullptr) {
if (mem->handle == nullptr) {
ALOGE("mem->handle == nullptr");
mError = BAD_VALUE;
return;
}
mNativeHandle = ::native_handle_clone(mem->handle);
if (mNativeHandle == nullptr) {
ALOGE("clone mem->handle failed...");
mError = NO_MEMORY;
return;
}
mError = GrallocHalWrapper::getInstance().registerBuffer(mNativeHandle);
if (mError != NO_ERROR) {
ALOGE("registerBuffer failed");
return;
}
mError = GrallocHalWrapper::getInstance().lock(mNativeHandle,
GRALLOC_USAGE_SW_WRITE_OFTEN, 0, 0, mem->size, 1, &mBase);
if (mError != NO_ERROR) {
ALOGE("lock buffer failed");
return;
}
if (mBase == nullptr) {
ALOGE("lock buffer => nullptr");
mError = NO_MEMORY;
return;
}
mSize = mem->size;
mBuffer = std::make_unique<LockfreeBuffer>(mBase, mSize);
if (!mBuffer) {
mError = NO_MEMORY;
return;
}
mError = NO_ERROR;
}
GrallocDirectChannel::~GrallocDirectChannel() {
if (mNativeHandle != nullptr) {
if (mBase) {
mBuffer = nullptr;
GrallocHalWrapper::getInstance().unlock(mNativeHandle);
mBase = nullptr;
}
GrallocHalWrapper::getInstance().unregisterBuffer(mNativeHandle);
if (!GrallocHalWrapper::getInstance().unregisterImplyDelete()) {
::native_handle_close(mNativeHandle);
::native_handle_delete(mNativeHandle);
}
mNativeHandle = nullptr;
}
}
} // namespace android
| [
"[email protected]"
] | |
821564ccd2d07e9ac281fae9db61f395ac70e396 | 5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e | /main/source/src/protocols/kinematic_closure/perturbers/OmegaPerturber.fwd.hh | eb357f32483225420f3f572a613f280b94d9b2de | [] | no_license | MedicaicloudLink/Rosetta | 3ee2d79d48b31bd8ca898036ad32fe910c9a7a28 | 01affdf77abb773ed375b83cdbbf58439edd8719 | refs/heads/master | 2020-12-07T17:52:01.350906 | 2020-01-10T08:24:09 | 2020-01-10T08:24:09 | 232,757,729 | 2 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 997 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: [email protected].
#ifndef INCLUDED_protocols_kinematic_closure_perturbers_OmegaPerturber_FWD_HH
#define INCLUDED_protocols_kinematic_closure_perturbers_OmegaPerturber_FWD_HH
#include <utility/pointer/owning_ptr.hh>
namespace protocols {
namespace kinematic_closure {
namespace perturbers {
class OmegaPerturber;
typedef utility::pointer::shared_ptr<OmegaPerturber> OmegaPerturberOP;
typedef utility::pointer::shared_ptr<OmegaPerturber const> OmegaPerturberCOP;
}
}
}
#endif
| [
"[email protected]"
] | |
94b33877f1ea6125eafc3cfe8fbbc513f5d76803 | 75ab6a045ccfae81a1f0c5ffadeecafbfc82c475 | /day7/src/main.cpp | a13d782a4200cfab1d5c33970774c27cdaaa4982 | [] | no_license | CelestineSauvage/AdventOfCode15 | 073a491fe44e6d64f8c03b05574301153ebb0857 | 4d1d6ac4170d86d6a61b74460133ed8569b951f3 | refs/heads/master | 2022-09-13T01:34:54.284272 | 2020-06-01T14:57:18 | 2020-06-01T14:57:18 | 268,099,955 | 0 | 1 | null | 2020-06-02T11:41:04 | 2020-05-30T14:50:21 | C++ | UTF-8 | C++ | false | false | 4,111 | cpp | #include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <boost/algorithm/string.hpp>
using namespace std;
bool lights[1000][1000];
int lights2[1000][1000];
class Action
{
public:
// Constructeurs
//Accesseurs et mutateurs
void setX(pair<int, int> x) {
this->x = x;
}
void setY(pair<int, int> y) {
this->y = y;
}
pair<int, int> getX() const {
return this->x;
}
pair<int, int> getY() const {
return this->y;
}
int getX1() {
return getX().first;
}
int getX2() {
return getY().first;
}
int getY1() {
return getX().second;
}
int getY2() {
return getY().second;
}
virtual void changelights();
virtual void changebrighness();
protected:
std::pair<int,int> x,y;
};
class Toggle : public Action {
void changelights() {
for (int i = getX1() ; i <= getX2(); i++){
for (int j = getY1(); j <= getY2(); j++)
lights[i][j] = !lights[i][j];
}
}
void changebrighness() {
for (int i = getX1() ; i <= getX2(); i++){
for (int j = getY1(); j <= getY2(); j++)
lights2[i][j] = lights2[i][j]+2;
}
}
};
class TurnOn : public Action {
void changelights() {
for (int i = getX1() ; i <= getX2(); i++){
for (int j = getY1(); j <= getY2(); j++)
lights[i][j] = true;
}
}
void changebrighness() {
for (int i = getX1() ; i <= getX2(); i++){
for (int j = getY1(); j <= getY2(); j++)
lights2[i][j] = lights2[i][j] + 1;
}
}
};
class TurnOff : public Action {
void changelights() {
for (int i = getX1() ; i <= getX2(); i++){
for (int j = getY1(); j <= getY2(); j++)
lights[i][j] = false;
}
}
void changebrighness() {
for (int i = getX1() ; i <= getX2(); i++){
for (int j = getY1(); j <= getY2(); j++)
lights2[i][j] = (lights2[i][j] == 0) ? 0 : lights2[i][j]-1;
}
}
};
void initialize() {
for (int i = 0; i < 1000; i++){
for (int j = 0; j < 1000; j++)
lights[i][j] = false;
}
}
void initialize2() {
for (int i = 0; i < 1000; i++){
for (int j = 0; j < 1000; j++)
lights2[i][j] = 0;
}
}
int count() {
int res;
res = 0;
for (int i = 0; i < 1000; i++){
for (int j = 0; j < 1000; j++){
if (lights[i][j])
res++;
}
}
return res;
}
int count2() {
int res;
res = 0;
for (int i = 0; i < 1000; i++){
for (int j = 0; j < 1000; j++)
res = res + lights2[i][j];
}
return res;
}
void computeAct (Action *act, vector<string> s1, vector<string> s2){
pair<int,int> p1;
pair<int,int> p2;
p1 = make_pair(stoi(s1[0]), stoi(s1[1]));
p2 = make_pair(stoi(s2[0]), stoi(s2[1]));
act->setX(p1);
act->setY(p2);
// act->changelights();
act->changebrighness();
}
void parseLine (string line) {
vector<string> strs;
vector<string> p1;
vector<string> p2;
boost::split(strs,line,boost::is_space());
if (strs[0] == "toggle"){
Toggle act;
boost::split(p1,strs[1],boost::is_any_of(","));
boost::split(p2,strs[3],boost::is_any_of(","));
computeAct (&act, p1, p2);
}
else {
if (strs[1] == "on"){
TurnOn act;
boost::split(p1,strs[2],boost::is_any_of(","));
boost::split(p2,strs[4],boost::is_any_of(","));
computeAct (&act, p1, p2);
}
else {
if (strs[1] == "off"){
TurnOff act;
boost::split(p1,strs[2],boost::is_any_of(","));
boost::split(p2,strs[4],boost::is_any_of(","));
computeAct (&act, p1, p2);
}
else
exit(1);
}
}
}
int readfile (char * file) {
string line;
ifstream myfile;
int good;
int res;
myfile.open (file);
res = 0;
good = 0;
if (myfile.is_open()) {
if (myfile.is_open()) {
while (getline(myfile, line))
parseLine(line);
myfile.close();
}
}
else
cout << "Unable to open file";
//
// res = count();
res = count2();
return res;
}
int main(int argc, char * argv[]) {
// initialize();
initialize2();
cout << readfile(argv[1]) << '\n';
// cout << parseFloors2 (code) << '\n';
exit(0);
}
| [
"[email protected]"
] | |
e95bff75ed528a887f0027f20545fd47e9cc6ada | 8f95326c8e2ba10ee56bcbd572cfa60df7abeedb | /src/identifiers/empty.cpp | 33651993260840ea3b06f08a320ebcc3323ad90b | [
"MIT"
] | permissive | aidane1/Racket-Interpreter | 357ec29b253b3173610ec3e8faba87a4638b9610 | 84a2915d0b239ce084707fbb0cc0bf7f49897899 | refs/heads/master | 2023-01-13T16:52:57.590762 | 2020-11-26T05:54:25 | 2020-11-26T05:54:25 | 292,935,153 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | cpp | #include "evaluation.hpp"
#include "token.hpp"
#include <iostream>
Token *Evaluation::evaluate_empty(std::vector<Token *> args)
{
Token *new_token = new Token("list", list);
return new_token;
// std::cout << "hey" << "\n";
// Token *new_token = new Token("list", list);
// for (int i = 0; i < args.size(); i++)
// {
// new_token->stored_value.list.append(args[i]);
// }
// return new_token;
} | [
"[email protected]"
] | |
2ac9ff4b30988027002d50d5bd6465dbb8a0a326 | 545882210ca9bbd0d10f4f29fe7fef83703364b6 | /include/lxw_shade.hpp | 080dc156647cfeb2f775b9ea9752d137af64f6e4 | [] | no_license | kioku-systemk/mrzExporter | 8992ccf4c78f94bc284b3fb1697c1f54d5323a81 | 73d803d8b6031cda6abeebe539a12f1bcc04da4a | refs/heads/master | 2021-01-15T17:45:31.719753 | 2014-01-30T11:11:09 | 2014-01-30T11:11:09 | 12,744,819 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,580 | hpp | /*
* C++ wrapper for lxshade.h
*
* Copyright (c) 2008-2013 Luxology LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. Except as contained
* in this notice, the name(s) of the above copyright holders shall not be
* used in advertising or otherwise to promote the sale, use or other dealings
* in this Software without prior written authorization.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#ifndef LXW_SHADE_HPP
#define LXW_SHADE_HPP
#include <lxshade.h>
#include <lx_wrap.hpp>
#include <string>
namespace lx {
static const LXtGUID guid_CompShader = {0x371e8b57,0x3a1e,0x444b,0x91,0xf8,0x5e,0x43,0xc7,0x5b,0xf1,0xcb};
static const LXtGUID guid_ValueTextureCustom = {0xDE3298A6,0x1607,0x4338,0xB0,0x61,0x18,0x55,0x28,0xE6,0xFB,0x51};
static const LXtGUID guid_TextureGL = {0x55CE355E,0xC838,0x4222,0xAB,0xED,0xCB,0xDD,0x80,0x82,0x09,0xAF};
static const LXtGUID guid_CompShader1 = {0x06717e9d,0x610d,0x439f,0x93,0x5b,0xaf,0x08,0x05,0x82,0x7e,0xde};
static const LXtGUID guid_TextureLayer = {0x42369FE7,0x869E,0x4c61,0x8D,0x40,0xAC,0x62,0xE5,0x29,0xDD,0x15};
static const LXtGUID guid_CustomMaterial = {0x64e2dd96,0xff7f,0x4c9b,0x96,0x7e,0x24,0xde,0xc8,0x3b,0xfb,0x72};
static const LXtGUID guid_Texture = {0x6376D941,0x9437,0x4cf8,0xB6,0xEC,0xAB,0x50,0x79,0x1F,0xE6,0x0F};
static const LXtGUID guid_TextureVMap = {0x0C68AC79,0x993C,0x4823,0x97,0xFA,0xEA,0xD5,0xEF,0xF9,0x7B,0x64};
static const LXtGUID guid_CustomMaterial1 = {0xd0c4106c,0xdfd5,0x4a58,0xad,0x48,0x45,0xb5,0x0a,0xe6,0x3f,0x59};
static const LXtGUID guid_TextureEval = {0x847C1567,0x1725,0x4e98,0xBA,0x09,0xEA,0x1F,0x90,0x49,0xD7,0x6A};
static const LXtGUID guid_ValueTexture = {0xCA0E3524,0x6F82,0x44B8,0xAA,0xC9,0xDC,0x25,0x8F,0x54,0x8C,0x02};
static const LXtGUID guid_TextureMask = {0x701E81D3,0xFFA6,0x475a,0xA0,0x2D,0xEC,0xE9,0xAB,0x15,0xB4,0xCD};
};
class CLxImpl_CompShader {
public:
virtual ~CLxImpl_CompShader() {}
virtual LxResult
csh_SetupChannels (ILxUnknownID addChan)
{ return LXe_NOTIMPL; }
virtual LxResult
csh_LinkChannels (ILxUnknownID eval, ILxUnknownID item)
{ return LXe_NOTIMPL; }
virtual LxResult
csh_ReadChannels (ILxUnknownID attr, void **ppvData)
{ return LXe_NOTIMPL; }
virtual LxResult
csh_Customize (ILxUnknownID custom, void **ppvData)
{ return LXe_NOTIMPL; }
virtual void
csh_Evaluate (ILxUnknownID vector, ILxUnknownID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
{ }
virtual LxResult
csh_SetShadeFlags (LXpShadeFlags *sFlg)
{ return LXe_NOTIMPL; }
virtual LxResult
csh_SetOpaque (int *opaque)
{ return LXe_NOTIMPL; }
virtual LxResult
csh_CustomPacket (const char **packet)
{ return LXe_NOTIMPL; }
virtual void
csh_Cleanup (void *data)
{ }
virtual int
csh_Flags (void)
= 0;
};
#define LXxD_CompShader_SetupChannels LxResult csh_SetupChannels (ILxUnknownID addChan)
#define LXxO_CompShader_SetupChannels LXxD_CompShader_SetupChannels LXx_OVERRIDE
#define LXxD_CompShader_LinkChannels LxResult csh_LinkChannels (ILxUnknownID eval, ILxUnknownID item)
#define LXxO_CompShader_LinkChannels LXxD_CompShader_LinkChannels LXx_OVERRIDE
#define LXxD_CompShader_ReadChannels LxResult csh_ReadChannels (ILxUnknownID attr, void **ppvData)
#define LXxO_CompShader_ReadChannels LXxD_CompShader_ReadChannels LXx_OVERRIDE
#define LXxD_CompShader_Customize LxResult csh_Customize (ILxUnknownID custom, void **ppvData)
#define LXxO_CompShader_Customize LXxD_CompShader_Customize LXx_OVERRIDE
#define LXxD_CompShader_Evaluate void csh_Evaluate (ILxUnknownID vector, ILxUnknownID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
#define LXxO_CompShader_Evaluate LXxD_CompShader_Evaluate LXx_OVERRIDE
#define LXxD_CompShader_SetShadeFlags LxResult csh_SetShadeFlags (LXpShadeFlags *sFlg)
#define LXxO_CompShader_SetShadeFlags LXxD_CompShader_SetShadeFlags LXx_OVERRIDE
#define LXxD_CompShader_SetOpaque LxResult csh_SetOpaque (int *opaque)
#define LXxO_CompShader_SetOpaque LXxD_CompShader_SetOpaque LXx_OVERRIDE
#define LXxD_CompShader_CustomPacket LxResult csh_CustomPacket (const char **packet)
#define LXxO_CompShader_CustomPacket LXxD_CompShader_CustomPacket LXx_OVERRIDE
#define LXxD_CompShader_Cleanup void csh_Cleanup (void *data)
#define LXxO_CompShader_Cleanup LXxD_CompShader_Cleanup LXx_OVERRIDE
#define LXxD_CompShader_Flags int csh_Flags (void)
#define LXxO_CompShader_Flags LXxD_CompShader_Flags LXx_OVERRIDE
template <class T>
class CLxIfc_CompShader : public CLxInterface
{
static LxResult
SetupChannels (LXtObjectID wcom, LXtObjectID addChan)
{
LXCWxINST (CLxImpl_CompShader, loc);
try {
return loc->csh_SetupChannels ((ILxUnknownID)addChan);
} catch (LxResult rc) { return rc; }
}
static LxResult
LinkChannels (LXtObjectID wcom, LXtObjectID eval, LXtObjectID item)
{
LXCWxINST (CLxImpl_CompShader, loc);
try {
return loc->csh_LinkChannels ((ILxUnknownID)eval,(ILxUnknownID)item);
} catch (LxResult rc) { return rc; }
}
static LxResult
ReadChannels (LXtObjectID wcom, LXtObjectID attr, void **ppvData)
{
LXCWxINST (CLxImpl_CompShader, loc);
try {
return loc->csh_ReadChannels ((ILxUnknownID)attr,ppvData);
} catch (LxResult rc) { return rc; }
}
static LxResult
Customize (LXtObjectID wcom, LXtObjectID custom, void **ppvData)
{
LXCWxINST (CLxImpl_CompShader, loc);
try {
return loc->csh_Customize ((ILxUnknownID)custom,ppvData);
} catch (LxResult rc) { return rc; }
}
static void
Evaluate (LXtObjectID wcom, LXtObjectID vector, LXtObjectID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
{
LXCWxINST (CLxImpl_CompShader, loc);
loc->csh_Evaluate ((ILxUnknownID)vector,(ILxUnknownID)rayObj,sCmp,sOut,data);
}
static LxResult
SetShadeFlags (LXtObjectID wcom, LXpShadeFlags *sFlg)
{
LXCWxINST (CLxImpl_CompShader, loc);
try {
return loc->csh_SetShadeFlags (sFlg);
} catch (LxResult rc) { return rc; }
}
static LxResult
SetOpaque (LXtObjectID wcom, int *opaque)
{
LXCWxINST (CLxImpl_CompShader, loc);
try {
return loc->csh_SetOpaque (opaque);
} catch (LxResult rc) { return rc; }
}
static LxResult
CustomPacket (LXtObjectID wcom, const char **packet)
{
LXCWxINST (CLxImpl_CompShader, loc);
try {
return loc->csh_CustomPacket (packet);
} catch (LxResult rc) { return rc; }
}
static void
Cleanup (LXtObjectID wcom, void *data)
{
LXCWxINST (CLxImpl_CompShader, loc);
loc->csh_Cleanup (data);
}
static int
Flags (LXtObjectID wcom)
{
LXCWxINST (CLxImpl_CompShader, loc);
return loc->csh_Flags ();
}
ILxCompShader vt;
public:
CLxIfc_CompShader ()
{
vt.SetupChannels = SetupChannels;
vt.LinkChannels = LinkChannels;
vt.ReadChannels = ReadChannels;
vt.Customize = Customize;
vt.Evaluate = Evaluate;
vt.SetShadeFlags = SetShadeFlags;
vt.SetOpaque = SetOpaque;
vt.CustomPacket = CustomPacket;
vt.Cleanup = Cleanup;
vt.Flags = Flags;
vTable = &vt.iunk;
iid = &lx::guid_CompShader;
}
};
class CLxLoc_CompShader : public CLxLocalize<ILxCompShaderID>
{
public:
void _init() {m_loc=0;}
CLxLoc_CompShader() {_init();}
CLxLoc_CompShader(ILxUnknownID obj) {_init();set(obj);}
CLxLoc_CompShader(const CLxLoc_CompShader &other) {_init();set(other.m_loc);}
const LXtGUID * guid() const {return &lx::guid_CompShader;}
LxResult
SetupChannels (ILxUnknownID addChan)
{
return m_loc[0]->SetupChannels (m_loc,(ILxUnknownID)addChan);
}
LxResult
LinkChannels (ILxUnknownID eval, ILxUnknownID item)
{
return m_loc[0]->LinkChannels (m_loc,(ILxUnknownID)eval,(ILxUnknownID)item);
}
LxResult
ReadChannels (ILxUnknownID attr, void **ppvData)
{
return m_loc[0]->ReadChannels (m_loc,(ILxUnknownID)attr,ppvData);
}
LxResult
Customize (ILxUnknownID custom, void **ppvData)
{
return m_loc[0]->Customize (m_loc,(ILxUnknownID)custom,ppvData);
}
void
Evaluate (ILxUnknownID vector, ILxUnknownID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
{
m_loc[0]->Evaluate (m_loc,(ILxUnknownID)vector,(ILxUnknownID)rayObj,sCmp,sOut,data);
}
LxResult
SetShadeFlags (LXpShadeFlags *sFlg)
{
return m_loc[0]->SetShadeFlags (m_loc,sFlg);
}
LxResult
SetOpaque (int *opaque)
{
return m_loc[0]->SetOpaque (m_loc,opaque);
}
LxResult
CustomPacket (const char **packet)
{
return m_loc[0]->CustomPacket (m_loc,packet);
}
void
Cleanup (void *data)
{
m_loc[0]->Cleanup (m_loc,data);
}
int
Flags (void)
{
return m_loc[0]->Flags (m_loc);
}
};
class CLxLoc_ValueTextureCustom : public CLxLocalize<ILxValueTextureCustomID>
{
public:
void _init() {m_loc=0;}
CLxLoc_ValueTextureCustom() {_init();}
CLxLoc_ValueTextureCustom(ILxUnknownID obj) {_init();set(obj);}
CLxLoc_ValueTextureCustom(const CLxLoc_ValueTextureCustom &other) {_init();set(other.m_loc);}
const LXtGUID * guid() const {return &lx::guid_ValueTextureCustom;}
LxResult
AddFeature (LXtID4 type, const char *name)
{
return m_loc[0]->AddFeature (m_loc,type,name);
}
LxResult
AddPacket (const char *name)
{
return m_loc[0]->AddPacket (m_loc,name);
}
};
class CLxImpl_CustomMaterial {
public:
virtual ~CLxImpl_CustomMaterial() {}
virtual LxResult
cmt_SetupChannels (ILxUnknownID addChan)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_LinkChannels (ILxUnknownID eval, ILxUnknownID item)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_ReadChannels (ILxUnknownID attr, void **ppvData)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_Customize (ILxUnknownID custom, void **ppvData)
{ return LXe_NOTIMPL; }
virtual void
cmt_MaterialEvaluate (ILxUnknownID vector, void *data)
{ }
virtual void
cmt_ShaderEvaluate (ILxUnknownID vector, ILxUnknownID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
{ }
virtual LxResult
cmt_SetShadeFlags (LXpShadeFlags *sFlg)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_SetBump (float *bumpAmplitude, int *clearBump)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_SetDisplacement (float *dispDist)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_SetOpaque (int *opaque)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_SetSmoothing (double *smooth, double *angle)
{ return LXe_NOTIMPL; }
virtual LxResult
cmt_CustomPacket (const char **packet)
{ return LXe_NOTIMPL; }
virtual void
cmt_Cleanup (void *data)
{ }
virtual LxResult
cmt_UpdatePreview (int chanIdx, int *flags)
{ return LXe_NOTIMPL; }
virtual int
cmt_Flags (void)
= 0;
};
#define LXxD_CustomMaterial_SetupChannels LxResult cmt_SetupChannels (ILxUnknownID addChan)
#define LXxO_CustomMaterial_SetupChannels LXxD_CustomMaterial_SetupChannels LXx_OVERRIDE
#define LXxD_CustomMaterial_LinkChannels LxResult cmt_LinkChannels (ILxUnknownID eval, ILxUnknownID item)
#define LXxO_CustomMaterial_LinkChannels LXxD_CustomMaterial_LinkChannels LXx_OVERRIDE
#define LXxD_CustomMaterial_ReadChannels LxResult cmt_ReadChannels (ILxUnknownID attr, void **ppvData)
#define LXxO_CustomMaterial_ReadChannels LXxD_CustomMaterial_ReadChannels LXx_OVERRIDE
#define LXxD_CustomMaterial_Customize LxResult cmt_Customize (ILxUnknownID custom, void **ppvData)
#define LXxO_CustomMaterial_Customize LXxD_CustomMaterial_Customize LXx_OVERRIDE
#define LXxD_CustomMaterial_MaterialEvaluate void cmt_MaterialEvaluate (ILxUnknownID vector, void *data)
#define LXxO_CustomMaterial_MaterialEvaluate LXxD_CustomMaterial_MaterialEvaluate LXx_OVERRIDE
#define LXxD_CustomMaterial_ShaderEvaluate void cmt_ShaderEvaluate (ILxUnknownID vector, ILxUnknownID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
#define LXxO_CustomMaterial_ShaderEvaluate LXxD_CustomMaterial_ShaderEvaluate LXx_OVERRIDE
#define LXxD_CustomMaterial_SetShadeFlags LxResult cmt_SetShadeFlags (LXpShadeFlags *sFlg)
#define LXxO_CustomMaterial_SetShadeFlags LXxD_CustomMaterial_SetShadeFlags LXx_OVERRIDE
#define LXxD_CustomMaterial_SetBump LxResult cmt_SetBump (float *bumpAmplitude, int *clearBump)
#define LXxO_CustomMaterial_SetBump LXxD_CustomMaterial_SetBump LXx_OVERRIDE
#define LXxD_CustomMaterial_SetDisplacement LxResult cmt_SetDisplacement (float *dispDist)
#define LXxO_CustomMaterial_SetDisplacement LXxD_CustomMaterial_SetDisplacement LXx_OVERRIDE
#define LXxD_CustomMaterial_SetOpaque LxResult cmt_SetOpaque (int *opaque)
#define LXxO_CustomMaterial_SetOpaque LXxD_CustomMaterial_SetOpaque LXx_OVERRIDE
#define LXxD_CustomMaterial_SetSmoothing LxResult cmt_SetSmoothing (double *smooth, double *angle)
#define LXxO_CustomMaterial_SetSmoothing LXxD_CustomMaterial_SetSmoothing LXx_OVERRIDE
#define LXxD_CustomMaterial_CustomPacket LxResult cmt_CustomPacket (const char **packet)
#define LXxO_CustomMaterial_CustomPacket LXxD_CustomMaterial_CustomPacket LXx_OVERRIDE
#define LXxD_CustomMaterial_Cleanup void cmt_Cleanup (void *data)
#define LXxO_CustomMaterial_Cleanup LXxD_CustomMaterial_Cleanup LXx_OVERRIDE
#define LXxD_CustomMaterial_UpdatePreview LxResult cmt_UpdatePreview (int chanIdx, int *flags)
#define LXxO_CustomMaterial_UpdatePreview LXxD_CustomMaterial_UpdatePreview LXx_OVERRIDE
#define LXxD_CustomMaterial_Flags int cmt_Flags (void)
#define LXxO_CustomMaterial_Flags LXxD_CustomMaterial_Flags LXx_OVERRIDE
template <class T>
class CLxIfc_CustomMaterial : public CLxInterface
{
static LxResult
SetupChannels (LXtObjectID wcom, LXtObjectID addChan)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_SetupChannels ((ILxUnknownID)addChan);
} catch (LxResult rc) { return rc; }
}
static LxResult
LinkChannels (LXtObjectID wcom, LXtObjectID eval, LXtObjectID item)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_LinkChannels ((ILxUnknownID)eval,(ILxUnknownID)item);
} catch (LxResult rc) { return rc; }
}
static LxResult
ReadChannels (LXtObjectID wcom, LXtObjectID attr, void **ppvData)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_ReadChannels ((ILxUnknownID)attr,ppvData);
} catch (LxResult rc) { return rc; }
}
static LxResult
Customize (LXtObjectID wcom, LXtObjectID custom, void **ppvData)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_Customize ((ILxUnknownID)custom,ppvData);
} catch (LxResult rc) { return rc; }
}
static void
MaterialEvaluate (LXtObjectID wcom, LXtObjectID vector, void *data)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
loc->cmt_MaterialEvaluate ((ILxUnknownID)vector,data);
}
static void
ShaderEvaluate (LXtObjectID wcom, LXtObjectID vector, LXtObjectID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
loc->cmt_ShaderEvaluate ((ILxUnknownID)vector,(ILxUnknownID)rayObj,sCmp,sOut,data);
}
static LxResult
SetShadeFlags (LXtObjectID wcom, LXpShadeFlags *sFlg)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_SetShadeFlags (sFlg);
} catch (LxResult rc) { return rc; }
}
static LxResult
SetBump (LXtObjectID wcom, float *bumpAmplitude, int *clearBump)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_SetBump (bumpAmplitude,clearBump);
} catch (LxResult rc) { return rc; }
}
static LxResult
SetDisplacement (LXtObjectID wcom, float *dispDist)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_SetDisplacement (dispDist);
} catch (LxResult rc) { return rc; }
}
static LxResult
SetOpaque (LXtObjectID wcom, int *opaque)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_SetOpaque (opaque);
} catch (LxResult rc) { return rc; }
}
static LxResult
SetSmoothing (LXtObjectID wcom, double *smooth, double *angle)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_SetSmoothing (smooth,angle);
} catch (LxResult rc) { return rc; }
}
static LxResult
CustomPacket (LXtObjectID wcom, const char **packet)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_CustomPacket (packet);
} catch (LxResult rc) { return rc; }
}
static void
Cleanup (LXtObjectID wcom, void *data)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
loc->cmt_Cleanup (data);
}
static LxResult
UpdatePreview (LXtObjectID wcom, int chanIdx, int *flags)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
try {
return loc->cmt_UpdatePreview (chanIdx,flags);
} catch (LxResult rc) { return rc; }
}
static int
Flags (LXtObjectID wcom)
{
LXCWxINST (CLxImpl_CustomMaterial, loc);
return loc->cmt_Flags ();
}
ILxCustomMaterial vt;
public:
CLxIfc_CustomMaterial ()
{
vt.SetupChannels = SetupChannels;
vt.LinkChannels = LinkChannels;
vt.ReadChannels = ReadChannels;
vt.Customize = Customize;
vt.MaterialEvaluate = MaterialEvaluate;
vt.ShaderEvaluate = ShaderEvaluate;
vt.SetShadeFlags = SetShadeFlags;
vt.SetBump = SetBump;
vt.SetDisplacement = SetDisplacement;
vt.SetOpaque = SetOpaque;
vt.SetSmoothing = SetSmoothing;
vt.CustomPacket = CustomPacket;
vt.Cleanup = Cleanup;
vt.UpdatePreview = UpdatePreview;
vt.Flags = Flags;
vTable = &vt.iunk;
iid = &lx::guid_CustomMaterial;
}
};
class CLxLoc_CustomMaterial : public CLxLocalize<ILxCustomMaterialID>
{
public:
void _init() {m_loc=0;}
CLxLoc_CustomMaterial() {_init();}
CLxLoc_CustomMaterial(ILxUnknownID obj) {_init();set(obj);}
CLxLoc_CustomMaterial(const CLxLoc_CustomMaterial &other) {_init();set(other.m_loc);}
const LXtGUID * guid() const {return &lx::guid_CustomMaterial;}
LxResult
SetupChannels (ILxUnknownID addChan)
{
return m_loc[0]->SetupChannels (m_loc,(ILxUnknownID)addChan);
}
LxResult
LinkChannels (ILxUnknownID eval, ILxUnknownID item)
{
return m_loc[0]->LinkChannels (m_loc,(ILxUnknownID)eval,(ILxUnknownID)item);
}
LxResult
ReadChannels (ILxUnknownID attr, void **ppvData)
{
return m_loc[0]->ReadChannels (m_loc,(ILxUnknownID)attr,ppvData);
}
LxResult
Customize (ILxUnknownID custom, void **ppvData)
{
return m_loc[0]->Customize (m_loc,(ILxUnknownID)custom,ppvData);
}
void
MaterialEvaluate (ILxUnknownID vector, void *data)
{
m_loc[0]->MaterialEvaluate (m_loc,(ILxUnknownID)vector,data);
}
void
ShaderEvaluate (ILxUnknownID vector, ILxUnknownID rayObj, LXpShadeComponents *sCmp, LXpShadeOutput *sOut, void *data)
{
m_loc[0]->ShaderEvaluate (m_loc,(ILxUnknownID)vector,(ILxUnknownID)rayObj,sCmp,sOut,data);
}
LxResult
SetShadeFlags (LXpShadeFlags *sFlg)
{
return m_loc[0]->SetShadeFlags (m_loc,sFlg);
}
LxResult
SetBump (float *bumpAmplitude, int *clearBump)
{
return m_loc[0]->SetBump (m_loc,bumpAmplitude,clearBump);
}
LxResult
SetDisplacement (float *dispDist)
{
return m_loc[0]->SetDisplacement (m_loc,dispDist);
}
LxResult
SetOpaque (int *opaque)
{
return m_loc[0]->SetOpaque (m_loc,opaque);
}
LxResult
SetSmoothing (double *smooth, double *angle)
{
return m_loc[0]->SetSmoothing (m_loc,smooth,angle);
}
LxResult
CustomPacket (const char **packet)
{
return m_loc[0]->CustomPacket (m_loc,packet);
}
void
Cleanup (void *data)
{
m_loc[0]->Cleanup (m_loc,data);
}
LxResult
UpdatePreview (int chanIdx, int *flags)
{
return m_loc[0]->UpdatePreview (m_loc,chanIdx,flags);
}
int
Flags (void)
{
return m_loc[0]->Flags (m_loc);
}
};
class CLxLoc_Texture : public CLxLocalize<ILxTextureID>
{
public:
void _init() {m_loc=0;}
CLxLoc_Texture() {_init();}
CLxLoc_Texture(ILxUnknownID obj) {_init();set(obj);}
CLxLoc_Texture(const CLxLoc_Texture &other) {_init();set(other.m_loc);}
const LXtGUID * guid() const {return &lx::guid_Texture;}
LxResult
Locator (void **ppvObj)
{
return m_loc[0]->Locator (m_loc,ppvObj);
}
bool
Locator (CLxLocalizedObject &dest)
{
LXtObjectID obj;
dest.clear();
return LXx_OK(m_loc[0]->Locator (m_loc,&obj)) && dest.take(obj);
}
LxResult
SetLocator (ILxUnknownID tloc)
{
return m_loc[0]->SetLocator (m_loc,(ILxUnknownID)tloc);
}
LxResult
Image (void **ppvObj)
{
return m_loc[0]->Image (m_loc,ppvObj);
}
bool
Image (CLxLocalizedObject &dest)
{
LXtObjectID obj;
dest.clear();
return LXx_OK(m_loc[0]->Image (m_loc,&obj)) && dest.take(obj);
}
LxResult
SetImage (ILxUnknownID img)
{
return m_loc[0]->SetImage (m_loc,(ILxUnknownID)img);
}
const char *
ImageName (void)
{
return m_loc[0]->ImageName (m_loc);
}
LxResult
EvalImage (ILxUnknownID scene, void **ppvObj)
{
return m_loc[0]->EvalImage (m_loc,(ILxUnknownID)scene,ppvObj);
}
bool
EvalImage (ILxUnknownID scene, CLxLocalizedObject &dest)
{
LXtObjectID obj;
dest.clear();
return LXx_OK(m_loc[0]->EvalImage (m_loc,(ILxUnknownID)scene,&obj)) && dest.take(obj);
}
int
LocatorProjectionMode (double time)
{
return m_loc[0]->LocatorProjectionMode (m_loc,time);
}
int
LocatorProjectionAxis (double time)
{
return m_loc[0]->LocatorProjectionAxis (m_loc,time);
}
const char *
Effect (void)
{
return m_loc[0]->Effect (m_loc);
}
LxResult
SetEffect (const char *effect)
{
return m_loc[0]->SetEffect (m_loc,effect);
}
};
class CLxImpl_ValueTexture {
public:
virtual ~CLxImpl_ValueTexture() {}
virtual LxResult
vtx_SetupChannels (ILxUnknownID addChan)
{ return LXe_NOTIMPL; }
virtual LxResult
vtx_LinkChannels (ILxUnknownID eval, ILxUnknownID item)
{ return LXe_NOTIMPL; }
virtual LxResult
vtx_ReadChannels (ILxUnknownID attr, void **ppvData)
{ return LXe_NOTIMPL; }
virtual LxResult
vtx_Customize (ILxUnknownID custom, void **ppvData)
{ return LXe_NOTIMPL; }
virtual void
vtx_Evaluate (ILxUnknownID vector, LXpTextureOutput *tOut, void *data)
{ }
virtual void
vtx_Cleanup (void *data)
{ }
};
#define LXxD_ValueTexture_SetupChannels LxResult vtx_SetupChannels (ILxUnknownID addChan)
#define LXxO_ValueTexture_SetupChannels LXxD_ValueTexture_SetupChannels LXx_OVERRIDE
#define LXxD_ValueTexture_LinkChannels LxResult vtx_LinkChannels (ILxUnknownID eval, ILxUnknownID item)
#define LXxO_ValueTexture_LinkChannels LXxD_ValueTexture_LinkChannels LXx_OVERRIDE
#define LXxD_ValueTexture_ReadChannels LxResult vtx_ReadChannels (ILxUnknownID attr, void **ppvData)
#define LXxO_ValueTexture_ReadChannels LXxD_ValueTexture_ReadChannels LXx_OVERRIDE
#define LXxD_ValueTexture_Customize LxResult vtx_Customize (ILxUnknownID custom, void **ppvData)
#define LXxO_ValueTexture_Customize LXxD_ValueTexture_Customize LXx_OVERRIDE
#define LXxD_ValueTexture_Evaluate void vtx_Evaluate (ILxUnknownID vector, LXpTextureOutput *tOut, void *data)
#define LXxO_ValueTexture_Evaluate LXxD_ValueTexture_Evaluate LXx_OVERRIDE
#define LXxD_ValueTexture_Cleanup void vtx_Cleanup (void *data)
#define LXxO_ValueTexture_Cleanup LXxD_ValueTexture_Cleanup LXx_OVERRIDE
template <class T>
class CLxIfc_ValueTexture : public CLxInterface
{
static LxResult
SetupChannels (LXtObjectID wcom, LXtObjectID addChan)
{
LXCWxINST (CLxImpl_ValueTexture, loc);
try {
return loc->vtx_SetupChannels ((ILxUnknownID)addChan);
} catch (LxResult rc) { return rc; }
}
static LxResult
LinkChannels (LXtObjectID wcom, LXtObjectID eval, LXtObjectID item)
{
LXCWxINST (CLxImpl_ValueTexture, loc);
try {
return loc->vtx_LinkChannels ((ILxUnknownID)eval,(ILxUnknownID)item);
} catch (LxResult rc) { return rc; }
}
static LxResult
ReadChannels (LXtObjectID wcom, LXtObjectID attr, void **ppvData)
{
LXCWxINST (CLxImpl_ValueTexture, loc);
try {
return loc->vtx_ReadChannels ((ILxUnknownID)attr,ppvData);
} catch (LxResult rc) { return rc; }
}
static LxResult
Customize (LXtObjectID wcom, LXtObjectID custom, void **ppvData)
{
LXCWxINST (CLxImpl_ValueTexture, loc);
try {
return loc->vtx_Customize ((ILxUnknownID)custom,ppvData);
} catch (LxResult rc) { return rc; }
}
static void
Evaluate (LXtObjectID wcom, LXtObjectID vector, LXpTextureOutput *tOut, void *data)
{
LXCWxINST (CLxImpl_ValueTexture, loc);
loc->vtx_Evaluate ((ILxUnknownID)vector,tOut,data);
}
static void
Cleanup (LXtObjectID wcom, void *data)
{
LXCWxINST (CLxImpl_ValueTexture, loc);
loc->vtx_Cleanup (data);
}
ILxValueTexture vt;
public:
CLxIfc_ValueTexture ()
{
vt.SetupChannels = SetupChannels;
vt.LinkChannels = LinkChannels;
vt.ReadChannels = ReadChannels;
vt.Customize = Customize;
vt.Evaluate = Evaluate;
vt.Cleanup = Cleanup;
vTable = &vt.iunk;
iid = &lx::guid_ValueTexture;
}
};
class CLxLoc_ValueTexture : public CLxLocalize<ILxValueTextureID>
{
public:
void _init() {m_loc=0;}
CLxLoc_ValueTexture() {_init();}
CLxLoc_ValueTexture(ILxUnknownID obj) {_init();set(obj);}
CLxLoc_ValueTexture(const CLxLoc_ValueTexture &other) {_init();set(other.m_loc);}
const LXtGUID * guid() const {return &lx::guid_ValueTexture;}
LxResult
SetupChannels (ILxUnknownID addChan)
{
return m_loc[0]->SetupChannels (m_loc,(ILxUnknownID)addChan);
}
LxResult
LinkChannels (ILxUnknownID eval, ILxUnknownID item)
{
return m_loc[0]->LinkChannels (m_loc,(ILxUnknownID)eval,(ILxUnknownID)item);
}
LxResult
ReadChannels (ILxUnknownID attr, void **ppvData)
{
return m_loc[0]->ReadChannels (m_loc,(ILxUnknownID)attr,ppvData);
}
LxResult
Customize (ILxUnknownID custom, void **ppvData)
{
return m_loc[0]->Customize (m_loc,(ILxUnknownID)custom,ppvData);
}
void
Evaluate (ILxUnknownID vector, LXpTextureOutput *tOut, void *data)
{
m_loc[0]->Evaluate (m_loc,(ILxUnknownID)vector,tOut,data);
}
void
Cleanup (void *data)
{
m_loc[0]->Cleanup (m_loc,data);
}
};
#endif
| [
"[email protected]"
] | |
b830e65e5b6039f7b12c7b18029eacf79b7e3d4d | 99224ad2b09267051f95e87ad9e17f9bea43c007 | /adaptivity/TimeSeries.cpp | 826506391efbe9558ff98d44b5ef998757935e1c | [] | no_license | thejourneyofman/WinDolfin | bcf7bf4e7c78a7c443a3f24259527afb98ae9bbd | ffae925d449957f3d1ede14070bb9bb81ca7e97a | refs/heads/main | 2023-02-15T12:27:26.648397 | 2021-01-03T18:27:43 | 2021-01-03T18:27:43 | 325,487,994 | 1 | 0 | null | 2021-01-03T18:33:35 | 2020-12-30T07:44:37 | C++ | UTF-8 | C++ | false | false | 13,189 | cpp | // Copyright (C) 2009-2013 Chris Richardson and Anders Logg
//
// This file is part of DOLFIN.
//
// DOLFIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#ifdef HAS_HDF5
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <log/LogStream.h>
#include <common/constants.h>
#include <common/MPI.h>
#include <common/SubSystemsManager.h>
#include <io/File.h>
#include <io/HDF5File.h>
#include <io/HDF5Interface.h>
#include <la/GenericVector.h>
#include <la/GenericLinearAlgebraFactory.h>
#include <mesh/Mesh.h>
#include "TimeSeries.h"
using namespace dolfin;
//-----------------------------------------------------------------------------
template <typename T>
void TimeSeries::store_object(MPI_Comm comm, const T& object, double t,
std::vector<double>& times,
std::string series_name,
std::string group_name)
{
// Write object
// Check for pre-existing file to append to
std::string mode = "w";
if(File::exists(series_name) &&
(_vector_times.size() > 0 || _mesh_times.size() > 0))
mode = "a";
// Get file handle for low level operations
HDF5File hdf5_file(comm, series_name, mode);
const hid_t fid = hdf5_file._hdf5_file_id;
// Find existing datasets (should be equal to number of times)
std::size_t nobjs = 0;
if(HDF5Interface::has_group(fid, group_name))
nobjs = HDF5Interface::num_datasets_in_group(fid, group_name);
dolfin_assert(nobjs == times.size());
// Write new dataset (mesh or vector)
std::string dataset_name = group_name + "/" + std::to_string(nobjs);
hdf5_file.write(object, dataset_name);
// Check that time values are strictly increasing
const std::size_t n = times.size();
if (n >= 2 && (times[n - 1] - times[n - 2])*(t - times[n - 1]) < 0.0)
{
dolfin_error("TimeSeries.cpp",
"store object to time series",
"Sample points must be strictly monotone (t_0 = %g, t_1 = %g, t_2 = %g)",
times[n - 2], times[n - 1], t);
}
// Add time
times.push_back(t);
// Store time
HDF5Interface::add_attribute(fid, dataset_name, "time", t);
}
//-----------------------------------------------------------------------------
TimeSeries::TimeSeries(MPI_Comm mpi_comm, std::string name)
: _name(name + ".h5"), _cleared(false)
{
// Set default parameters
parameters = default_parameters();
// In case MPI is not already initialised
SubSystemsManager::init_mpi();
if (File::exists(_name))
{
// Read from file
const hid_t hdf5_file_id = HDF5Interface::open_file(mpi_comm, _name, "r",
true);
if (HDF5Interface::has_group(hdf5_file_id, "/Vector"))
{
const unsigned int nvecs
= HDF5Interface::num_datasets_in_group(hdf5_file_id, "/Vector");
_vector_times.clear();
for (unsigned int i = 0; i != nvecs; ++i)
{
const std::string dataset_name = "/Vector/" + std::to_string(i);
double t;
HDF5Interface::get_attribute(hdf5_file_id, dataset_name, "time", t);
_vector_times.push_back(t);
}
log(PROGRESS, "Found %d vector sample(s) in time series.",
_vector_times.size());
if (!monotone(_vector_times))
{
dolfin_error("TimeSeries.cpp",
"read time series from file",
"Sample points for vector data are not strictly monotone in series \"%s\"",
name.c_str());
}
}
if (HDF5Interface::has_group(hdf5_file_id, "/Mesh"))
{
const unsigned int nmesh
= HDF5Interface::num_datasets_in_group(hdf5_file_id, "/Mesh");
_mesh_times.clear();
for (unsigned int i = 0; i != nmesh; ++i)
{
const std::string dataset_name = "/Mesh/" + std::to_string(i);
double t;
HDF5Interface::get_attribute(hdf5_file_id, dataset_name, "time", t);
_mesh_times.push_back(t);
}
log(PROGRESS, "Found %d mesh sample(s) in time series.",
_mesh_times.size());
if (!monotone(_mesh_times))
{
dolfin_error("TimeSeries.cpp",
"read time series from file",
"Sample points for mesh data are not strictly monotone in series \"%s\"",
name.c_str());
}
}
HDF5Interface::close_file(hdf5_file_id);
}
else
log(PROGRESS, "No samples found in time series.");
}
//-----------------------------------------------------------------------------
TimeSeries::~TimeSeries()
{
// Do nothing (keep files)
}
//-----------------------------------------------------------------------------
void TimeSeries::store(const GenericVector& vector, double t)
{
// Clear earlier history first time we store a value
const bool clear_on_write = this->parameters["clear_on_write"];
if (!_cleared && clear_on_write)
clear();
// Store object
store_object(vector.mpi_comm(), vector, t, _vector_times, _name, "/Vector");
}
//-----------------------------------------------------------------------------
void TimeSeries::store(const Mesh& mesh, double t)
{
// Clear earlier history first time we store a value
const bool clear_on_write = this->parameters["clear_on_write"];
if (!_cleared && clear_on_write)
clear();
// Store object
store_object(mesh.mpi_comm(), mesh, t, _mesh_times, _name, "/Mesh");
}
//-----------------------------------------------------------------------------
void TimeSeries::retrieve(GenericVector& vector, double t,
bool interpolate) const
{
if (!File::exists(_name))
{
dolfin_error("TimeSeries.cpp",
"open file to retrieve series",
"File does not exist");
}
HDF5File hdf5_file(MPI_COMM_WORLD, _name, "r");
// Interpolate value
if (interpolate)
{
// Find closest pair
const std::pair<std::size_t, std::size_t> index_pair
= find_closest_pair(t, _vector_times, _name, "vector");
const std::size_t i0 = index_pair.first;
const std::size_t i1 = index_pair.second;
// Special case: same index
if (i0 == i1)
{
hdf5_file.read(vector, "/Vector/" + std::to_string(i0), false);
log(PROGRESS, "Reading vector value at t = %g.", _vector_times[0]);
return;
}
log(PROGRESS, "Interpolating vector value at t = %g in interval [%g, %g].",
t, _vector_times[i0], _vector_times[i1]);
// Read vectors
GenericVector& x0(vector);
std::shared_ptr<GenericVector> x1
= x0.factory().create_vector(x0.mpi_comm());
hdf5_file.read(x0, "/Vector/" + std::to_string(i0), false);
hdf5_file.read(*x1, "/Vector/" + std::to_string(i1), false);
// Check that the vectors have the same size
if (x0.size() != x1->size())
{
dolfin_error("TimeSeries.cpp",
"interpolate vector value in time series",
"Vector sizes don't match (%d and %d)",
x0.size(), x1->size());
}
// Compute weights for linear interpolation
const double dt = _vector_times[i1] - _vector_times[i0];
dolfin_assert(std::abs(dt) > DOLFIN_EPS);
const double w0 = (_vector_times[i1] - t) / dt;
const double w1 = 1.0 - w0;
// Interpolate
x0 *= w0;
x0.axpy(w1, *x1);
}
else
{
// Find closest index
const std::size_t index = find_closest_index(t, _vector_times, _name,
"vector");
log(PROGRESS, "Reading vector at t = %g (close to t = %g).",
_vector_times[index], t);
// Read vector
hdf5_file.read(vector, "/Vector/" + std::to_string(index), false);
}
}
//-----------------------------------------------------------------------------
void TimeSeries::retrieve(Mesh& mesh, double t) const
{
if (!File::exists(_name))
{
dolfin_error("TimeSeries.cpp",
"open file to retrieve series",
"File does not exist");
}
// Get index closest to given time
const std::size_t index = find_closest_index(t, _mesh_times, _name, "mesh");
log(PROGRESS, "Reading mesh at t = %g (close to t = %g).",
_mesh_times[index], t);
// Read mesh
HDF5File hdf5_file(MPI_COMM_WORLD, _name, "r");
hdf5_file.read(mesh, "/Mesh/" + std::to_string(index), false);
}
//-----------------------------------------------------------------------------
std::vector<double> TimeSeries::vector_times() const
{
return _vector_times;
}
//-----------------------------------------------------------------------------
std::vector<double> TimeSeries::mesh_times() const
{
return _mesh_times;
}
//-----------------------------------------------------------------------------
void TimeSeries::clear()
{
_vector_times.clear();
_mesh_times.clear();
_cleared = true;
}
//-----------------------------------------------------------------------------
std::string TimeSeries::str(bool verbose) const
{
std::stringstream s;
if (verbose)
{
s << str(false) << std::endl << std::endl;
s << "Vectors:";
for (std::size_t i = 0; i < _vector_times.size(); ++i)
s << " " << i << ": " << _vector_times[i];
s << std::endl;
s << "Meshes:";
for (std::size_t i = 0; i < _mesh_times.size(); ++i)
s << " " << i << ": " << _mesh_times[i];
s << std::endl;
}
else
{
s << "<Time series with "
<< _vector_times.size()
<< " vector(s) and "
<< _mesh_times.size()
<< " mesh(es)>";
}
return s.str();
}
//-----------------------------------------------------------------------------
bool TimeSeries::monotone(const std::vector<double>& times)
{
// If size of time series is 0 or 1 they are always monotone
if (times.size() < 2)
return true;
// If size is 2
if (times.size() == 2)
return times[0] < times[1];
for (std::size_t i = 0; i < times.size() - 2; i++)
{
if ((times[i + 2] - times[i + 1])*(times[i + 1] - times[i]) <= 0.0)
return false;
}
return true;
}
//-----------------------------------------------------------------------------
std::size_t TimeSeries::find_closest_index(double t,
const std::vector<double>& times,
std::string series_name,
std::string type_name)
{
// Get closest pair
const std::pair<std::size_t, std::size_t> index_pair
= find_closest_pair(t, times, series_name, type_name);
const std::size_t i0 = index_pair.first;
const std::size_t i1 = index_pair.second;
// Check which is closer
const std::size_t i = (std::abs(t - times[i0])
< std::abs(t - times[i1]) ? i0 : i1);
dolfin_debug2("Using closest value t[%d] = %g", i, times[i]);
return i;
}
//-----------------------------------------------------------------------------
std::pair<std::size_t, std::size_t>
TimeSeries::find_closest_pair(double t, const std::vector<double>& times,
std::string series_name,
std::string type_name)
{
// Must have at least one value stored
if (times.empty())
{
dolfin_error("TimeSeries.cpp",
"to retrieve data from time series",
"No %s stored in time series",
type_name.c_str());
}
// Special case: just one value stored
if (times.size() == 1)
{
dolfin_debug("Series has just one value, returning index 0.");
return std::make_pair(0, 0);
}
// Check whether series is reversed
const bool reversed = times[0] > times[1];
// Find lower bound. Note that lower_bound() returns first item
// larger than t or end of vector if no such item exists.
std::vector<double>::const_iterator lower;
if (reversed)
{
lower = std::lower_bound(times.begin(), times.end(), t,
std::greater<double>());
}
else
{
lower = std::lower_bound(times.begin(), times.end(), t,
std::less<double>());
}
// Set index lower and upper bound
std::size_t i0 = 0;
std::size_t i1 = 0;
if (lower == times.begin())
i0 = i1 = lower - times.begin();
else if (lower == times.end())
i0 = i1 = lower - times.begin() - 1;
else
{
i0 = lower - times.begin() - 1;
i1 = i0 + 1;
}
dolfin_debug1("Looking for value at time t = %g", t);
dolfin_debug4("Neighboring values are t[%d] = %g and t[%d] = %g",
i0, times[i0], i1, times[i1]);
return std::make_pair(i0, i1);
}
//-----------------------------------------------------------------------------
#endif
| [
"[email protected]"
] | |
410da70ed7a71bdf79396880ac5230bca85ee812 | c8c6901d75d2aad53ee2f6729f80f042029279aa | /streams/region/region_file.cpp | 661f24af8ba5b487e412507fb04d04ad12cc1883 | [
"MIT"
] | permissive | jomiq/godot_voxel | a88bfdcc4d2252e8506481c549a93d59f1fe7a4d | 28fe3365e793434fd4084ab5b63a630b4417acc9 | refs/heads/master | 2022-06-09T11:05:05.090516 | 2022-05-18T22:31:37 | 2022-05-18T22:31:37 | 120,922,994 | 0 | 0 | null | 2018-02-09T15:37:49 | 2018-02-09T15:37:49 | null | UTF-8 | C++ | false | false | 23,319 | cpp | #include "region_file.h"
#include "../../streams/voxel_block_serializer.h"
#include "../../util/godot/funcs.h"
#include "../../util/log.h"
#include "../../util/profiling.h"
#include "../../util/string_funcs.h"
#include "../file_utils.h"
#include <core/io/file_access.h>
#include <algorithm>
namespace zylann::voxel {
namespace {
const uint8_t FORMAT_VERSION = 3;
// Version 2 is like 3, but does not include any format information
const uint8_t FORMAT_VERSION_LEGACY_2 = 2;
const uint8_t FORMAT_VERSION_LEGACY_1 = 1;
const char *FORMAT_REGION_MAGIC = "VXR_";
const uint32_t MAGIC_AND_VERSION_SIZE = 4 + 1;
const uint32_t FIXED_HEADER_DATA_SIZE = 7 + RegionFormat::CHANNEL_COUNT;
const uint32_t PALETTE_SIZE_IN_BYTES = 256 * 4;
} // namespace
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const char *RegionFormat::FILE_EXTENSION = "vxr";
bool RegionFormat::validate() const {
ERR_FAIL_COND_V(region_size.x < 0 || region_size.x >= static_cast<int>(MAX_BLOCKS_ACROSS), false);
ERR_FAIL_COND_V(region_size.y < 0 || region_size.y >= static_cast<int>(MAX_BLOCKS_ACROSS), false);
ERR_FAIL_COND_V(region_size.z < 0 || region_size.z >= static_cast<int>(MAX_BLOCKS_ACROSS), false);
ERR_FAIL_COND_V(block_size_po2 <= 0, false);
// Test worst case limits (this does not include arbitrary metadata, so it can't be 100% accurrate...)
size_t bytes_per_block = 0;
for (unsigned int i = 0; i < channel_depths.size(); ++i) {
bytes_per_block += VoxelBufferInternal::get_depth_bit_count(channel_depths[i]) / 8;
}
bytes_per_block *= Vector3iUtil::get_volume(Vector3iUtil::create(1 << block_size_po2));
const size_t sectors_per_block = (bytes_per_block - 1) / sector_size + 1;
ERR_FAIL_COND_V(sectors_per_block > RegionBlockInfo::MAX_SECTOR_COUNT, false);
const size_t max_potential_sectors = Vector3iUtil::get_volume(region_size) * sectors_per_block;
ERR_FAIL_COND_V(max_potential_sectors > RegionBlockInfo::MAX_SECTOR_INDEX, false);
return true;
}
bool RegionFormat::verify_block(const VoxelBufferInternal &block) const {
ERR_FAIL_COND_V(block.get_size() != Vector3iUtil::create(1 << block_size_po2), false);
for (unsigned int i = 0; i < VoxelBufferInternal::MAX_CHANNELS; ++i) {
ERR_FAIL_COND_V(block.get_channel_depth(i) != channel_depths[i], false);
}
return true;
}
static uint32_t get_header_size_v3(const RegionFormat &format) {
// Which file offset blocks data is starting
// magic + version + blockinfos
return MAGIC_AND_VERSION_SIZE + FIXED_HEADER_DATA_SIZE + (format.has_palette ? PALETTE_SIZE_IN_BYTES : 0) +
Vector3iUtil::get_volume(format.region_size) * sizeof(RegionBlockInfo);
}
static bool save_header(
FileAccess &f, uint8_t version, const RegionFormat &format, const std::vector<RegionBlockInfo> &block_infos) {
f.seek(0);
f.store_buffer(reinterpret_cast<const uint8_t *>(FORMAT_REGION_MAGIC), 4);
f.store_8(version);
f.store_8(format.block_size_po2);
f.store_8(format.region_size.x);
f.store_8(format.region_size.y);
f.store_8(format.region_size.z);
for (unsigned int i = 0; i < format.channel_depths.size(); ++i) {
f.store_8(format.channel_depths[i]);
}
f.store_16(format.sector_size);
if (format.has_palette) {
f.store_8(0xff);
for (unsigned int i = 0; i < format.palette.size(); ++i) {
const Color8 c = format.palette[i];
f.store_8(c.r);
f.store_8(c.g);
f.store_8(c.b);
f.store_8(c.a);
}
} else {
f.store_8(0x00);
}
// TODO Deal with endianess, this should be little-endian
f.store_buffer(reinterpret_cast<const uint8_t *>(block_infos.data()), block_infos.size() * sizeof(RegionBlockInfo));
const size_t blocks_begin_offset = f.get_position();
#ifdef DEBUG_ENABLED
CRASH_COND(blocks_begin_offset != get_header_size_v3(format));
#endif
return true;
}
static bool load_header(
FileAccess &f, uint8_t &out_version, RegionFormat &out_format, std::vector<RegionBlockInfo> &out_block_infos) {
ERR_FAIL_COND_V(f.get_position() != 0, false);
ERR_FAIL_COND_V(f.get_length() < MAGIC_AND_VERSION_SIZE, false);
FixedArray<char, 5> magic;
fill(magic, '\0');
ERR_FAIL_COND_V(f.get_buffer(reinterpret_cast<uint8_t *>(magic.data()), 4) != 4, false);
ERR_FAIL_COND_V(strcmp(magic.data(), FORMAT_REGION_MAGIC) != 0, false);
const uint8_t version = f.get_8();
if (version == FORMAT_VERSION) {
out_format.block_size_po2 = f.get_8();
out_format.region_size.x = f.get_8();
out_format.region_size.y = f.get_8();
out_format.region_size.z = f.get_8();
for (unsigned int i = 0; i < out_format.channel_depths.size(); ++i) {
const uint8_t d = f.get_8();
ERR_FAIL_COND_V(d >= VoxelBufferInternal::DEPTH_COUNT, false);
out_format.channel_depths[i] = static_cast<VoxelBufferInternal::Depth>(d);
}
out_format.sector_size = f.get_16();
const uint8_t palette_size = f.get_8();
if (palette_size == 0xff) {
out_format.has_palette = true;
for (unsigned int i = 0; i < out_format.palette.size(); ++i) {
Color8 c;
c.r = f.get_8();
c.g = f.get_8();
c.b = f.get_8();
c.a = f.get_8();
out_format.palette[i] = c;
}
} else if (palette_size == 0x00) {
out_format.has_palette = false;
} else {
ERR_PRINT(String("Unexpected palette value: {0}").format(varray(palette_size)));
return false;
}
}
out_version = version;
out_block_infos.resize(Vector3iUtil::get_volume(out_format.region_size));
// TODO Deal with endianess
const size_t blocks_len = out_block_infos.size() * sizeof(RegionBlockInfo);
const size_t read_size = f.get_buffer((uint8_t *)out_block_infos.data(), blocks_len);
ERR_FAIL_COND_V(read_size != blocks_len, false);
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RegionFile::RegionFile() {
// Defaults
_header.format.block_size_po2 = 4;
_header.format.region_size = Vector3i(16, 16, 16);
fill(_header.format.channel_depths, VoxelBufferInternal::DEPTH_8_BIT);
_header.format.sector_size = 512;
}
RegionFile::~RegionFile() {
close();
}
Error RegionFile::open(const String &fpath, bool create_if_not_found) {
close();
_file_path = fpath;
Error file_error;
// Open existing file for read and write permissions. This should not create the file if it doesn't exist.
// Note, there is no read-only mode supported, because there was no need for it yet.
Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ_WRITE, &file_error);
if (file_error != OK) {
if (create_if_not_found) {
CRASH_COND(f != nullptr);
// Checking folders, needed for region "forests"
const CharString fpath_base_dir = fpath.get_base_dir().utf8();
const Error dir_err = check_directory_created_using_file_locker(fpath_base_dir.get_data());
if (dir_err != OK) {
return ERR_CANT_CREATE;
}
// This time, we attempt to create the file
f = FileAccess::open(fpath, FileAccess::WRITE_READ, &file_error);
if (file_error != OK) {
ERR_PRINT(String("Failed to create file {0}").format(varray(fpath)));
return file_error;
}
_header.version = FORMAT_VERSION;
ERR_FAIL_COND_V(save_header(**f) == false, ERR_FILE_CANT_WRITE);
} else {
return file_error;
}
} else {
CRASH_COND(f.is_null());
const Error header_error = load_header(**f);
if (header_error != OK) {
return header_error;
}
}
_file_access = f;
// Precalculate location of sectors and which block they contain.
// This will be useful to know when sectors get moved on insertion and removal
struct BlockInfoAndIndex {
RegionBlockInfo b;
unsigned int i;
};
// Filter only present blocks and keep the index around because it represents the 3D position of the block
std::vector<BlockInfoAndIndex> blocks_sorted_by_offset;
for (unsigned int i = 0; i < _header.blocks.size(); ++i) {
const RegionBlockInfo b = _header.blocks[i];
if (b.data != 0) {
BlockInfoAndIndex p;
p.b = b;
p.i = i;
blocks_sorted_by_offset.push_back(p);
}
}
std::sort(blocks_sorted_by_offset.begin(), blocks_sorted_by_offset.end(),
[](const BlockInfoAndIndex &a, const BlockInfoAndIndex &b) {
return a.b.get_sector_index() < b.b.get_sector_index();
});
CRASH_COND(_sectors.size() != 0);
for (unsigned int i = 0; i < blocks_sorted_by_offset.size(); ++i) {
const BlockInfoAndIndex b = blocks_sorted_by_offset[i];
Vector3i bpos = get_block_position_from_index(b.i);
for (unsigned int j = 0; j < b.b.get_sector_count(); ++j) {
_sectors.push_back(bpos);
}
}
#ifdef DEBUG_ENABLED
debug_check();
#endif
return OK;
}
Error RegionFile::close() {
ZN_PROFILE_SCOPE();
Error err = OK;
if (_file_access != nullptr) {
if (_header_modified) {
_file_access->seek(MAGIC_AND_VERSION_SIZE);
if (!save_header(**_file_access)) {
// TODO Need to do a big pass on these errors codes so we can return meaningful ones...
// Godot codes are quite limited
err = ERR_FILE_CANT_WRITE;
}
}
_file_access.unref();
}
_sectors.clear();
return err;
}
bool RegionFile::is_open() const {
return _file_access != nullptr;
}
bool RegionFile::set_format(const RegionFormat &format) {
ERR_FAIL_COND_V_MSG(_file_access != nullptr, false, "Can't set format when the file already exists");
ERR_FAIL_COND_V(!format.validate(), false);
// This will be the format used to create the next file if not found on open()
_header.format = format;
_header.blocks.resize(Vector3iUtil::get_volume(format.region_size));
return true;
}
const RegionFormat &RegionFile::get_format() const {
return _header.format;
}
bool RegionFile::is_valid_block_position(const Vector3 position) const {
return position.x >= 0 && //
position.y >= 0 && //
position.z >= 0 && //
position.x < _header.format.region_size.x && //
position.y < _header.format.region_size.y && //
position.z < _header.format.region_size.z;
}
Error RegionFile::load_block(Vector3i position, VoxelBufferInternal &out_block) {
ERR_FAIL_COND_V(_file_access == nullptr, ERR_FILE_CANT_READ);
FileAccess &f = **_file_access;
ERR_FAIL_COND_V(!is_valid_block_position(position), ERR_INVALID_PARAMETER);
const unsigned int lut_index = get_block_index_in_header(position);
ERR_FAIL_COND_V(lut_index >= _header.blocks.size(), ERR_INVALID_PARAMETER);
const RegionBlockInfo &block_info = _header.blocks[lut_index];
if (block_info.data == 0) {
return ERR_DOES_NOT_EXIST;
}
ERR_FAIL_COND_V(out_block.get_size() != out_block.get_size(), ERR_INVALID_PARAMETER);
// Configure block format
for (unsigned int channel_index = 0; channel_index < _header.format.channel_depths.size(); ++channel_index) {
out_block.set_channel_depth(channel_index, _header.format.channel_depths[channel_index]);
}
const unsigned int sector_index = block_info.get_sector_index();
const unsigned int block_begin = _blocks_begin_offset + sector_index * _header.format.sector_size;
f.seek(block_begin);
unsigned int block_data_size = f.get_32();
CRASH_COND(f.eof_reached());
ERR_FAIL_COND_V_MSG(!BlockSerializer::decompress_and_deserialize(f, block_data_size, out_block), ERR_PARSE_ERROR,
String("Failed to read block {0}").format(varray(position)));
return OK;
}
Error RegionFile::save_block(Vector3i position, VoxelBufferInternal &block) {
ERR_FAIL_COND_V(_header.format.verify_block(block) == false, ERR_INVALID_PARAMETER);
ERR_FAIL_COND_V(!is_valid_block_position(position), ERR_INVALID_PARAMETER);
ERR_FAIL_COND_V(_file_access == nullptr, ERR_FILE_CANT_WRITE);
FileAccess &f = **_file_access;
// We should be allowed to migrate before write operations
if (_header.version != FORMAT_VERSION) {
ERR_FAIL_COND_V(migrate_to_latest(f) == false, ERR_UNAVAILABLE);
}
const unsigned int lut_index = get_block_index_in_header(position);
ERR_FAIL_COND_V(lut_index >= _header.blocks.size(), ERR_INVALID_PARAMETER);
RegionBlockInfo &block_info = _header.blocks[lut_index];
if (block_info.data == 0) {
// The block isn't in the file yet, append at the end
const unsigned int end_offset = _blocks_begin_offset + _sectors.size() * _header.format.sector_size;
f.seek(end_offset);
const unsigned int block_offset = f.get_position();
// Check position matches the sectors rule
CRASH_COND((block_offset - _blocks_begin_offset) % _header.format.sector_size != 0);
BlockSerializer::SerializeResult res = BlockSerializer::serialize_and_compress(block);
ERR_FAIL_COND_V(!res.success, ERR_INVALID_PARAMETER);
f.store_32(res.data.size());
const unsigned int written_size = sizeof(uint32_t) + res.data.size();
f.store_buffer(res.data.data(), res.data.size());
const unsigned int end_pos = f.get_position();
CRASH_COND_MSG(written_size != (end_pos - block_offset),
String("written_size: {0}, block_offset: {1}, end_pos: {2}")
.format(varray(written_size, block_offset, end_pos)));
pad_to_sector_size(f);
block_info.set_sector_index((block_offset - _blocks_begin_offset) / _header.format.sector_size);
block_info.set_sector_count(get_sector_count_from_bytes(written_size));
for (unsigned int i = 0; i < block_info.get_sector_count(); ++i) {
_sectors.push_back(position);
}
_header_modified = true;
} else {
// The block is already in the file
CRASH_COND(_sectors.size() == 0);
const int old_sector_index = block_info.get_sector_index();
const int old_sector_count = block_info.get_sector_count();
CRASH_COND(old_sector_count < 1);
BlockSerializer::SerializeResult res = BlockSerializer::serialize_and_compress(block);
ERR_FAIL_COND_V(!res.success, ERR_INVALID_PARAMETER);
const std::vector<uint8_t> &data = res.data;
const size_t written_size = sizeof(uint32_t) + data.size();
const int new_sector_count = get_sector_count_from_bytes(written_size);
CRASH_COND(new_sector_count < 1);
if (new_sector_count <= old_sector_count) {
// We can write the block at the same spot
if (new_sector_count < old_sector_count) {
// The block now uses less sectors, we can compact others.
remove_sectors_from_block(position, old_sector_count - new_sector_count);
_header_modified = true;
}
const size_t block_offset = _blocks_begin_offset + old_sector_index * _header.format.sector_size;
f.seek(block_offset);
f.store_32(data.size());
f.store_buffer(data.data(), data.size());
const size_t end_pos = f.get_position();
CRASH_COND(written_size != (end_pos - block_offset));
} else {
// The block now uses more sectors, we have to move others.
// Note: we could shift blocks forward, but we can also remove the block entirely and rewrite it at the end.
// Need to investigate if it's worth implementing forward shift instead.
// TODO Prefer doing an end swap kind of thing?
// This also shifts the rest of the file so the freed sectors may get re-occupied.
remove_sectors_from_block(position, old_sector_count);
const size_t block_offset = _blocks_begin_offset + _sectors.size() * _header.format.sector_size;
f.seek(block_offset);
f.store_32(data.size());
f.store_buffer(data.data(), data.size());
const size_t end_pos = f.get_position();
CRASH_COND(written_size != (end_pos - block_offset));
pad_to_sector_size(f);
block_info.set_sector_index(_sectors.size());
for (int i = 0; i < new_sector_count; ++i) {
_sectors.push_back(Vector3u16(position));
}
_header_modified = true;
}
block_info.set_sector_count(new_sector_count);
}
return OK;
}
void RegionFile::pad_to_sector_size(FileAccess &f) {
const int64_t rpos = f.get_position() - _blocks_begin_offset;
if (rpos == 0) {
return;
}
CRASH_COND(rpos < 0);
const int64_t pad = int64_t(_header.format.sector_size) - (rpos - 1) % int64_t(_header.format.sector_size) - 1;
CRASH_COND(pad < 0);
for (int64_t i = 0; i < pad; ++i) {
// Virtual function called many times, hmmmm...
f.store_8(0);
}
}
void RegionFile::remove_sectors_from_block(Vector3i block_pos, unsigned int p_sector_count) {
ZN_PROFILE_SCOPE();
// Removes sectors from a block, starting from the last ones.
// So if a block has 5 sectors and we remove 2, the first 3 will be preserved.
// Then all following sectors are moved earlier in the file to fill the gap.
CRASH_COND(_file_access == nullptr);
CRASH_COND(p_sector_count <= 0);
FileAccess &f = **_file_access;
const unsigned int sector_size = _header.format.sector_size;
const unsigned int old_end_offset = _blocks_begin_offset + _sectors.size() * sector_size;
const unsigned int block_index = get_block_index_in_header(block_pos);
CRASH_COND(block_index >= _header.blocks.size());
RegionBlockInfo &block_info = _header.blocks[block_index];
unsigned int src_offset =
_blocks_begin_offset + (block_info.get_sector_index() + block_info.get_sector_count()) * sector_size;
unsigned int dst_offset = src_offset - p_sector_count * sector_size;
CRASH_COND(_sectors.size() < p_sector_count);
CRASH_COND(src_offset - sector_size < dst_offset);
CRASH_COND(block_info.get_sector_index() + p_sector_count > _sectors.size());
CRASH_COND(p_sector_count > block_info.get_sector_count());
CRASH_COND(dst_offset < _blocks_begin_offset);
std::vector<uint8_t> temp;
temp.resize(sector_size);
// TODO There might be a faster way to shrink a file
// Erase sectors from file
while (src_offset < old_end_offset) {
f.seek(src_offset);
const size_t read_bytes = f.get_buffer(temp.data(), sector_size);
CRASH_COND(read_bytes != sector_size); // Corrupted file
f.seek(dst_offset);
f.store_buffer(temp.data(), sector_size);
src_offset += sector_size;
dst_offset += sector_size;
}
// TODO We need to truncate the end of the file since we effectively shortened it,
// but FileAccess doesn't have any function to do that... so can't rely on EOF either
// Erase sectors from cache
_sectors.erase(_sectors.begin() + (block_info.get_sector_index() + block_info.get_sector_count() - p_sector_count),
_sectors.begin() + (block_info.get_sector_index() + block_info.get_sector_count()));
const unsigned int old_sector_index = block_info.get_sector_index();
// Reduce sectors of current block in header.
if (block_info.get_sector_count() > p_sector_count) {
block_info.set_sector_count(block_info.get_sector_count() - p_sector_count);
} else {
// Block removed
block_info.data = 0;
}
// Shift sector index of following blocks
if (old_sector_index < _sectors.size()) {
for (unsigned int i = 0; i < _header.blocks.size(); ++i) {
RegionBlockInfo &b = _header.blocks[i];
if (b.data != 0 && b.get_sector_index() > old_sector_index) {
b.set_sector_index(b.get_sector_index() - p_sector_count);
}
}
}
}
bool RegionFile::save_header(FileAccess &f) {
// We should be allowed to migrate before write operations.
if (_header.version != FORMAT_VERSION) {
ERR_FAIL_COND_V(migrate_to_latest(f) == false, false);
}
ERR_FAIL_COND_V(!zylann::voxel::save_header(f, _header.version, _header.format, _header.blocks), false);
_blocks_begin_offset = f.get_position();
_header_modified = false;
return true;
}
bool RegionFile::migrate_from_v2_to_v3(FileAccess &f, RegionFormat &format) {
ZN_PRINT_VERBOSE(zylann::format("Migrating region file {} from v2 to v3", _file_path));
// We can migrate if we know in advance what format the file should contain.
ERR_FAIL_COND_V_MSG(format.block_size_po2 == 0, false, "Cannot migrate without knowing the correct format");
// Which file offset blocks data is starting
// magic + version + blockinfos
const unsigned int old_header_size = Vector3iUtil::get_volume(format.region_size) * sizeof(uint32_t);
const unsigned int new_header_size = get_header_size_v3(format) - MAGIC_AND_VERSION_SIZE;
ERR_FAIL_COND_V_MSG(new_header_size < old_header_size, false, "New version is supposed to have larger header");
const unsigned int extra_bytes_needed = new_header_size - old_header_size;
f.seek(MAGIC_AND_VERSION_SIZE);
insert_bytes(f, extra_bytes_needed);
f.seek(0);
// Set version because otherwise `save_header` will attempt to migrate again causing stack-overflow
_header.version = FORMAT_VERSION;
return save_header(f);
}
bool RegionFile::migrate_to_latest(FileAccess &f) {
ERR_FAIL_COND_V(_file_path.is_empty(), false);
uint8_t version = _header.version;
// Make a backup?
// {
// DirAccessRef da = DirAccess::create_for_path(_file_path.get_base_dir());
// ERR_FAIL_COND_V_MSG(!da, false, String("Can't make a backup before migrating {0}").format(varray(_file_path)));
// da->copy(_file_path, _file_path + ".backup");
// }
if (version == FORMAT_VERSION_LEGACY_2) {
ERR_FAIL_COND_V(!migrate_from_v2_to_v3(f, _header.format), false);
version = FORMAT_VERSION;
}
if (version != FORMAT_VERSION) {
ERR_PRINT(String("Invalid file version: {0}").format(varray(version)));
return false;
}
_header.version = version;
return true;
}
Error RegionFile::load_header(FileAccess &f) {
ERR_FAIL_COND_V(!zylann::voxel::load_header(f, _header.version, _header.format, _header.blocks), ERR_PARSE_ERROR);
_blocks_begin_offset = f.get_position();
return OK;
}
unsigned int RegionFile::get_block_index_in_header(const Vector3i &rpos) const {
return Vector3iUtil::get_zxy_index(rpos, _header.format.region_size);
}
Vector3i RegionFile::get_block_position_from_index(uint32_t i) const {
return Vector3iUtil::from_zxy_index(i, _header.format.region_size);
}
uint32_t RegionFile::get_sector_count_from_bytes(uint32_t size_in_bytes) const {
return (size_in_bytes - 1) / _header.format.sector_size + 1;
}
unsigned int RegionFile::get_header_block_count() const {
ERR_FAIL_COND_V(!is_open(), 0);
return _header.blocks.size();
}
bool RegionFile::has_block(Vector3i position) const {
ERR_FAIL_COND_V(!is_open(), false);
ERR_FAIL_COND_V(!is_valid_block_position(position), false);
const unsigned int bi = get_block_index_in_header(position);
return _header.blocks[bi].data != 0;
}
bool RegionFile::has_block(unsigned int index) const {
ERR_FAIL_COND_V(!is_open(), false);
CRASH_COND(index >= _header.blocks.size());
return _header.blocks[index].data != 0;
}
// Checks to detect some corruption signs in the file
void RegionFile::debug_check() {
ERR_FAIL_COND(!is_open());
ERR_FAIL_COND(_file_access == nullptr);
FileAccess &f = **_file_access;
const size_t file_len = f.get_length();
for (unsigned int lut_index = 0; lut_index < _header.blocks.size(); ++lut_index) {
const RegionBlockInfo &block_info = _header.blocks[lut_index];
const Vector3i position = get_block_position_from_index(lut_index);
if (block_info.data == 0) {
continue;
}
const unsigned int sector_index = block_info.get_sector_index();
const unsigned int block_begin = _blocks_begin_offset + sector_index * _header.format.sector_size;
if (block_begin >= file_len) {
ZN_PRINT_ERROR(format("ERROR: LUT {} ({}): offset {} is larger than file size {}", lut_index, position,
block_begin, file_len));
continue;
}
f.seek(block_begin);
const size_t block_data_size = f.get_32();
const size_t pos = f.get_position();
const size_t remaining_size = file_len - pos;
if (block_data_size > remaining_size) {
ZN_PRINT_ERROR(format("ERROR: LUT {} ({}): block size at offset {} is larger than remaining size {}",
lut_index, position, block_data_size, remaining_size));
}
}
}
} // namespace zylann::voxel
| [
"[email protected]"
] | |
ceebeb01b4d72e7d39e38fa3ac2f2e900834aaea | 527739ed800e3234136b3284838c81334b751b44 | /include/RED4ext/Types/generated/AI/CoverDemandHolder.hpp | b0c7ad680a17c15bd3c7d573fe93b81636f4efbb | [
"MIT"
] | permissive | 0xSombra/RED4ext.SDK | 79ed912e5b628ef28efbf92d5bb257b195bfc821 | 218b411991ed0b7cb7acd5efdddd784f31c66f20 | refs/heads/master | 2023-07-02T11:03:45.732337 | 2021-04-15T16:38:19 | 2021-04-15T16:38:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | hpp | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Scripting/IScriptable.hpp>
namespace RED4ext
{
namespace AI {
struct CoverDemandHolder : IScriptable
{
static constexpr const char* NAME = "AICoverDemandHolder";
static constexpr const char* ALIAS = "CoverDemandHolder";
uint8_t unk40[0x58 - 0x40]; // 40
};
RED4EXT_ASSERT_SIZE(CoverDemandHolder, 0x58);
} // namespace AI
using CoverDemandHolder = AI::CoverDemandHolder;
} // namespace RED4ext
| [
"[email protected]"
] | |
7206f8dacb3f1921ec564fa2f4b2b794e42b14e8 | 799fa29e29568c5f8be9fdc27b07db268862fd8b | /Android1/Android1/Android1.NativeActivity/fft4g.hpp | b6e20c55b27e202b76bfb3fea49263ea9785f78c | [] | no_license | Hikari-AsakaToru/KadaiIntelligent | e002dde38f3d5c9cffd4d97f2d934970a94c426a | 3351359643aa9a6b8816248a1d6e44f0dee0cbc7 | refs/heads/master | 2021-03-27T19:04:55.713952 | 2018-12-06T05:40:07 | 2018-12-06T05:40:07 | 75,546,265 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,316 | hpp | #pragma once
class fft4g{
// メンバ変数
int *ip; //ビット反転に使用する作業領域
double *w; //cosとsinのテーブル(ip[0] == 0だと初期化される)
int n; //配列の要素数(2N)
// メンバ関数
void makewt(int nw, int *ip, double *w);
void makect(int nc, int *ip, double *c);
void bitrv2(int n, int *ip, double *a);
void bitrv2conj(int n, int *ip, double *a);
void cftfsub(int n, double *a, double *w);
void cftbsub(int n, double *a, double *w);
void cft1st(int n, double *a, double *w);
void cftmdl(int n, int l, double *a, double *w);
void rftfsub(int n, double *a, int nc, double *c);
void rftbsub(int n, double *a, int nc, double *c);
void dctsub(int n, double *a, int nc, double *c);
void dstsub(int n, double *a, int nc, double *c);
public:
fft4g(const int n); //コンストラクタ
~fft4g(); //デストラクタ
void cdft(int isgn, double *a); //複素離散フーリエ変換
void rdft(int isgn, double *a); //実数離散フーリエ変換
void ddct(int isgn, double *a); //離散コサイン変換
void ddst(int isgn, double *a); //離散サイン変換
void dfct(double *a, double *t); //実対称フーリエ変換を用いたコサイン変換
void dfst(double *a, double *t); //実非対称フーリエ変換を用いたサイン変換
};
| [
"[email protected]"
] | |
048ddf0bf0d81c33500fad52c64476e2047e9eca | 24d3527ca20f8600d03f4634c8785c88931d73fe | /Chapitre_3/TD_Barre/barrehexagone.cpp | 9689fb71e54a0efa4965f7c60d41e4574e58391e | [] | no_license | GeoffreyBeranger/Apprendre_Cpp | 803bb847fc17f397dec5afb028a645f4117b6bb7 | 2321d5b3997af2a6a25ab5637ef592316a794be2 | refs/heads/master | 2020-07-19T17:34:11.497367 | 2020-01-09T07:27:17 | 2020-01-09T07:27:17 | 206,487,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | cpp | #include "barrehexagone.h"
/**
* @brief barreHexagone::barreHexagone
* @param _reference
* @param _longueur
* @param _densite
* @param _nomAlliage
* @param _diametre
* @details Constructeur de la classe Barre Hexagone
*/
barreHexagone::barreHexagone(const string _reference, const int _longueur, const float _densite, const string _nomAlliage, const double _diametre):
barre(_reference,_longueur,_densite,_nomAlliage),
diametre(_diametre)
{
cout << "Constructeur de la Classe Barre Hexagone" << endl;
}
/**
* @brief barreHexagone::~barreHexagone
* @details Destructeur de la classe Barre Hexagone
*/
barreHexagone::~barreHexagone()
{
cout << "Destructeur de la Classe Barre Hexagone" << endl;
}
double barreHexagone::CalculerMasse()
{
double masse = 0;
///On change le type de longueur et densite en double
masse = (static_cast<double>(longueur))*(CalculerSection())*(static_cast<double>(densite));
return masse;
}
/**
* @brief barreHexagone::CalculerSection
* @return
* @details Methode CalculerSection qui renvoie la Section
*/
double barreHexagone::CalculerSection()
{
return 2*(sqrt((3*diametre*diametre)/4));
}
| [
"[email protected]"
] | |
a1c8e33eb695f2754bd2a53a6ec26ba01820ca8d | ac2cfee9d35be674f87cb561d60fb77ce8753a43 | /server/3rd/Theron/Detail/Allocators/Pool.h | b5554263891c8d2c6b4ad35a4c86ef86a66da05d | [] | no_license | a83376750/ZeroServer | 8ead03ad7fc3ab9077f15d48a7c08be25815747b | 2770c4aac78d77d0834ec98dd888bd3107ca60d5 | refs/heads/master | 2020-04-01T23:56:03.833927 | 2019-01-02T13:03:38 | 2019-01-02T13:03:38 | 153,780,102 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,484 | h | // Copyright (C) by Ashton Mason. See LICENSE.txt for licensing information.
#ifndef THERON_DETAIL_ALLOCATORS_POOL_H
#define THERON_DETAIL_ALLOCATORS_POOL_H
#include <Theron/Align.h>
#include <Theron/Assert.h>
#include <Theron/BasicTypes.h>
#include <Theron/Defines.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning (disable:4324) // structure was padded due to __declspec(align())
#endif //_MSC_VER
namespace Theron
{
namespace Detail
{
/**
A list of free memory blocks.
*/
template <class LockType>
class THERON_PREALIGN(THERON_CACHELINE_ALIGNMENT) Pool
{
public:
/**
Constructor.
*/
inline Pool();
/**
Locks the pool for exclusive access, if the lock type supports it.
*/
inline void Lock() const;
/**
UnlLocks a previously locked pool.
*/
inline void Unlock() const;
/**
Returns true if the pool contains no memory blocks.
*/
inline bool Empty() const;
/**
Adds a memory block to the pool.
*/
inline bool Add(void *memory);
/**
Retrieves a memory block from the pool with the given alignment.
\return Zero if no suitable blocks in pool.
*/
inline void *FetchAligned(const uint32_t alignment);
/**
Retrieves a memory block from the pool with any alignment.
\return Zero if no blocks in pool.
*/
inline void *Fetch();
private:
/**
A node representing a free memory block within the pool.
Nodes are created in-place within the free blocks they represent.
*/
struct Node
{
THERON_FORCEINLINE Node() : mNext(0)
{
}
Node *mNext; ///< Pointer to next node in a list.
};
static const uint32_t MAX_BLOCKS = 16; ///< Maximum number of memory blocks stored per pool.
mutable LockType mLock; ///< Synchronization primitive for thread-safe access to state.
Node mHead; ///< Dummy node at head of a linked list of nodes in the pool.
uint32_t mBlockCount; ///< Number of blocks currently cached in the pool.
} THERON_POSTALIGN(THERON_CACHELINE_ALIGNMENT);
template <class LockType>
THERON_FORCEINLINE Pool<LockType>::Pool() :
mLock(),
mHead(),
mBlockCount(0)
{
}
template <class LockType>
THERON_FORCEINLINE void Pool<LockType>::Lock() const
{
mLock.Lock();
}
template <class LockType>
THERON_FORCEINLINE void Pool<LockType>::Unlock() const
{
mLock.Unlock();
}
template <class LockType>
THERON_FORCEINLINE bool Pool<LockType>::Empty() const
{
THERON_ASSERT((mBlockCount == 0 && mHead.mNext == 0) || (mBlockCount != 0 && mHead.mNext != 0));
return (mBlockCount == 0);
}
template <class LockType>
THERON_FORCEINLINE bool Pool<LockType>::Add(void *const memory)
{
THERON_ASSERT(memory);
// Just call it a node and link it in.
Node *const node(reinterpret_cast<Node *>(memory));
// Below maximum block count limit?
if (mBlockCount < MAX_BLOCKS)
{
node->mNext = mHead.mNext;
mHead.mNext = node;
++mBlockCount;
return true;
}
return false;
}
template <class LockType>
THERON_FORCEINLINE void *Pool<LockType>::FetchAligned(const uint32_t alignment)
{
Node *previous(&mHead);
const uint32_t alignmentMask(alignment - 1);
// Search the block list.
Node *node(mHead.mNext);
while (node)
{
// Prefetch.
Node *const next(node->mNext);
// This is THERON_ALIGNED with the alignment mask calculated outside the loop.
if ((reinterpret_cast<uintptr_t>(node) & alignmentMask) == 0)
{
// Remove from list and return as block.
previous->mNext = next;
--mBlockCount;
return reinterpret_cast<void *>(node);
}
previous = node;
node = next;
}
// Zero result indicates no correctly aligned block available.
return 0;
}
template <class LockType>
THERON_FORCEINLINE void *Pool<LockType>::Fetch()
{
// Grab first block in the list if the list isn't empty.
Node *const node(mHead.mNext);
if (node)
{
mHead.mNext = node->mNext;
--mBlockCount;
return reinterpret_cast<void *>(node);
}
// Zero result indicates no correctly aligned block available.
return 0;
}
} // namespace Detail
} // namespace Theron
#ifdef _MSC_VER
#pragma warning(pop)
#endif //_MSC_VER
#endif // THERON_DETAIL_ALLOCATORS_POOL_H
| [
"[email protected]"
] | |
e2dc06679e0b8a6750f1e85c6534e4a2d48d9ebb | 2e2ebf3eaf26374a2cf9410e08ae831cdf502f77 | /src/engine/news.h | bcedddf621bef60846c3c25eea437ce8207a8e73 | [
"LicenseRef-scancode-other-permissive",
"Zlib"
] | permissive | def-/HClient | 2531c792524d0a4fc7dbe5e4f64d751b3b4b3413 | 813ae5482e4e863ba63d1fc09fe8c30b551ceccf | refs/heads/master | 2020-12-30T22:56:42.408707 | 2014-02-14T20:56:42 | 2014-02-14T20:56:42 | 16,848,956 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | h | /*
unsigned char*
*/
#ifndef ENGINE_NEWS_H
#define ENGINE_NEWS_H
#include "kernel.h"
#include <vector>
struct SNewsPost {
char m_Date[128];
char m_Title[128];
char m_Text[2048];
char m_Image[512];
int m_ImageID;
};
class INews : public IInterface
{
MACRO_INTERFACE("news", 0)
public:
enum
{
MAX_NEWS_PER_PAGE=4,
STATE_EMPTY=0,
STATE_DOWNLOADING,
STATE_READY,
};
virtual void Init() = 0;
virtual void RefreshForumFails(unsigned int page = 0) = 0;
virtual void RefreshTeeworlds(unsigned int page = 0) = 0;
virtual size_t TotalNews() = 0;
virtual SNewsPost GetNew(size_t npos) = 0;
virtual int GetState() = 0;
virtual void LoadTextures() = 0;
virtual void SetPage(unsigned int page) = 0;
};
void ThreadRefreshForumFails(void *params);
#endif
| [
"[email protected]"
] | |
779cf6e956997e75234457fd268561298f3455bb | 8567438779e6af0754620a25d379c348e4cd5a5d | /third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceGradient.cpp | de3646c58a3195f7f77d256807fc5f6c77a3b426 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 5,348 | cpp | /*
* Copyright (C) 2006 Nikolas Zimmermann <[email protected]>
* Copyright (C) 2008 Eric Seidel <[email protected]>
* Copyright (C) 2008 Dirk Schulze <[email protected]>
* Copyright (C) Research In Motion Limited 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "core/layout/svg/LayoutSVGResourceGradient.h"
#include "wtf/PtrUtil.h"
#include <memory>
namespace blink {
LayoutSVGResourceGradient::LayoutSVGResourceGradient(SVGGradientElement* node)
: LayoutSVGResourcePaintServer(node),
m_shouldCollectGradientAttributes(true) {}
void LayoutSVGResourceGradient::removeAllClientsFromCache(
bool markForInvalidation) {
m_gradientMap.clear();
m_shouldCollectGradientAttributes = true;
markAllClientsForInvalidation(markForInvalidation ? PaintInvalidation
: ParentOnlyInvalidation);
}
void LayoutSVGResourceGradient::removeClientFromCache(
LayoutObject* client,
bool markForInvalidation) {
ASSERT(client);
m_gradientMap.erase(client);
markClientForInvalidation(
client, markForInvalidation ? PaintInvalidation : ParentOnlyInvalidation);
}
SVGPaintServer LayoutSVGResourceGradient::preparePaintServer(
const LayoutObject& object) {
clearInvalidationMask();
// Be sure to synchronize all SVG properties on the gradientElement _before_
// processing any further. Otherwhise the call to collectGradientAttributes()
// in createTileImage(), may cause the SVG DOM property synchronization to
// kick in, which causes removeAllClientsFromCache() to be called, which in
// turn deletes our GradientData object! Leaving out the line below will cause
// svg/dynamic-updates/SVG*GradientElement-svgdom* to crash.
SVGGradientElement* gradientElement = toSVGGradientElement(element());
if (!gradientElement)
return SVGPaintServer::invalid();
if (m_shouldCollectGradientAttributes) {
gradientElement->synchronizeAnimatedSVGAttribute(anyQName());
if (!collectGradientAttributes(gradientElement))
return SVGPaintServer::invalid();
m_shouldCollectGradientAttributes = false;
}
// Spec: When the geometry of the applicable element has no width or height
// and objectBoundingBox is specified, then the given effect (e.g. a gradient
// or a filter) will be ignored.
FloatRect objectBoundingBox = object.objectBoundingBox();
if (gradientUnits() == SVGUnitTypes::kSvgUnitTypeObjectboundingbox &&
objectBoundingBox.isEmpty())
return SVGPaintServer::invalid();
std::unique_ptr<GradientData>& gradientData =
m_gradientMap.insert(&object, nullptr).storedValue->value;
if (!gradientData)
gradientData = WTF::wrapUnique(new GradientData);
// Create gradient object
if (!gradientData->gradient) {
gradientData->gradient = buildGradient();
// We want the text bounding box applied to the gradient space transform
// now, so the gradient shader can use it.
if (gradientUnits() == SVGUnitTypes::kSvgUnitTypeObjectboundingbox &&
!objectBoundingBox.isEmpty()) {
gradientData->userspaceTransform.translate(objectBoundingBox.x(),
objectBoundingBox.y());
gradientData->userspaceTransform.scaleNonUniform(
objectBoundingBox.width(), objectBoundingBox.height());
}
AffineTransform gradientTransform = calculateGradientTransform();
gradientData->userspaceTransform *= gradientTransform;
}
if (!gradientData->gradient)
return SVGPaintServer::invalid();
return SVGPaintServer(gradientData->gradient,
gradientData->userspaceTransform);
}
bool LayoutSVGResourceGradient::isChildAllowed(LayoutObject* child,
const ComputedStyle&) const {
if (child->isSVGGradientStop())
return true;
if (!child->isSVGResourceContainer())
return false;
return toLayoutSVGResourceContainer(child)->isSVGPaintServer();
}
void LayoutSVGResourceGradient::addStops(
Gradient& gradient,
const Vector<Gradient::ColorStop>& stops) const {
for (const auto& stop : stops)
gradient.addColorStop(stop);
}
GradientSpreadMethod LayoutSVGResourceGradient::platformSpreadMethodFromSVGType(
SVGSpreadMethodType method) {
switch (method) {
case SVGSpreadMethodUnknown:
case SVGSpreadMethodPad:
return SpreadMethodPad;
case SVGSpreadMethodReflect:
return SpreadMethodReflect;
case SVGSpreadMethodRepeat:
return SpreadMethodRepeat;
}
ASSERT_NOT_REACHED();
return SpreadMethodPad;
}
} // namespace blink
| [
"[email protected]"
] | |
2e9a2847875ac143d5839864fc6993561b7583d9 | 6cc69d2446fb12f8660df7863d8866d29d52ce08 | /src/Practice/Websites/GeeksForGeeks/Trees/Page 3/InorderTraversalStack.h | 603ee78b875a67bf39ad5022ad3a5f6b05f50a9c | [] | no_license | kodakandlaavinash/DoOrDie | 977e253b048668561fb56ec5c6d3c40d9b57a440 | f961e068e435a5cedb66d0fba5c21b63afe37390 | refs/heads/master | 2021-01-23T02:30:10.606394 | 2013-09-12T08:06:45 | 2013-09-12T08:06:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,192 | h | /*
* InorderTraversalStack.h
*
* Created on: Jul 26, 2013
* Author: Avinash
*/
//
// Testing Status
//
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
using namespace std;
using namespace __gnu_cxx;
#define null NULL
#define PRINT_NEW_LINE printf("\n")
//int main(){
// return -1;
//}
#ifndef INORDERTRAVERSALSTACK_H_
#define INORDERTRAVERSALSTACK_H_
void InOrderTraversalUsingStack(tNode *ptr){
if(ptr == NULL){
return;
}
stack<tNode *> auxSpace;
tNode *currentNode = ptr;
while(1){
if(currentNode == NULL && auxSpace.empty()){
return;
}
if(currentNode->left != NULL){
auxSpace.push(currentNode);
currentNode = currentNode->left;
}else{
printf("%d\t",auxSpace.top()->value);
currentNode = auxSpace.top();
currentNode = currentNode->right;
auxSpace.pop();
}
}
}
#endif /* INORDERTRAVERSALSTACK_H_ */
| [
"[email protected]"
] | |
5e4e02f7f71559cb250f7e9772d42b70fdc25c27 | ac2958e1c8493f60381a017b2e68faeb5b3562f8 | /trunk/ProjectCode/SGVcode/main.cpp | 7bdca99c4e516dd746149ff016144876df011cdc | [] | no_license | 519984307/slicOutDoorParallelCollection.Spiral | 3eb77dc4fbfee78df55b1d7f02f08ff3e73bdbd2 | 1378e1574e9f1686c6a25a524278d9f4ace58cb1 | refs/heads/master | 2023-03-17T08:51:42.843796 | 2019-07-17T10:21:06 | 2019-07-17T10:21:06 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,158 | cpp | #include "stdafx.h"
#include "module_all_cui.h"
/*----------------------------------------------*/
/*
C++:编写跨平台程序的关键,C/C++中的内置宏定义
分两部分:
操作系统判定:
Windows: WIN32
Linux: linux
Solaris: __sun
编译器判定:
VC: _MSC_VER
GCC/G++: __GNUC__
SunCC: __SUNPRO_C和__SUNPRO_CC
*/
/*----------------------------------------------*/
void PrintARG(int argc,char *argv[])
{
for(int i=0;i<argc;i++){
printf("###########################################\n");
printf("Param: %d>>%s \n",i,argv[i]);
printf("###########################################\n");
}
}
/*----------------------------------------------*/
/*
*
*/
/*----------------------------------------------*/
void PrintHelp(){
}
/*----------------------------------------------*/
/*
*
*/
/*----------------------------------------------*/
void TestOpenCV()
{
#if _DEBUG
{
IplImage *img=cvCreateImage(cvSize(100,100),IPL_DEPTH_8U,4);
cvReleaseImage(&img);
}
#endif
}
/*----------------------------------------------*/
/*
*
*/
/*----------------------------------------------*/
int main(int argc,char *argv[])
{
TestOpenCV();
PrintARG(argc,argv);
vector<string> file;
string out;
if (argc==1)
{
}else if (argc>1){
for (int i=1;i<argc;i++){
if (
#if linux||__linux||__linux__||__GNUC__
!access(argv[i], F_OK)
#endif
#if _WIN64 ||_WIN32 ||_MSC_VER
access(argv[i], 0) == 0
#endif
){
printf("this is a file /n");
file.push_back(argv[i]);
}else if (strcmp(argv[i],"-Save")==0){
cui_GeneralImgProcess::SAVE_IMAGE_2DISK=TRUE;
}else if(strcmp(argv[i],"-NotSave")==0){
cui_GeneralImgProcess::SAVE_IMAGE_2DISK=FALSE;
printf("Will not save Image \n");
}else if (strcmp(argv[i],"-DebugInfo")==0){
cui_GeneralImgProcess::SAVE_DEBUG_2DISK=TRUE;
}else if(strcmp(argv[i],"-NotDebugInfo")==0){
cui_GeneralImgProcess::SAVE_DEBUG_2DISK=FALSE;
printf("Will not save debug info \n");
}
else{
printf("not support cmd /n");
}
}
}else{
}
#if _WIN64 ||_WIN32 ||_MSC_VER
if (file.size()==0){
#if 0
file.push_back("E:\\OutPutImg\\org\\12.jpg");
file.push_back("E:\\OutPutImg\\org\\13.jpg");
file.push_back("E:\\OutPutImg\\org\\I527x930.jpg");
#endif
//file.push_back("X:\\ImageDataBase\\400img\\img-10.21op7-p-046t000.jpg");
file.push_back("X:\\MyProject\\r.png");
}
if (out.empty())
{
out="E:\\OutPutImg\\";
}
#endif
#if linux||__linux||__linux__||__GNUC__
if (file.size()==0){
file.push_back("/home/blacksherry/400/400img/img-op39-p-015t000.jpg");
file.push_back("/home/blacksherry/400/400img/img-10.21op7-p-046t000.jpg");
}
if (out.empty()){
out="/home/blacksherry/400/400out/";
}
#endif
cui_GeneralImgProcess::THreadSuperPixel_CUDA_CollectionMethods(0,file,out,1000);
printf("Done ! \n");
return 0;
}
/*----------------------------------------------*/
/*
*
*/
/*----------------------------------------------*/ | [
"[email protected]"
] | |
9f4f608cd48594061fe0e529a2a983b1f41ed263 | 29f7bc0d16c8eeb4dca5a5cacb34d8c3b27ba853 | /src/core/base/RawInput.cpp | d3541f062b6fd3da26c65dbcc5c32d88d001c7fb | [
"MIT"
] | permissive | lixiaoyu0123/DataReporter | 821863c079f12e3b576a8a878a8f202aaea9d299 | bde668a7d181ffc823a0106acabdbeb44d547ffc | refs/heads/master | 2020-04-07T17:00:11.783005 | 2018-11-21T13:04:58 | 2018-11-21T13:04:58 | 158,552,391 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,166 | cpp | #include <limits.h>
#include <assert.h>
#include "RawInput.h"
#include "Log.h"
#include "PBUtility.h"
namespace future {
RawInput::RawInput(const void *oData, int32_t length)
: m_Ptr((uint8_t *) oData), m_Size(length), m_Position(0) {
assert(m_Ptr);
}
RawInput::~RawInput() {
m_Ptr = nullptr;
m_Size = 0;
}
double RawInput::ReadDouble() {
return Int64ToFloat64(this->ReadRawLittleEndian64());
}
float RawInput::ReadFloat() {
return Int32ToFloat32(this->ReadRawLittleEndian32());
}
int64_t RawInput::ReadInt64() {
int32_t shift = 0;
int64_t result = 0;
while (shift < 64) {
int8_t b = this->ReadRawByte();
result |= (int64_t) (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
return result;
}
shift += 7;
}
Error("InvalidProtocolBuffer malformedInt64");
return 0;
}
int32_t RawInput::ReadInt32() {
return this->ReadRawVarint32();
}
int32_t RawInput::ReadFixed32() {
return this->ReadRawLittleEndian32();
}
bool RawInput::ReadBool() {
return this->ReadRawVarint32() != 0;
}
std::string RawInput::ReadString() {
int32_t size = this->ReadRawVarint32();
if (size <= (m_Size - m_Position) && size > 0) {
std::string result((char *) (m_Ptr + m_Position), size);
m_Position += size;
return result;
} else if (size == 0) {
return "";
} else {
Error("Invalid Size: %d", size);
return "";
}
}
Buffer RawInput::ReadData() {
int32_t size = this->ReadRawVarint32();
if (size < 0) {
Error("InvalidProtocolBuffer negativeSize");
return Buffer(0);
}
if (size <= m_Size - m_Position) {
Buffer data(((int8_t *) m_Ptr) + m_Position, size);
m_Position += size;
return data;
} else {
Error("InvalidProtocolBuffer truncatedMessage");
return Buffer(0);
}
}
Buffer RawInput::ReadData(int32_t count){
if (count < 0) {
Error("InvalidProtocolBuffer negativeSize");
return Buffer(0);
}
if (count <= m_Size - m_Position) {
Buffer data(((int8_t *) m_Ptr) + m_Position, count);
m_Position += count;
return data;
} else {
Error("InvalidProtocolBuffer truncatedMessage");
return Buffer(0);
}
}
int32_t RawInput::ReadRawVarint32() {
int8_t tmp = this->ReadRawByte();
if (tmp >= 0) {
return tmp;
}
int32_t result = tmp & 0x7f;
if ((tmp = this->ReadRawByte()) >= 0) {
result |= tmp << 7;
} else {
result |= (tmp & 0x7f) << 7;
if ((tmp = this->ReadRawByte()) >= 0) {
result |= tmp << 14;
} else {
result |= (tmp & 0x7f) << 14;
if ((tmp = this->ReadRawByte()) >= 0) {
result |= tmp << 21;
} else {
result |= (tmp & 0x7f) << 21;
result |= (tmp = this->ReadRawByte()) << 28;
if (tmp < 0) {
// discard upper 32 bits
for (int i = 0; i < 5; i++) {
if (this->ReadRawByte() >= 0) {
return result;
}
}
Error("InvalidProtocolBuffer malformed varint32");
}
}
}
}
return result;
}
int32_t RawInput::ReadRawLittleEndian32() {
int8_t b1 = this->ReadRawByte();
int8_t b2 = this->ReadRawByte();
int8_t b3 = this->ReadRawByte();
int8_t b4 = this->ReadRawByte();
return (((int32_t) b1 & 0xff)) | (((int32_t) b2 & 0xff) << 8) |
(((int32_t) b3 & 0xff) << 16) |
(((int32_t) b4 & 0xff) << 24);
}
int64_t RawInput::ReadRawLittleEndian64() {
int8_t b1 = this->ReadRawByte();
int8_t b2 = this->ReadRawByte();
int8_t b3 = this->ReadRawByte();
int8_t b4 = this->ReadRawByte();
int8_t b5 = this->ReadRawByte();
int8_t b6 = this->ReadRawByte();
int8_t b7 = this->ReadRawByte();
int8_t b8 = this->ReadRawByte();
return (((int64_t) b1 & 0xff)) | (((int64_t) b2 & 0xff) << 8) |
(((int64_t) b3 & 0xff) << 16) |
(((int64_t) b4 & 0xff) << 24) | (((int64_t) b5 & 0xff) << 32) |
(((int64_t) b6 & 0xff) << 40) | (((int64_t) b7 & 0xff) << 48) |
(((int64_t) b8 & 0xff) << 56);
}
int8_t RawInput::ReadRawByte() {
if (m_Position == m_Size) {
Error("reach end, m_Position: %d, m_Size: %d", m_Position, m_Size);
return 0;
}
int8_t *bytes = (int8_t *) m_Ptr;
return bytes[m_Position++];
}
} | [
"[email protected]"
] | |
3213057c94f0260c2d86e4967d613dd468b9d167 | 6dfcf0c373181b75b39d9b89490e3d48b6ebc7a6 | /Algorithms/lcs1.cpp | 334f46ab55f14cdd06ab1eb05b2f2d5d15f9c8e8 | [] | no_license | zero-jim/Aacademic-Coding-Stuffs | f4c1d559ea0b51170163f803fec306a813fa0194 | 57315f2196479034a1222ed395e6f66331ad26ef | refs/heads/master | 2020-04-08T13:39:56.233080 | 2019-07-18T18:45:01 | 2019-07-18T18:45:01 | 159,401,163 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | cpp | #include<bits/stdc++.h>
int max(int a, int b);
int lcs( char *X, char *Y, int m, int n )
{
int L[m+1][n+1];
int i, j;
for (i=0; i<=m; i++)
{
for (j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
return L[m][n];
}
int max(int a, int b)
{
return (a > b)? a : b;
}
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";
int m = strlen(X);
int n = strlen(Y);
printf("Length of LCS is %d\n", lcs( X, Y, m, n ) );
return 0;
}
| [
"[email protected]"
] | |
8b36627ac0e4872a7ce9e9e6867ef48c594a3fe4 | acb84fb8d54724fac008a75711f926126e9a7dcd | /poj/poj3145.cpp | 821503e6431c25809e55d9d31ba4979d42b51b79 | [] | no_license | zrt/algorithm | ceb48825094642d9704c98a7817aa60c2f3ccdeb | dd56a1ba86270060791deb91532ab12f5028c7c2 | refs/heads/master | 2020-05-04T23:44:25.347482 | 2019-04-04T19:48:58 | 2019-04-04T19:48:58 | 179,553,878 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,840 | cpp | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long LL;
typedef long double ld;
void read(int&x){scanf("%d",&x);}
void read(long double&x){double xx;scanf("%lf",&xx);x=xx;}
void read(LL&x){scanf("%lld",&x);}
void read(char*s){scanf("%s",s);}
int n,kase;
char s[10];
int mn[500000*4];
int ans[800];
int a[40005];
int to[500005];
inline void add(int o,int l,int r,int pos){
if(l==r){
mn[o]=pos;
}else{
int mid=(l+r)>>1;
if(pos<=mid) add(o<<1,l,mid,pos);
else add(o<<1|1,mid+1,r,pos);
mn[o]=min(mn[o<<1],mn[o<<1|1]);
}
}
inline int ask(int o,int l,int r,int L,int R){
if(l==L&&r==R){
return mn[o];
}else{
int mid=(l+r)>>1;
if(R<=mid) return ask(o<<1,l,mid,L,R);
else if(L>mid) return ask(o<<1|1,mid+1,r,L,R);
else return min(ask(o<<1,l,mid,L,mid),ask(o<<1|1,mid+1,r,mid+1,R));
}
}
int main(){
int lim=sqrt(500000);
while(scanf("%d",&n),n){
printf("Case %d:\n",++kase);
memset(ans,-1,sizeof ans);
memset(mn,0x3f,sizeof mn);
int tot=0;
bool ok=0;
for(int i=0,x;i<n;i++){
scanf("%s%d",s,&x);
if(s[0]=='B'){
ok=1;
to[x]=++tot;
add(1,1,500000,x);
for(int i=1;i<=lim;i++){
if(ans[i]==-1||x%i<=ans[i]%i){
ans[i]=x;
}
}
}else{
if(!ok){
puts("-1");
continue;
}
if(x<=lim){
printf("%d\n",to[ans[x]]);
}else{
int p=(500000-1)/x+1;
int ans=-1;
for(int i=0;i<p;i++){
int mn=ask(1,1,500000,max(i*x,1),min((i+1)*x,500000));
if(mn==0x3f3f3f3f) continue;
if(ans==-1||ans%x>mn%x) ans=mn;
else if(ans%x==mn%x&&to[ans]<to[mn]) ans=mn;
}
printf("%d\n",to[ans]);
}
}
}
puts("");
}
return 0;
}
| [
"[email protected]"
] | |
1947b08a83f68545d13cec2e6f896d90049b1177 | cde63d7272be7851fd7ccd3794f714e985d407ef | /std_lib_facilities.h | e6398f55d5132444bd111ab3ec6c10895cd8cc1e | [] | no_license | Anonymous-V/Principles-and-Practice-Using-CPP-2nd-edition | bc4866b2f8ae950f829302da56e7b513df82ea48 | 2d40b7b252c7dc7e42a50099ea1395c14351a6a9 | refs/heads/master | 2022-12-26T22:13:14.238374 | 2020-10-15T11:09:25 | 2020-10-15T11:09:25 | 273,668,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,703 | h | /*
std_lib_facilities.h
*/
/*
simple "Programming: Principles and Practice using C++ (second edition)" course header to
be used for the first few weeks.
It provides the most common standard headers (in the global namespace)
and minimal exception/error support.
Students: please don't try to understand the details of headers just yet.
All will be explained. This header is primarily used so that you don't have
to understand every concept all at once.
By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
Revised April 25, 2010: simple_error() added
Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
Revised November 28 2013: add a few container algorithms
Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
Revised Febrary 2 2015: randint() can now be seeded (see exercise 5.13).
Revised June 15 for defaultfloat hack for older GCCs
*/
#ifndef H112
#define H112 020215L
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
//------------------------------------------------------------------------------
#if __GNUC__ && __GNUC__ < 5
inline std::ios_base& defaultfloat(std::ios_base& b) // to augment fixed and scientific as in C++11
{
b.setf(std::ios_base::fmtflags(0), std::ios_base::floatfield);
return b;
}
#endif
//------------------------------------------------------------------------------
using Unicode = long;
//------------------------------------------------------------------------------
using namespace std;
template<class T> string to_string(const T& t)
{
ostringstream os;
os << t;
return os.str();
}
struct Range_error : out_of_range { // enhanced vector range error reporting
int index;
Range_error(int i) :out_of_range("Range error: "+to_string(i)), index(i) { }
};
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
#ifdef _MSC_VER
// microsoft doesn't yet support C++11 inheriting constructors
Vector() { }
explicit Vector(size_type n) :std::vector<T>(n) {}
Vector(size_type n, const T& v) :std::vector<T>(n,v) {}
template <class I>
Vector(I first, I last) : std::vector<T>(first, last) {}
Vector(initializer_list<T> list) : std::vector<T>(list) {}
#else
using std::vector<T>::vector; // inheriting constructor
#endif
T& operator[](unsigned int i) // rather than return at(i);
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
const T& operator[](unsigned int i) const
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
};
// disgusting macro hack to get a range checked vector:
#define vector Vector
// trivially range-checked string (no iterator checking):
struct String : std::string {
using size_type = std::string::size_type;
// using string::string;
char& operator[](unsigned int i) // rather than return at(i);
{
if (i<0||size()<=i) throw Range_error(i);
return std::string::operator[](i);
}
const char& operator[](unsigned int i) const
{
if (i<0||size()<=i) throw Range_error(i);
return std::string::operator[](i);
}
};
namespace std {
template<> struct hash<String>
{
size_t operator()(const String& s) const
{
return hash<std::string>()(s);
}
};
} // of namespace std
struct Exit : runtime_error {
Exit(): runtime_error("Exit") {}
};
// error() simply disguises throws:
inline void error(const string& s)
{
throw runtime_error(s);
}
inline void error(const string& s, const string& s2)
{
error(s+s2);
}
inline void error(const string& s, int i)
{
ostringstream os;
os << s <<": " << i;
error(os.str());
}
template<class T> char* as_bytes(T& i) // needed for binary I/O
{
void* addr = &i; // get the address of the first byte
// of memory used to store the object
return static_cast<char*>(addr); // treat that memory as bytes
}
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
inline void keep_window_open(string s)
{
if (s=="") return;
cin.clear();
cin.ignore(120,'\n');
for (;;) {
cout << "Please enter " << s << " to exit\n";
string ss;
while (cin >> ss && ss!=s)
cout << "Please enter " << s << " to exit\n";
return;
}
}
// error function to be used (only) until error() is introduced in Chapter 5:
inline void simple_error(string s) // write ``error: s and exit program
{
cerr << "error: " << s << '\n';
keep_window_open(); // for some Windows environments
exit(1);
}
// make std::min() and std::max() accessible on systems with antisocial macros:
#undef min
#undef max
// run-time checked narrowing cast (type conversion). See ???.
template<class R, class A> R narrow_cast(const A& a)
{
R r = R(a);
if (A(r)!=a) error(string("info loss"));
return r;
}
// random number generators. See 24.7.
default_random_engine& get_rand()
{
static default_random_engine ran;
return ran;
};
void seed_randint(int s) { get_rand().seed(s); }
inline int randint(int min, int max) { return uniform_int_distribution<>(min, max)(get_rand()); }
inline int randint(int max) { return randint(0, max); }
//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x
// container algorithms. See 21.9.
template<typename C>
using Value_type = typename C::value_type;
template<typename C>
using Iterator = typename C::iterator;
template<typename C>
// requires Container<C>()
void sort(C& c)
{
std::sort(c.begin(), c.end());
}
template<typename C, typename Pred>
// requires Container<C>() && Binary_Predicate<Value_type<C>>()
void sort(C& c, Pred p)
{
std::sort(c.begin(), c.end(), p);
}
template<typename C, typename Val>
// requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C> find(C& c, Val v)
{
return std::find(c.begin(), c.end(), v);
}
template<typename C, typename Pred>
// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C> find_if(C& c, Pred p)
{
return std::find_if(c.begin(), c.end(), p);
}
#endif //H112 | [
"[email protected]"
] | |
6ed19087c155cbef3865a0e557dde5794ccb5469 | a455898673ba9ed21450db18c798dd677f3aae3a | /src/brush/pencilbrush.cpp | 3814f8000e80fd5360ac5d9dd70cc1095052854c | [] | no_license | sheepkill15/painter | 41cac8338ee1c49a3ce963820e659e993f4d7130 | cba1d8e7e92f09c4b0f113bc4fff7d69b91074bb | refs/heads/master | 2023-08-22T03:55:13.741715 | 2021-10-18T18:18:51 | 2021-10-18T18:18:51 | 401,294,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | //
// Created by Aron on 10/3/2021.
//
#include "pencilbrush.h"
#include <canvas/canvas.h>
#include <shapes/lineshape.h>
void PencilBrush::onMouseDown(const sf::Vector2f &pos) {
auto circle = sf::CircleShape(settings.size);
circle.setFillColor(settings.color);
circle.setOrigin(settings.size, settings.size);
prepareForDraw(_canvas->flip_vertical(pos), sf::Vector2f(), 1);
_canvas->preview(circle, pos, false, &renderShader);
_prevPos = pos;
}
void PencilBrush::onMouseUp(const sf::Vector2f& pos) {
_canvas->apply_preview();
}
void PencilBrush::onMouseMoved(const sf::Vector2f &pos) {
auto circle = sf::CircleShape(settings.size);
circle.setOrigin(settings.size, settings.size);
circle.setFillColor(settings.color);
const auto pos1 = (sf::Vector2f)_canvas->transform_pos(_prevPos);
const auto pos2 = (sf::Vector2f)_canvas->transform_pos(pos);
// _canvas->draw(circle, pos);
prepareForDraw(_canvas->flip_vertical(pos1), sf::Vector2f(), 1);
_canvas->preview(circle, pos, false, &renderShader);
auto line = sf::LineShape(pos1, pos2);
line.setThickness(settings.size * 2);
line.setFillColor(settings.color);
prepareForDraw(_canvas->flip_vertical(pos1), _canvas->flip_vertical(pos2), 0);
_canvas->preview(line, _prevPos, false, &renderShader);
_prevPos = pos;
}
PencilBrush::PencilBrush(Canvas& canvas) : Brush(canvas) {
} | [
"[email protected]"
] | |
9d6d0fb17391c024d872f4a376fda447bdf29939 | 7a572c43d35f9f5bf026268ea36493f82e206846 | /TestMac/Curl_C.cpp | c766136d6d2822b89f938f6c806fa74352a58094 | [] | no_license | xu561865/Test_Mac | f674cbd5c484b90135b8e5b46e951dc5f4cc6c09 | ff51c667d7f88ca976e948761e37ff329a4eb4b3 | refs/heads/master | 2021-01-10T01:20:38.259352 | 2016-09-09T09:22:43 | 2016-09-09T09:22:43 | 47,551,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,173 | cpp | //
// Curl_C.cpp
// TestMac
//
// Created by 徐以 on 4/1/16.
// Copyright © 2016 xuyi. All rights reserved.
//
#include "Curl_C.h"
#include <curl/curl.h>
#include <stdlib.h>
#include <iostream>
Curl_C* Curl_C::sharedInstance()
{
static Curl_C* s_pCurl = nullptr;
if(!s_pCurl)
{
s_pCurl = new Curl_C();
}
return s_pCurl;
}
void Curl_C::testUrl()
{
CURL *curl; //定义CURL类型的指针
CURLcode res; //定义CURLcode类型的变量
curl = curl_easy_init(); //初始化一个CURL类型的指针
if(curl!=NULL)
{
//设置curl选项. 其中CURLOPT_URL是让用户指定url. argv[1]中存放的命令行传进来的网址
curl_easy_setopt(curl, CURLOPT_URL, "www.chinaunix1.net");
//调用curl_easy_perform 执行我们的设置.并进行相关的操作. 在这里只在屏幕上显示出来.
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
std::cout<<"success"<<std::endl;
}
else
{
std::cout<<"failed"<<std::endl;
}
//清除curl操作.
curl_easy_cleanup(curl);
}
} | [
"[email protected]"
] | |
17ea8f415b2ce8c9f26d14adc3b940660bc0e5c1 | 20398f12903a20f3a8740d89edaff96242956f69 | /unused/view.cc | a2dd42c709023349379a36af4cbb87a4f607199d | [
"MIT"
] | permissive | RobertWeber1/cli | 2dee03ed83cca0ff59250c7058ea54b3b9cba1ef | 5cb67325610be41014403e9342dddbe942511c2b | refs/heads/master | 2021-01-09T20:29:51.568564 | 2019-03-31T18:37:14 | 2019-03-31T18:37:14 | 64,243,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,293 | cc | #include "view.h"
#include "hlayout.h"
#include "vlayout.h"
#include "cliwindow.h"
#include <stdarg.h>
UnknownLayoutException::UnknownLayoutException(const std::string& viewName,
const std::string& layoutName) throw():
viewName(viewName), layoutName(layoutName)
{
fillWhat();
}
UnknownLayoutException::UnknownLayoutException(const UnknownLayoutException & e) throw() :
viewName(e.viewName), layoutName(e.layoutName)
{
fillWhat();
}
void UnknownLayoutException::fillWhat()
{
whatStr << "The layout name \"" << layoutName
<< "\" is unknown in view \"" << viewName << "\"";
}
const char* UnknownLayoutException::what() const throw()
{
return (whatStr.str().c_str());
}
//----------------------------------------------------------------------------//
NameDuplicateException::NameDuplicateException(const std::string& viewName,
const std::string& objectName,
LayoutObject::ObjectType type) throw():
viewName(viewName), objectName(objectName), type(type)
{
fillWhat();
}
NameDuplicateException::NameDuplicateException(const NameDuplicateException & e) throw():
viewName(e.viewName), type(e.type), objectName(e.objectName)
{
fillWhat();
}
void NameDuplicateException::fillWhat()
{
whatStr << "The "<< ((type==LayoutObject::WINDOW)?"window":"layout") <<" name \"" << objectName
<< "\" is aleary used in view \"" << viewName << "\"";
}
const char* NameDuplicateException::what() const throw()
{
return whatStr.str().c_str();
}
//----------------------------------------------------------------------------//
ParentIsWindowException::ParentIsWindowException(const std::string& viewName,
const std::string& windowName,
const std::string& layoutObjectName) throw():
viewName(viewName), windowName(windowName), layoutObjectName(layoutObjectName)
{
fillWhat();
}
ParentIsWindowException::ParentIsWindowException(const ParentIsWindowException & e) throw():
viewName(e.viewName), windowName(e.windowName), layoutObjectName(e.layoutObjectName)
{
fillWhat();
}
void ParentIsWindowException::fillWhat()
{
whatStr << "You tried to insert a LayoutObject(" << layoutObjectName
<< ") into a Window (" << windowName <<"in view " << viewName << ")";
}
const char* ParentIsWindowException::what() const throw()
{
return whatStr.str().c_str();
}
//----------------------------------------------------------------------------//
UnknownLayoutTypeException::UnknownLayoutTypeException(const std::string& viewName,
const std::string& layoutName,
LayoutObject::ObjectType type) throw():
viewName(viewName), layoutName(layoutName), type(type)
{
fillWhat();
}
UnknownLayoutTypeException::UnknownLayoutTypeException(const UnknownLayoutTypeException & e) throw():
viewName(e.viewName), layoutName(e.layoutName), type(e.type)
{
fillWhat();
}
void UnknownLayoutTypeException::fillWhat()
{
whatStr << "The layout type \"" << static_cast<int>(type) << "\" ("
<< LayoutObject::ObjectTypeName[static_cast<int>(type)] << ") is unknown "
<< "(view name: " << viewName << ", layout name: " << layoutName << ")!";
}
const char* UnknownLayoutTypeException::what() const throw()
{
return whatStr.str().c_str();
}
//----------------------------------------------------------------------------//
View::View(const std::string & name) :
name(name), rootObject(NULL), borderBuffer()
{}
View::~View()
{
for(std::map<std::string, LayoutObject*>::iterator it = layoutMap.begin(); it != layoutMap.end(); it++)
{
delete it->second;
}
for(std::map<std::string, CLIWindow*>::iterator it = windowMap.begin(); it != windowMap.end(); it++)
{
delete it->second;
}
}
LayoutObject * View::createObj(LayoutObject::ObjectType type, const std::string& objectName)
{
LayoutObject* obj = NULL;
std::pair<std::map<std::string, LayoutObject*>::iterator, bool> insertLResult;
std::pair<std::map<std::string, CLIWindow*>::iterator, bool> insertWResult;
switch(type)
{
case LayoutObject::H_LAYOUT:
obj = new HLayout();
insertLResult = layoutMap.insert(make_pair(objectName, obj));
if(!insertLResult.second)
{
delete obj;
obj = NULL;
}
break;
case LayoutObject::V_LAYOUT:
obj = new VLayout();
insertLResult = layoutMap.insert(make_pair(objectName, obj));
if(!insertLResult.second)
{
delete obj;
obj = NULL;
}
break;
case LayoutObject::WINDOW:
obj = new CLIWindow();
insertWResult = windowMap.insert(make_pair(objectName, static_cast<CLIWindow*>(obj)));
if(!insertWResult.second)
{
delete obj;
obj = NULL;
}
break;
}
return obj;
}
void addObjToObj(LayoutObject * child, LayoutObject * parent)
{
switch(parent->type)
{
case LayoutObject::H_LAYOUT:
static_cast<HLayout*>(parent)->addObject(child);
break;
case LayoutObject::V_LAYOUT:
static_cast<VLayout*>(parent)->addObject(child);
break;
}
}
void removeObjFromObj(LayoutObject * child, LayoutObject * parent)
{
switch(parent->type)
{
case LayoutObject::H_LAYOUT:
static_cast<HLayout*>(parent)->removeObject(child);
break;
case LayoutObject::V_LAYOUT:
static_cast<VLayout*>(parent)->removeObject(child);
break;
}
}
void View::addLayout(LayoutObject::ObjectType type,
const std::string & layoutName,
const std::string & parentName)
{
if(windowMap.find(layoutName) != windowMap.end() ||
layoutMap.find(layoutName) != layoutMap.end())
{
throw NameDuplicateException(name, layoutName, type);
}
if(type != LayoutObject::H_LAYOUT && type != LayoutObject::V_LAYOUT)
{
throw UnknownLayoutTypeException(name, layoutName, type);
}
if(parentName != "")
{
std::map<std::string, LayoutObject*>::iterator findResult;
findResult = layoutMap.find(parentName);
if(findResult == layoutMap.end())
{
throw UnknownLayoutException(name, layoutName);
}
else
{
addObjToObj(createObj(type, layoutName), findResult->second);
}
}
else
{
if(rootObject)
{
if(rootObject->type == LayoutObject::H_LAYOUT ||
rootObject->type == LayoutObject::V_LAYOUT)
{
addObjToObj(createObj(type, layoutName), rootObject);
}
else
{
throw ParentIsWindowException(name, parentName, layoutName);
}
}
else
{
rootObject = createObj(type, layoutName);
}
}
}
CLIWindow * View::addWindow(const std::string & windowName, const std::string & parentName)
{
if(windowMap.find(windowName) != windowMap.end() ||
layoutMap.find(windowName) != layoutMap.end())
{
throw NameDuplicateException(name, windowName);
}
if(parentName == "")
{
if(rootObject != NULL)
{
if(rootObject->type == LayoutObject::WINDOW)
{
throw ParentIsWindowException(name, "", windowName);
}
else
{
addObjToObj(createObj(LayoutObject::WINDOW, windowName), rootObject);
}
}
else
{
rootObject = createObj(LayoutObject::WINDOW, windowName);
}
}
else
{
std::map<std::string, LayoutObject*>::iterator findResult;
findResult = layoutMap.find(parentName);
if(findResult == layoutMap.end())
{
throw UnknownLayoutException(name, windowName);
}
else
{
addObjToObj(createObj(LayoutObject::WINDOW, windowName), findResult->second);
}
}
}
void View::removeObject(const std::string & name)
{
LayoutObject * findResult = NULL;
std::map<std::string, LayoutObject*>::iterator layoutFindResult;
std::map<std::string, CLIWindow*>::iterator windowFindResult;
layoutFindResult = layoutMap.find(name);
if(layoutFindResult == layoutMap.end())
{
windowFindResult = windowMap.find(name);
if(windowFindResult == windowMap.end())
{
findResult = windowFindResult->second;
windowMap.erase(windowFindResult);
}
else
{
return;
}
}
else
{
findResult = layoutFindResult->second;
layoutMap.erase(layoutFindResult);
}
if(findResult)
{
removeObjFromObj(findResult, rootObject);
delete findResult;
}
}
LayoutObject * View::getRoot()
{
return rootObject;
}
| [
"[email protected]"
] | |
730b251a295a961fd8cca908db2efdf3c7ba74c3 | e8d783d45ac0f3ef7f38eadc5b44b7e2a595179f | /wxwidgets/tutorials/t27.cpp | 5244e41c9b07e3ab284ff2e039a82fc010f5fe36 | [
"Zlib"
] | permissive | osom8979/example | e3be7fd355e241be6b829586b93d3cbcb1fbf3a5 | 603bb7cbbc6427ebdc7de28f57263c47d583c2e4 | refs/heads/master | 2023-07-21T19:55:55.590941 | 2023-07-20T02:06:42 | 2023-07-20T02:06:42 | 52,238,897 | 2 | 1 | NOASSERTION | 2023-07-20T02:06:43 | 2016-02-22T01:42:09 | C++ | UTF-8 | C++ | false | false | 850 | cpp | #include "tutorial.h"
class MyFrameT27: public wxFrame
{
public:
MyFrameT27(const wxString& title);
};
MyFrameT27::MyFrameT27(const wxString& title) :
wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(200, 150))
{
wxPanel *panel = new wxPanel(this, -1);
wxGridSizer *grid = new wxGridSizer(3, 2, 10, 10);
grid->Add(new wxButton(panel, wxID_CANCEL), 0, wxTOP | wxLEFT, 9);
grid->Add(new wxButton(panel, wxID_DELETE), 0, wxTOP, 9);
grid->Add(new wxButton(panel, wxID_SAVE), 0, wxLEFT, 9);
grid->Add(new wxButton(panel, wxID_EXIT));
grid->Add(new wxButton(panel, wxID_STOP), 0, wxLEFT, 9);
grid->Add(new wxButton(panel, wxID_NEW));
panel->SetSizer(grid);
Centre();
}
int t27()
{
MyFrameT27 * frame = new MyFrameT27(wxT("MyFrame"));
frame->Show(true);
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
27cf74a72ebc1708ebe29257245165e6d68c9077 | d64f5b22a4ec23ad28019ba129a50e216acadb92 | /ParseFile.cpp | d4e97e8cab00021b252891b81e38ab9e3d166752 | [] | no_license | LHFCOD/ImportData | 6f85219e509bd67ccfea7ab4160e3d4f4391ef83 | c68faa98af8aa98bef675ec5d62a09f7500be08e | refs/heads/master | 2021-05-06T01:02:49.946198 | 2017-12-15T15:40:38 | 2017-12-15T15:40:38 | 114,350,887 | 0 | 0 | null | 2017-12-15T15:40:39 | 2017-12-15T09:11:58 | C++ | UTF-8 | C++ | false | false | 5,633 | cpp | #include <string>
#include <fstream>
#include <sstream>
#include <streambuf>
#include <regex>
#include <iostream>
#include <cassert>
#include "ParseFile.h"
using namespace std;
bool ParseFile::ReadFile(string strPath)
{
ifstream infile;
infile.open(strPath.data());
if (!infile.is_open())
{
ParseException *excep = new ParseException("Can't opent configure file:" + strPath);
throw excep;
}
string buffer;
int line = 0;
while (getline(infile, buffer))
{
line++;
//remove the comment based on "##"
string::size_type pos = buffer.find("##");
string serchStr;
if (pos != string::npos)
{
if (pos != 0)
serchStr = buffer.substr(0, pos - 1);
else
serchStr = "";///if all are comments
}
else
{
serchStr = buffer;
}
regex reg("\\s*(\\S+)\\s*=\\s*(.+)\\s*");
smatch m;
if (regex_search(serchStr, m, reg))
{
//str(1) reprents the variable on the left of the equal sign
//str(2) reprents the variable on the right of the equal sign
//cout << m.str(1) << m.str(2) << endl;
//analyze the keywords
map<string, keyWords>::iterator iter;
string strKey= m.str(1);
iter = keyWordsMap.find(strKey);
if (iter != keyWordsMap.end())
{
keyWords keyword = iter->second;
if (keyword == keyWords::titleLine)
{
int a=2;
}
//if not successfully create the class info
if (!CreateInfo(keyword, m.str(2)))
{
char msg[100];
sprintf(msg, "line%d:error when creating infomation based on the keyword!", line);
ParseException *excep = new ParseException(msg);
throw excep;
}
}
else
{
//if not find keyword in map
char msg[100];
sprintf(msg, "line%d:not find keyword!", line);
ParseException *excep = new ParseException(msg);
throw excep;
}
}
else
{
///if not find a suitable expression and the string is not empty,an error is reported
if (!serchStr.empty())
{
char *msg = new char[100];
sprintf(msg, "line%d:syntax error!", line);
ParseException *excep = new ParseException(msg);
throw excep;
}
}
}
infile.close();
return true;
}
bool ParseFile::CreateInfo(keyWords keyword, string info)
{
switch (keyword)
{
case keyWords::orclSrv:
{
orclSrv = info;
break;
}
case keyWords::path:
{
FileInfo *fileinfo = new FileInfo();
fileinfo->filePath = info;
list_info.push_back(fileinfo);
break;
}
case keyWords::title:
{
regex reg("([^,]\\S[^,]+)");
smatch m;
//get the recent file path
FileInfo *fileinfo = list_info.back();
if (fileinfo == nullptr)
{
//if you don't specify the file path
ParseException *excep = new ParseException("No file path specified!");
throw excep;
}
else
{
while (regex_search(info, m, reg))
{
fileinfo->title.push_back(m.str(1));
info = m.suffix();
}
}
break;
}
case keyWords::field:
{
regex reg("([^,]\\S[^,]+)");
smatch m;
FileInfo *fileinfo = list_info.back();
if (fileinfo == nullptr)
{
ParseException *excep = new ParseException("No file path specified!");
throw excep;
}
else
{
while (regex_search(info, m, reg))
{
fileinfo->field.push_back(m.str(1));
info = m.suffix();
}
}
break;
}
case keyWords::start:
{
FileInfo *fileinfo = list_info.back();
if (fileinfo == nullptr)
{
ParseException *excep = new ParseException("No file path specified!");
throw excep;
}
else
{
stringstream stream;
stream << info;
stream >> fileinfo->start;
}
break;
}
case keyWords::end:
{
FileInfo *fileinfo = list_info.back();
if (fileinfo == nullptr)
{
ParseException *excep = new ParseException("No file path specified!");
throw excep;
}
else
{
stringstream stream;
stream << info;
stream >> fileinfo->end;
}
break;
}
case keyWords::titleLine:
{
FileInfo *fileinfo = list_info.back();
if (fileinfo == nullptr)
{
ParseException *excep = new ParseException("No file path specified!");
throw excep;
}
else
{
stringstream stream;
stream << info;
stream >> fileinfo->titleLine;
}
break;
}
case keyWords::timePos:
{
FileInfo *fileinfo = list_info.back();
if (fileinfo == nullptr)
{
ParseException *excep = new ParseException("No file path specified!");
throw excep;
}
else
{
stringstream stream;
stream << info;
stream >> fileinfo->timePos;
}
break;
}
default:
return false;
break;
}
return true;
}
ParseFile::ParseFile()
{
initial();
}
ParseFile::~ParseFile()
{
list<FileInfo*>::iterator iter;
for (iter = list_info.begin(); iter != list_info.end(); iter++)
{
if (*iter != nullptr)
{
delete *iter;
}
}
}
bool ParseFile::initial()
{
//create map of keywords
keyWordsMap.insert(map<string, keyWords>::value_type("orclSrv", keyWords::orclSrv));
keyWordsMap.insert(map<string, keyWords>::value_type("path", keyWords::path));
keyWordsMap.insert(map<string, keyWords>::value_type("start", keyWords::start));
keyWordsMap.insert(map<string, keyWords>::value_type("end", keyWords::end));
keyWordsMap.insert(map<string, keyWords>::value_type("title", keyWords::title));
keyWordsMap.insert(map<string, keyWords>::value_type("field", keyWords::field));
keyWordsMap.insert(map<string, keyWords>::value_type("titleLine", keyWords::titleLine));
keyWordsMap.insert(map<string, keyWords>::value_type("timePos", keyWords::timePos));
return true;
} | [
"[email protected]"
] | |
596ed77b164a2268ec892833f1f78bcf6bb2c428 | ea3e4e4b7dc16c5eac0f1d7eecbe8aade6d9441d | /lab6/Huffman/src/encoding_ex.cpp | 0ade89fa23dd676546cdf9c4f207bf6432f89069 | [] | no_license | anden259/TDDD86 | 25ef79c3fe9158184776cabf62d699ade761cc36 | b7de080747c17f20cec23ab8bd9dfda07c494a7c | refs/heads/master | 2021-01-01T19:19:41.021026 | 2014-12-16T09:58:47 | 2014-12-16T09:58:47 | 23,538,556 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,875 | cpp | // anden259 andno037
#include "encoding.h"
#include <queue>
// builds a table with the count of each byte in the input data
map<int, int> buildFrequencyTable(istream& input)
{
map<int, int> freqTable;
while (true) {
int byte = 0;
byte = input.get();
if (byte == -1) {
++freqTable[PSEUDO_EOF];
break;
} else {
++freqTable[byte];
}
}
return freqTable;
}
// builds a huffman tree from the frequency table
HuffmanNode* buildEncodingTree(const map<int, int> &freqTable)
{
priority_queue<HuffmanNode> my_queue;
for (auto pair : freqTable) {
my_queue.push(HuffmanNode {pair.first, pair.second});
}
while (my_queue.size() != 1) {
HuffmanNode loc_root;
HuffmanNode* left = new HuffmanNode {my_queue.top()};
my_queue.pop();
HuffmanNode* right = new HuffmanNode {my_queue.top()};
my_queue.pop();
loc_root.count = left->count + right->count;
loc_root.zero = left;
loc_root.one = right;
my_queue.push(loc_root);
}
return new HuffmanNode {my_queue.top()};
}
// Recursive help funktion that builds the encoding map from the huffman tree.
void buildEncodingMapRecursive(HuffmanNode * node, map<int , string> &encodingMap, string bin = "")
{
if (node->character != NOT_A_CHAR) {
encodingMap[node->character] = bin;
} else {
buildEncodingMapRecursive(node->zero, encodingMap, bin + "0");
buildEncodingMapRecursive(node->one, encodingMap, bin + "1");
}
}
// Builds the encoding map from the huffman tree
map<int, string> buildEncodingMap(HuffmanNode* encodingTree)
{
map<int, string> encodingMap;
buildEncodingMapRecursive(encodingTree, encodingMap);
return encodingMap;
}
// Encodes the in-data
void encodeData(istream& input, const map<int, string> &encodingMap, obitstream& output)
{
bool run = true;
while (run) {
int byte = 0;
byte = input.get();
string code;
if (byte == -1) { // -1 is EOF
code = encodingMap.at(PSEUDO_EOF);
run = false;
} else {
code = encodingMap.at(byte);
}
for (auto c : code) {
if (c == '0') {
output.writeBit(0);
} else if (c == '1') {
output.writeBit(1);
} else {
cerr << "error\n";
}
}
}
}
// Decodes the in-data with an encoding tree.
void decodeData(ibitstream& input, HuffmanNode* encodingTree, ostream& output)
{
HuffmanNode* current = encodingTree;
while (true) {
if (current->character == PSEUDO_EOF) {
break;
} else if (current->character != NOT_A_CHAR) {
output << (char)current->character;
current = encodingTree;
} else {
bool bit = input.readBit();
if (bit) {
current = current->one;
} else {
current = current->zero;
}
}
}
}
/* Header structure
*
* +-----------------+-----------------+-----------------+ - - - +-----------------+-----------------+ - - -
* | #N header-pairs | byte | frequency | ..... | N'th byte | N'th frequency | compressed data after header
* | 1-byte | 1-byte | 1-4 bytes | | | |
* +-----------------+-----------------+-----------------+ - - - +-----------------+-----------------+ - - -
*
* how frequency works
* the leading non-zero bits tells us how many extra bytes we need to hold the frequency of a byte
* e.g.
*
* 00000001 is 1
* 01111111 is 127, and the most that we can fit in 1 byte.
*
* 10000000 10000000 is 128 and requires 2 bytes to be represented.
* 10111111 11111111 is 16383 and the most that fit in 2 bytes
*
* so the leading 1-set bits tells us how many extra bytes we need to represent the frequency
* since the given code only support int's we decided to support a maximum of four extra bytes, that is almost one int.
*
*/
// Help function to write the header while encoding.
void help_write_header_count(obitstream& output, unsigned int number)
{
if (number <= 0x7f) {
output << (char) number;
} else if (number <= 0x3fff) {
output << (char)((number >> 8) | 0x80) << (char) number;
} else if (number <= 0x1fffff) {
output << (char)((number >> 16) | 0xC0) << (char)(number >> 8) << (char) number;
} else if (number <= 0xfffffff) {
output << (char)((number >> 24) | 0xE0) << (char)(number >> 16) << (char)(number >> 8) << (char) number;
}
}
// Compress in-data with huffman compression algorithm, and save the frequency table in the output header.
void compress(istream& input, obitstream& output)
{
map<int, int>freqTable = buildFrequencyTable(input);
// ignore eof
output << (char)(freqTable.size() - 1);
for (auto pair : freqTable) {
if (pair.first != PSEUDO_EOF) {
output << (char)pair.first;
help_write_header_count(output, pair.second);
}
}
input.clear();
input.seekg(0, input.beg);
HuffmanNode* tree = buildEncodingTree(freqTable);
encodeData(input, buildEncodingMap(tree), output);
freeTree(tree);
}
// Help function for reading the header while decoding.
int help_read_header_count(istream& input)
{
unsigned int byte1 = input.get();
if((byte1 & 0xe0) == 0xe0) {
unsigned int byte2 = input.get();
unsigned int byte3 = input.get();
unsigned int byte4 = input.get();
return ((byte1 & 0x0f) << 24) | (byte2 << 16) | (byte3 << 8) | byte4;
} else if((byte1 & 0xc0) == 0xc0) {
unsigned int byte2 = input.get();
unsigned int byte3 = input.get();
return ((byte1 & 0x1f) << 16) | (byte2 << 8) | byte3;
} else if((byte1 & 0x80) == 0x80) {
unsigned int byte2 = input.get();
return ((byte1 & 0x3f) << 8) | byte2;
} else {
return byte1;
}
}
// Decompresses our huffman compressed indata with the help of the information in the header.
void decompress(ibitstream& input, ostream& output)
{
map<int, int>freqTable;
int header_pairs = input.get();
for (int i = 0; i < header_pairs; ++i) {
int character = input.get();
int counter = help_read_header_count(input);
freqTable[character] = counter;
}
freqTable[PSEUDO_EOF] = 1;
HuffmanNode* tree = buildEncodingTree(freqTable);
decodeData(input, tree, output);
freeTree(tree);
}
// dealloc a huffman tree.
void freeTree(HuffmanNode* node)
{
if (node == nullptr)
return;
if (node->zero != nullptr)
freeTree(node->zero);
if (node->one != nullptr)
freeTree(node->one);
delete node;
}
| [
"[email protected]"
] | |
716b070faf6eb88ef8c92af06b68a92034cc3f45 | fb2402740fce5082291b8fa6a0a20bebf4750418 | /hackerrank/day-8-dictionaries-and-maps.cpp | 6afb98ca111056e44e21cdfb1ba6434b48b308a2 | [] | no_license | tdwong/leetcode | 4e9b2323f5e8c7766fe7f0bd73543410718dead4 | 93aa582986fd7e95839d52ebecacb65859f0a6e6 | refs/heads/master | 2020-07-25T22:41:28.730152 | 2017-03-08T07:35:01 | 2017-03-08T07:35:01 | 73,647,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,504 | cpp | //https://www.hackerrank.com/challenges/30-dictionaries-and-maps
/*
# Day 8: Dictionaries and Maps
#
# Objective
#
# Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check
# out the Tutorial tab for learning materials and an instructional video!
#
# Task
#
# Given n names and phone numbers, assemble a phone book that maps friends' names to their
# respective phone numbers. You will then be given an unknown number of names to query your phone
# book for. For each name queried, print the associated entry from your phone book on a new line
# in the form "name=phoneNumber"; if an entry for name is not found, print "Not found" instead.
#
# Note: Your phone book should be a Dictionary/Map/HashMap data structure.
#
# Input Format
#
# The first line contains an integer, n, denoting the number of entries in the phone book.
# Each of the n subsequent lines describes an entry in the form of 2 space-separated values on a
# single line. The first value is a friend's name, and the second value is an 8-digit phone number.
#
# After the n lines of phone book entries, there are an unknown number of lines of queries. Each
# line (query) contains a name to look up, and you must continue reading lines until there is no
# more input.
#
# Note: Names consist of lowercase English alphabetic letters and are first names only.
#
# Constraints
#
# * 1 <= n <= 10**5
# * 1 <= queries <= 10**5
#
# Output Format
#
# On a new line for each query, print "Not found" if the name has no corresponding entry in the
# phone book; otherwise, print the full name and phone Number in the format "name=phoneNumber".
#
# Sample Input
#
# 3
# sam 99912222
# tom 11122222
# harry 12299933
# sam
# edward
# harry
#
# Sample Output
#
# sam=99912222
# Not found
# harry=12299933
#
# Explanation
#
# We add the following n = 3 (Key,Value) pairs to our map so it looks like this:
#
# phoneBooks = { (sam,99912222), (tom,11122222), (harry,12299933) }
#
# We then process each query and print "key=value" if the queried key is found in the map; otherwise, we print "Not found".
#
# Query 0: sam
# Sam is one of the keys in our dictionary, so we print "sam=99912222".
#
# Query 1: edward
# Edward is not one of the keys in our dictionary, so we print "Not found".
#
# Query 2: harry
# Harry is one of the keys in our dictionary, so we print "harry=12299933".
#
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include <exception>
using namespace std;
int main() {
printf("to run: day-8-dictionaries-and-maps < day-8-dictionaries-and-maps.txt\n");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
// read # of phonebook entries
int n;
cin >> n;
// built phonebooks
std::map<string,string> phoneBooks;
string name, number;
for (int ix = 0; ix < n; ix++) {
cin >> name >> number;
phoneBooks[name] = number;
}
// try {
// string name;
// continously read from stdin
while (1) {
cin >> name;
//** check end of input condition
if (cin.fail()) { break; }
if (phoneBooks.find(name) == phoneBooks.end()) {
cout << "Not found" << endl;
}
else {
cout << name << "=" << phoneBooks[name] << endl;
}
}
// }
// catch (exception &e) {
// // do nothing
// }
return 0;
}
| [
"[email protected]"
] | |
efddf6ae65e3936d9dcfe7fce9b2c2ccc05a424f | 03e698eabf47f8361c545b07e0f5d837e6d49fac | /lib/region.h | d0eeba55de48e2b7399a788023585e5873b851b9 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | zxzxzx131313/Global-Contrast-based-Salient-Region-Detection | 6c7baac3e2a6afe376d2c8a9e1d89972b879f883 | 5fab3dac82e1d5a514d2d170df9832714b7dddc3 | refs/heads/master | 2022-03-04T07:13:21.598714 | 2022-02-14T21:19:58 | 2022-02-14T21:19:58 | 120,560,842 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 681 | h | #include <opencv2/opencv.hpp>
#include <map>
#include <list>
#include <array>
#include <vector>
class Region{
public:
Region(): label(0), num_pixels(0), saliency(-1) {
};
int label;
int num_pixels;
float saliency;
std::map<std::array<int, 3>, int> colors;
std::vector<cv::Point> pixels;
void increment();
float findFrequency(Region::Region ®ion, std::array<int, 3> &color);
void setSaliency(float &saliency){
this->saliency = saliency;
}
float getSaliency(){
return this->saliency;
}
cv::Vec3b* findColor(std::map<std::array<int, 3>, int> & colors, std::array<int, 3> & color);
};
| [
"[email protected]"
] | |
f34b193a5a7f4a30f34af8377d8543006d8469c2 | 3ef492e4ceddcc487ef73ddd1befee2f0dd34777 | /Algorithms/Implementation/Equalize the Array.cpp | 0acdf26e7359f49834298cb7483915b6ba27c316 | [] | no_license | PhoenixDD/HackerRank | 23c9079e5b31657bc68f1709b5550be403f958ce | 044c39619ce535f5a247c7407b0f7793ca04719d | refs/heads/master | 2021-01-15T16:47:47.124935 | 2018-06-28T00:17:12 | 2018-06-28T00:17:12 | 99,726,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main()
{
int n,num,max=0;
cin>>n;
unordered_map<int,int> freq(n);
for(int i=0;i<n;i++)
{
cin>>num;
freq[num]++;
}
for(auto &i:freq)
if(i.second>max)
max=i.second;
cout<<n-max;
return 0;
} | [
"[email protected]"
] | |
8ed1c66a3dc6cc2fd7e7d5d5eae3fad7b4d836df | 7ca22b3a8e95c03b54c37b33cc49e27240f22274 | /src/Restaurant.cpp | e2c605d26e9dc0146039612157f7a2e16ff8dfdb | [] | no_license | almda/Spl-Restaurant | e640f630ed650426fc0717f50b5ed94a8d6d6101 | 84e2406305c56803807ff21b4c4e465e99b5d5f1 | refs/heads/master | 2022-12-12T16:21:45.160068 | 2020-09-14T21:39:51 | 2020-09-14T21:39:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,662 | cpp | ///////////////////////////last version ori 20.11
#include "../include/Restaurant.h"
#include <iostream>
#include <fstream>
using namespace std;
//init new Restaurant that isn't open and didnt get any customer so id init to 0.
Restaurant::Restaurant():open(false),tables(),menu(),actionsLog(),idAvailable(0) {}
//By what writen in the "program flow" the Restaurant opens by calling the start func it prints the line below and opens the Restaurant
//After each executed action, the program waits for the next action in a loop.
void Restaurant::start() {
//start an new restaurant by opening and prints
std::cout<<"Restaurant is now open!"<< std::endl;
open= true;
string line="";//line that we read
int closeAllDone =0;//a identifier of closeAll action - if closeAll is called - closeAllDone = 1.
std::getline(cin,line);
while(!line.empty()&&closeAllDone==0) {
string command =""; //a string of all the command line that was written by user
string action = ""; // the action that was written in command - 'close','status', 'move',...
string numberForAction; //the number that we recognize in the command line
for(unsigned int i=0;i<line.size();i++){
command+=line[i];
}
unsigned int whereIsTheDelimiter=0;
for(unsigned int j=0;j<command.size();j++){
if(command[j]!=' '){
action+=command[j];//while there is no delimiter we will read the action to action string
whereIsTheDelimiter++;//
}
else if(command[j]==' '){
while(whereIsTheDelimiter<command.size()) {
numberForAction += command[whereIsTheDelimiter];
whereIsTheDelimiter++;
j++;
}
}
}
if(action=="closeall"){
actionCloseAll();
closeAllDone=1;
break;
}
else if(action=="backup"){
actionBackup();
}
else if(action=="menu"){
actionPrintMenu();
}
else if(action=="restore"){
actionResote();
}
else if(action=="close"){
actionClose(command);
}
////////print table status
else if(action =="status"){
actionPrintstatusOfTable(command);
}
else if(action=="order"){
actionOreder(command);
}
else if(action=="open"){
actionOpentable(command);
}
else if(action=="move"){
actionMove(command);
}
else if(action=="log"){
actionPrintActionLog();
}
std::getline(cin,line);//reading line from
if(line=="closeall"){ ///catch the closeall
actionCloseAll();
closeAllDone=1;
break;
}
}
}
int Restaurant::getNumOfTables() const {
return tables.size();
}
std::vector<Dish> &Restaurant::getMenu() {
return this->menu;
}
const std::vector<BaseAction *> &Restaurant::getActionsLog() const {
return actionsLog;
}
//destructor - all the fields need to be destruct
Restaurant::~Restaurant() {
if(!tables.empty()) {
for (auto &table : tables)
if(table!= nullptr)
delete table;
tables.clear();
}
if(!menu.empty()) {
menu.clear();
}
if(!actionsLog.empty())
{
for (auto &i : actionsLog)
delete i;
actionsLog.clear();
}
}
//copy constructor - copy each one of fields from this to other
Restaurant::Restaurant(const Restaurant &other):open(other.open),tables(),menu(),actionsLog(),idAvailable(other.idAvailable) {
open = other.open;
idAvailable = other.idAvailable;
for (const auto &i : other.menu)
menu.push_back(i);
for (auto table : other.tables)
tables.push_back(new Table(*table));
for (auto i : other.actionsLog)
actionsLog.push_back(i->clone());
}
//Assignment Operator - The copy assignment operator is called when an existing object need to be assigned a new value
Restaurant& Restaurant::operator=(const Restaurant &other) {
if (this ==& other) {
return *this;
}
//destructor
if(!tables.empty()) {
for (auto &table : tables)
if(table!= nullptr)
delete table;
tables.clear();
}
if(!menu.empty()) {
menu.clear();
}
if(!actionsLog.empty())
{
for (auto &i : actionsLog)
delete i;
actionsLog.clear();
}
open = other.open;
idAvailable = other.idAvailable;
for (const auto &i : other.menu)
menu.push_back(i);
for (unsigned int i=0; i<other.tables.size();i++) {
tables.push_back(new Table(*other.tables[i]));
}
for (auto i : other.actionsLog)
actionsLog.push_back(i->clone());
return *this;
}
//The Move Constructor
//we need to copy the fields of other to this and after delete all the fields of other
//The move constructor is called when a newly created object need to be initialized from rvalue.
Restaurant::Restaurant(Restaurant &&other):open(),tables(),menu(),actionsLog(),idAvailable(other.idAvailable) {
if(!tables.empty()) {
for (auto &table : tables)
if(table!= nullptr)
delete table;
tables.clear();
}
if(!menu.empty()) {
menu.clear();
}
if(!actionsLog.empty())
{
for (auto &i : actionsLog)
delete i;
actionsLog.clear();
}
open = other.open;
idAvailable = other.idAvailable;
for(unsigned int i=0;i<other.tables.size(); i++)
tables.push_back(other.tables[i]);
other.tables.clear();
for(unsigned int i=0;i<other.actionsLog.size(); i++)
actionsLog.push_back(other.actionsLog[i]);
other.actionsLog.clear();
for(unsigned int i=0;i<other.menu.size(); i++)
menu.push_back(other.menu[i]);
other.menu.clear();
}
//The Move Assignment - check if there is memory leak in the way i done.
//The move assignment operator is called when an existing object need to be assigned a new rvalue
Restaurant& Restaurant::operator=(Restaurant &&other) {
//////////////////////destrucor
if(!tables.empty()) {
for (auto &table : tables)
if(table!= nullptr)
delete table;
tables.clear();
}
if(!menu.empty()) {
menu.clear();
}
if(!actionsLog.empty())
{
for (auto &i : actionsLog)
delete i;
actionsLog.clear();
}
/////////////end dest
/////Assign
for (const auto &i : other.menu)
menu.push_back(i);
tables = other.tables;
actionsLog = other.actionsLog;
idAvailable = other.idAvailable;
open = other.open;
return *this;
}
Table* Restaurant::getTable(int ind) {
int howManyTabless=tables.size();
if(!tables.empty() && ind<=howManyTabless)
return tables[ind];
return nullptr;
}
/////////////////////////////////////////////action to do at the Restaurant - the logic part of Restaurant
void Restaurant::actionResote() {
RestoreResturant* restoreResturant = new RestoreResturant();
restoreResturant->act(*this);
actionsLog.push_back(restoreResturant);
}
void Restaurant::actionBackup() {
BackupRestaurant* backupRestaurant = new BackupRestaurant;
backupRestaurant->act(*this);
actionsLog.push_back(backupRestaurant);
}
Restaurant::Restaurant(const std::string &configFilePath):open(),tables(),menu(),actionsLog(),idAvailable(0) {
string line="";
ifstream myfile (configFilePath);
int lineCounter=0;
std::vector<string> releventLines;
string numberOftables;
string tableCaps;
std::vector<string> dishes;
while (getline(myfile,line)){
if(!line.empty()&&line.size()>0){
int comment=0;
for(string::iterator letter=line.begin();letter!=line.end();++letter){
if (*letter == '#') {
comment=1;
break;
}
break;
}
if(comment==0){
if(lineCounter==0) {
numberOftables=line;
releventLines.push_back(line);
}
else if(lineCounter==1) {
tableCaps=line+",";
releventLines.push_back(line);
}
else {
dishes.push_back(line+",");
releventLines.push_back(line);
}
lineCounter++;
}
}
}
if(lineCounter!=0){
//create tables
createTables(numberOftables,tableCaps);
//create menu
generateMenu(dishes);
//handles memory Leak
releventLines.clear();
numberOftables.clear();
tableCaps.clear();
dishes.clear();
}
if(lineCounter==0){
std::cout<<"Error in reading file - missing relevent information or can't read the file"<<std::endl;
}
// }
}
void Restaurant::actionPrintMenu() {
//printing menu and saving to action log
PrintMenu* menu = new PrintMenu();
menu->act(*this);
actionsLog.push_back(menu);
}
void Restaurant::actionClose(std::string &letter) {
int tToClose=0;
//the numbers : for the word "400" - numbers are '4','0','0'
std::string numbers;
for(unsigned int i=0; i<letter.length();i++){
while(letter[i]!= ' '){
i++;
} i++;
while(i!=letter.length()){
numbers+=letter[i];
i++;;
}
}
tToClose=::stoi(numbers);
//closing action and adding it to action log
Close* cl = new Close(tToClose);
cl->act(*this);
actionsLog.push_back(cl);
}
void Restaurant::actionCloseAll() {
//closing all tables in rest
CloseAll* cla = new CloseAll();
cla->act(*this);
actionsLog.push_back(cla);
}
void Restaurant::actionPrintActionLog() {
PrintActionsLog* pal = new PrintActionsLog();
pal->act(*this);
actionsLog.push_back(pal);
}
void Restaurant::actionPrintstatusOfTable(std::string &letter) {
int tableId =-1;
std::string numbers="";
for(unsigned int i=0; i<letter.length();i++){
while(letter[i]!= ' '){
i++;
} //adding chars to string
i++;
while(i!=letter.length()){
numbers+=letter[i];
i++;
}
}
tableId=std::stoi(numbers);
PrintTableStatus* pts = new PrintTableStatus(tableId);
pts->act(*this);
actionsLog.push_back(pts);
}
//the generating menu go over the menu vector that is a vector of line of strings -
// each line structure is "Beer,ALC,50" - Beer - dish name, ALC-dish type ,50-dishe price
//
void Restaurant::generateMenu(std::vector<std::string> &dishes) {
if(dishes.size()>0&&!dishes.empty()){
for(unsigned int i=0; i<dishes.size();i++){
string name="";
string type="";
string price="";
for(unsigned int j=0;j<dishes[i].size();j++){
if(name.empty()){
while(dishes[i][j]!=',') {
name += dishes[i][j];
j++;
}
}
else if (type.empty()){
while(dishes[i][j]!=','){
type+=dishes[i][j];
j++;
}
}
else if(price.empty()){
while(dishes[i][j]!= ','){
price+=dishes[i][j];
j++;
}
}
}
//check if all the parameters to create dish are available
if(name.empty() | type.empty() | price.empty()){
std::cout<<"cant find one of the parameters to genetare a dish\n"<<std::endl;
if(name.empty())
std::cout<<"param name is missing\n"<<std::endl;
if(type.empty())
std::cout<<"param type of dish is missing\n"<<std::endl;
if(price.empty())
std::cout<<"param price of dish is missing\n"<<std::endl;
}
int etype=-1;
if(type=="VEG"){
etype=0;
menu.push_back(Dish(i,name,std::stoi(price),VEG));
}
if(type=="SPC"){
etype=1;
menu.push_back(Dish(i,name,std::stoi(price),SPC));
}
if(type=="BVG"){
etype=2;
menu.push_back(Dish(i,name,std::stoi(price),BVG));
}
if(type=="ALC"){
etype=3;
menu.push_back(Dish(i,name,std::stoi(price),ALC));
}
if(etype==-1){
std::cout<<"can't create dish\n"<<std::endl;
}
}
}
}
//create tables
void Restaurant::createTables(std::string numberOftables, std::string tableCaps) {
int howManyTabels=0;// how many tables in the rest
string howMany="";
std::vector<int> tablePlaces;
for(unsigned int i=0;i<numberOftables.length();i++){
if(numberOftables[i]!='\r'){
howMany+=numberOftables[i];
}
}
howManyTabels=std::stoi(howMany);
string temp="";
for(unsigned int i=0;i<tableCaps.length();i++){
if(tableCaps[i]!=','){
temp+=tableCaps[i];
}
else if(tableCaps[i]==','){
int tmp =std::stoi(temp);
tablePlaces.push_back(tmp);
temp="";
}
else if(tableCaps[i]=='\r'){
i=tableCaps.length();
}
}
for(int i =0; i<howManyTabels;i++){
tables.push_back(new Table(tablePlaces[i]));
}
tablePlaces.clear();
}
void Restaurant::actionMove(std::string &letter) {
std::string srcTable="";
std::string customerId="";
std::string dstTable="";
unsigned int i=5; // start after move_
while(letter[i]!=' '){
srcTable+=letter[i];
i++;
}//here we reached space 1
i++;
while(letter[i]!=' '){
dstTable+=letter[i];
i++;
}//here we reached space 2
i++;
while(i<letter.size()){
customerId+=letter[i];
i++;
}//ending
int srcT= std::stoi(srcTable);
int cId= std::stoi(customerId);
int dstT= std::stoi(dstTable);
MoveCustomer * move = new MoveCustomer(srcT,dstT,cId);
move->act(*this);
actionsLog.push_back(move);
}
void Restaurant::actionOreder(std::string &letter) {
int tableId = -1;
std::string orderName = "";
std::string numberToOrder = "";
std::string numbers="";
for(unsigned int i=0; i<letter.length();i++){
while(letter[i]!= ' '){
i++;
} //adding chars to string
i++;
while(i!=letter.length()){
numbers+=letter[i];
i++;
}
}
tableId=std::stoi(numbers);
Order* ord =new Order(tableId);
if(tableId > this->getNumOfTables()){
cout<<"Table does not exist or is not open"<<endl;
}
else if(!this->getTable(tableId)->isOpen()){
cout<<"Table does not exist or is not open"<<endl;
}
else {
ord->act(*this);
actionsLog.push_back(ord);
}
}
void Restaurant::actionOpentable(std::string &letter) {
vector<Customer*> customers;
unsigned int whereInLine=5;
int tId=-1;
string tableId;
for(;whereInLine<letter.size();){
while(letter[whereInLine]!=' ') {
tableId+=letter[whereInLine];
whereInLine++;
}
break;
}
tId=std::stoi(tableId);
whereInLine++;
string name;
string type;
for(;whereInLine<letter.size();whereInLine++){
while(letter[whereInLine]!=' ' && letter[whereInLine]!=','){
name+=letter[whereInLine];
whereInLine++;
}
if(whereInLine ==letter.length() || letter[whereInLine]==' '||letter[whereInLine]==','){
if(letter[whereInLine]==','){whereInLine++;}
if(!name.empty()&& type.empty()){
type+=letter[whereInLine];
type+=letter[whereInLine+1];
type+=letter[whereInLine+2];
whereInLine=whereInLine+3;
if(type=="alc"){
customers.push_back(new AlchoholicCustomer(name,idAvailable));/////////how will i konw the id!!
}
else if(type == "chp"){
customers.push_back(new CheapCustomer(name,idAvailable));
}
else if(type== "veg"){
customers.push_back(new VegetarianCustomer(name,idAvailable));
}
else if(type == "spc"){
customers.push_back(new SpicyCustomer(name,idAvailable));
}
else{
std::cout<<"cant create new customers for opening"<<std::endl;
}
if(!name.empty()&&!type.empty()){
name="";
type="";
}
idAvailable++;
}
}
}
OpenTable * openT = new OpenTable(tId,customers);
openT->act(*this);
actionsLog.push_back(openT);
}
| [
"[email protected]"
] | |
ba806735f9d4daf1003a026cb84067014d700cd2 | 2286ee85ed394b47d781e803f407195f00a79784 | /src/spink/irled.h | 8e9c21da594d27334760b781fb032ae4a417a0d4 | [] | no_license | jdcockrill/spink | 423c4a8155efacaa3fcaff557e40bd48f8973ab0 | 42ff08b8381c939bdc9f7964f1cdaf5f767b7722 | refs/heads/master | 2016-09-06T18:17:57.524500 | 2011-09-14T21:54:24 | 2011-09-14T21:54:24 | 2,366,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 330 | h | /*
irled.h - Library for flashing an IR LED with
a given signal.
Created by jdcockrill, September 11, 2011.
*/
#ifndef irled_h
#define irled_h
#include "WProgram.h"
class IRLED
{
public:
IRLED(int pin);
void sendSignal(int arr[], int len);
private:
void _pulseIR(long microsecs);
int _pin;
};
#endif
| [
"[email protected]"
] | |
f4b42c69789a6c32d9fb6839d56418e09d4ba9dc | 2f557f60fc609c03fbb42badf2c4f41ef2e60227 | /CondTools/SiPixel/test/SiPixelGenErrorDBObjectReader.h | 9a0d7b30ef6a195cdc7d7e8c27c07776e4f96297 | [
"Apache-2.0"
] | permissive | CMS-TMTT/cmssw | 91d70fc40a7110832a2ceb2dc08c15b5a299bd3b | 80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7 | refs/heads/TMTT_1060 | 2020-03-24T07:49:39.440996 | 2020-03-04T17:21:36 | 2020-03-04T17:21:36 | 142,576,342 | 3 | 5 | Apache-2.0 | 2019-12-05T21:16:34 | 2018-07-27T12:48:13 | C++ | UTF-8 | C++ | false | false | 1,429 | h | #ifndef CondTools_SiPixel_SiPixelGenErrorDBObjectReader_h
#define CondTools_SiPixel_SiPixelGenErrorDBObjectReader_h
#include <memory>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/ESWatcher.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "CondFormats/SiPixelObjects/interface/SiPixelGenErrorDBObject.h"
#include "CondFormats/DataRecord/interface/SiPixelGenErrorDBObjectRcd.h"
#include "CalibTracker/Records/interface/SiPixelGenErrorDBObjectESProducerRcd.h"
class SiPixelGenErrorDBObjectReader : public edm::EDAnalyzer {
public:
explicit SiPixelGenErrorDBObjectReader(const edm::ParameterSet&);
~SiPixelGenErrorDBObjectReader();
private:
virtual void beginJob() ;
virtual void analyze(const edm::Event&, const edm::EventSetup&);
virtual void endJob() ;
//edm::ESWatcher<SiPixelGenErrorDBObjectESProducerRcd> SiPixGenerDBObjectWatcher_;
//edm::ESWatcher<SiPixelGenErrorDBObjectRcd> SiPixGenerDBObjWatcher_;
std::string theGenErrorCalibrationLocation;
bool theDetailedGenErrorDBErrorOutput;
bool theFullGenErrorDBOutput;
//bool testGlobalTag;
SiPixelGenErrorDBObject dbobject;
//bool hasTriggeredWatcher;
};
#endif
| [
"[email protected]"
] | |
cba0e533465d52aa5fdd125711504ddd6f11f0eb | c74e77aed37c97ad459a876720e4e2848bb75d60 | /300-399/317/(3929359)[OK]A[ b'Perfect Pair' ].cpp | 23ccc074341b45201d7ad1f4744b1866310f764b | [] | no_license | yashar-sb-sb/my-codeforces-submissions | aebecf4e906a955f066db43cb97b478d218a720e | a044fccb2e2b2411a4fbd40c3788df2487c5e747 | refs/heads/master | 2021-01-21T21:06:06.327357 | 2017-11-14T21:20:28 | 2017-11-14T21:28:39 | 98,517,002 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 727 | cpp | #include<iostream>
using namespace std;
int main()
{
long long x,y,m,count,t;
cin>>x>>y>>m;
if (x<y)
{
count = x;
x = y;
y = count;
}
if (x>=m||y>=m)
{
cout<<0;
}
else if ((x+y)-m>min(x,y)-m)
{
count=0;
if (y<0)
{
count+=(-y)/x;
y+=(-y)/x*x;
}
while (x<m&&y<m)
{
if (x<y)
{
t = x;
x = y;
y = t;
}
count++;
t = x;
x = x + y;
y = t;
}
cout<<count;
}
else
{
cout<<-1;
}
} | [
"[email protected]"
] | |
c5d42f695e34c5cd5f333ca1fe69e14e4503b22b | 1dab59ad345716011ad0d87ee4d8bad549ad8b93 | /source/compute_engine/opencl/opencl_command_queue.h | 469a0c7d72339661ad58cad8c1112f4efdf75ab2 | [
"MIT"
] | permissive | aminnezarat/KTT | 1d15eca55348d03d350270d100235f7d6002cce0 | 6566f9adb1b010a695c48642eebcece68d37fa17 | refs/heads/master | 2021-07-17T07:45:39.016504 | 2020-10-16T16:13:00 | 2020-10-16T16:13:00 | 218,470,489 | 0 | 0 | MIT | 2019-10-30T07:45:16 | 2019-10-30T07:45:15 | null | UTF-8 | C++ | false | false | 1,369 | h | #pragma once
#include <vector>
#include <CL/cl.h>
#include <compute_engine/opencl/opencl_utility.h>
#include <ktt_types.h>
namespace ktt
{
class OpenCLCommandQueue
{
public:
explicit OpenCLCommandQueue(const QueueId id, const cl_context context, const cl_device_id device) :
id(id),
context(context),
device(device)
{
cl_int result;
#ifdef CL_VERSION_2_0
cl_queue_properties properties[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0 };
queue = clCreateCommandQueueWithProperties(context, device, properties, &result);
checkOpenCLError(result, "clCreateCommandQueueWithProperties");
#else
queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &result);
checkOpenCLError(result, "clCreateCommandQueue");
#endif
}
~OpenCLCommandQueue()
{
checkOpenCLError(clReleaseCommandQueue(queue), "clReleaseCommandQueue");
}
QueueId getId() const
{
return id;
}
cl_context getContext() const
{
return context;
}
cl_device_id getDevice() const
{
return device;
}
cl_command_queue getQueue() const
{
return queue;
}
private:
QueueId id;
cl_context context;
cl_device_id device;
cl_command_queue queue;
};
} // namespace ktt
| [
"[email protected]"
] | |
01b336414f82537100ae0de6ff25632a7c9e582e | 44d8ef4d380652976ce6db22120322f7cbaa98bc | /Programmers/kakao2018 - 캐시.cpp | 44b6b29a33dbb522a8d68f0a42d0cdec69a7e403 | [] | no_license | sw93/algorithm | dc9bb9fdefd74a3015121197de6cb3d526899940 | 30d17512474b27a752ac672a70b0a7feb8355a25 | refs/heads/master | 2021-07-15T12:41:49.513793 | 2020-06-08T04:24:08 | 2020-06-08T04:24:08 | 164,956,742 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 770 | cpp | #include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int solution(int cacheSize, vector<string> cities) {
int answer = 0;
vector<string> cache;
if (cacheSize == 0) {
return cities.size() * 5;
}
for (int i=0; i<cities.size(); i++) {
transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::tolower);
vector<string>::iterator it = find(cache.begin(), cache.end(), cities[i]);
if (it == cache.end()) {
if (cache.size() >= cacheSize) cache.erase(cache.begin());
cache.push_back(cities[i]);
answer+=5;
} else {
cache.erase(it);
cache.push_back(cities[i]);
answer++;
}
}
return answer;
} | [
"[email protected]"
] | |
39ef6f90a8f3e267cd6ed7cdaf277e1131005e47 | 765a5cfc885c255bb7726749144bad90288afebb | /mapper.cpp | 278433b4020757b337f07c1da4d97a747a8961e4 | [] | no_license | Sakura-gh/Parallel-Algorithm | 941ad2c20670675932c1b7f5bbef73f2b74d4795 | aabe92452d36faa9820c21f8146f26b257d1e05e | refs/heads/master | 2022-09-06T00:14:04.249839 | 2020-05-27T04:52:26 | 2020-05-27T04:52:26 | 267,193,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | cpp | #include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
// use regex to match english word
regex re("([A-Za-z]*)");
smatch result;
string word;
// read word separated by space
while (cin >> word)
{
// match word with regex
regex_search(word, result, re);
if (result[0] != "")
// output map (word, 1) for hadoop
cout << result[0] << "\t"
<< "1" << endl;
}
return 0;
} | [
"[email protected]"
] | |
d333538f859de2c98ce9d1999a2df4d28fae76d1 | a0442fcd9edc8b6d0975ce8799ea5a67e808c568 | /casa6/casa5/code/alma/ASDM/DelayModelTable.h | e419df7cd0edb8d3efda04cf86f0588e30a84f52 | [] | no_license | kernsuite-debian/carta-casacore | f0046b996e2d0e59bfbf3dbc6b5d7eeaf97813f7 | a88f662d4f6d7ba015dcaf13301d57117a2f3a17 | refs/heads/master | 2022-07-30T04:44:30.215120 | 2021-06-30T10:49:40 | 2021-06-30T10:49:40 | 381,669,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,481 | h |
/*
* ALMA - Atacama Large Millimeter Array
* (c) European Southern Observatory, 2002
* (c) Associated Universities Inc., 2002
* Copyright by ESO (in the framework of the ALMA collaboration),
* Copyright by AUI (in the framework of the ALMA collaboration),
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Warning!
* --------------------------------------------------------------------
* | This is generated code! Do not modify this file. |
* | If you do, all changes will be lost when the file is re-generated. |
* --------------------------------------------------------------------
*
* File DelayModelTable.h
*/
#ifndef DelayModelTable_CLASS
#define DelayModelTable_CLASS
#include <string>
#include <vector>
#include <map>
#include <alma/ASDM/ArrayTimeInterval.h>
#include <alma/ASDM/ArrayTime.h>
#include <alma/ASDM/Frequency.h>
#include <alma/ASDM/Tag.h>
#include <alma/Enumerations/CPolarizationType.h>
#include <alma/ASDM/ConversionException.h>
#include <alma/ASDM/DuplicateKey.h>
#include <alma/ASDM/UniquenessViolationException.h>
#include <alma/ASDM/NoSuchRow.h>
#include <alma/ASDM/DuplicateKey.h>
#ifndef WITHOUT_ACS
#include <asdmIDLC.h>
#endif
#include <alma/ASDM/Representable.h>
#include <pthread.h>
namespace asdm {
//class asdm::ASDM;
//class asdm::DelayModelRow;
class ASDM;
class DelayModelRow;
/**
* The DelayModelTable class is an Alma table.
* <BR>
*
* \par Role
* Contains the delay model components. For ALMA this includes all TMCDB delay model components.
* <BR>
* Generated from model's revision "-1", branch ""
*
* <TABLE BORDER="1">
* <CAPTION> Attributes of DelayModel </CAPTION>
* <TR BGCOLOR="#AAAAAA"> <TH> Name </TH> <TH> Type </TH> <TH> Expected shape </TH> <TH> Comment </TH></TR>
* <TR> <TH BGCOLOR="#CCCCCC" colspan="4" align="center"> Key </TD></TR>
* <TR>
* <TD> antennaId </TD>
* <TD> Tag</TD>
* <TD> </TD>
* <TD> refers to a unique row in AntennaTable. </TD>
* </TR>
* <TR>
* <TD> spectralWindowId </TD>
* <TD> Tag</TD>
* <TD> </TD>
* <TD> refers to a unique row in SpectraWindowTable. </TD>
* </TR>
* <TR>
* <TD> timeInterval </TD>
* <TD> ArrayTimeInterval</TD>
* <TD> </TD>
* <TD> time interval for which the row's content is valid. </TD>
* </TR>
* <TR> <TH BGCOLOR="#CCCCCC" colspan="4" valign="center"> Value <br> (Mandatory) </TH></TR>
* <TR>
* <TD> numPoly (numPoly)</TD>
* <TD> int </TD>
* <TD> </TD>
* <TD> the number of coefficients of the polynomials. </TD>
* </TR>
* <TR>
* <TD> phaseDelay </TD>
* <TD> std::vector<double > </TD>
* <TD> numPoly </TD>
* <TD> the phase delay polynomial (rad). </TD>
* </TR>
* <TR>
* <TD> phaseDelayRate </TD>
* <TD> std::vector<double > </TD>
* <TD> numPoly </TD>
* <TD> Phase delay rate polynomial (rad/s). </TD>
* </TR>
* <TR>
* <TD> groupDelay </TD>
* <TD> std::vector<double > </TD>
* <TD> numPoly </TD>
* <TD> Group delay polynomial (s). </TD>
* </TR>
* <TR>
* <TD> groupDelayRate </TD>
* <TD> std::vector<double > </TD>
* <TD> numPoly </TD>
* <TD> Group delay rate polynomial (s/s) </TD>
* </TR>
* <TR>
* <TD> fieldId </TD>
* <TD> Tag </TD>
* <TD> </TD>
* <TD> </TD>
* </TR>
* <TR> <TH BGCOLOR="#CCCCCC" colspan="4" valign="center"> Value <br> (Optional) </TH></TR>
* <TR>
* <TD> timeOrigin</TD>
* <TD> ArrayTime </TD>
* <TD> </TD>
* <TD> value used as the origin for the evaluation of the polynomials. </TD>
* </TR>
* <TR>
* <TD> atmosphericGroupDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Atmosphere group delay. </TD>
* </TR>
* <TR>
* <TD> atmosphericGroupDelayRate</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Atmosphere group delay rate. </TD>
* </TR>
* <TR>
* <TD> geometricDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Geometric delay. </TD>
* </TR>
* <TR>
* <TD> geometricDelayRate</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Geometric delay. </TD>
* </TR>
* <TR>
* <TD> numLO(numLO)</TD>
* <TD> int </TD>
* <TD> </TD>
* <TD> the number of local oscillators. </TD>
* </TR>
* <TR>
* <TD> LOOffset</TD>
* <TD> std::vector<Frequency > </TD>
* <TD> numLO </TD>
* <TD> Local oscillator offset. </TD>
* </TR>
* <TR>
* <TD> LOOffsetRate</TD>
* <TD> std::vector<Frequency > </TD>
* <TD> numLO </TD>
* <TD> Local oscillator offset rate. </TD>
* </TR>
* <TR>
* <TD> dispersiveDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Dispersive delay. </TD>
* </TR>
* <TR>
* <TD> dispersiveDelayRate</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Dispersive delay rate. </TD>
* </TR>
* <TR>
* <TD> atmosphericDryDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> the dry atmospheric delay component. </TD>
* </TR>
* <TR>
* <TD> atmosphericWetDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> the wet atmospheric delay. </TD>
* </TR>
* <TR>
* <TD> padDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Pad delay. </TD>
* </TR>
* <TR>
* <TD> antennaDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> Antenna delay. </TD>
* </TR>
* <TR>
* <TD> numReceptor(numReceptor)</TD>
* <TD> int </TD>
* <TD> </TD>
* <TD> </TD>
* </TR>
* <TR>
* <TD> polarizationType</TD>
* <TD> std::vector<PolarizationTypeMod::PolarizationType > </TD>
* <TD> numReceptor </TD>
* <TD> describes the polarizations of the receptors (one value per receptor). </TD>
* </TR>
* <TR>
* <TD> electronicDelay</TD>
* <TD> std::vector<double > </TD>
* <TD> numReceptor </TD>
* <TD> the electronic delay. </TD>
* </TR>
* <TR>
* <TD> electronicDelayRate</TD>
* <TD> std::vector<double > </TD>
* <TD> numReceptor </TD>
* <TD> the electronic delay rate. </TD>
* </TR>
* <TR>
* <TD> receiverDelay</TD>
* <TD> std::vector<double > </TD>
* <TD> numReceptor </TD>
* <TD> the receiver delay. </TD>
* </TR>
* <TR>
* <TD> IFDelay</TD>
* <TD> std::vector<double > </TD>
* <TD> numReceptor </TD>
* <TD> the intermediate frequency delay. </TD>
* </TR>
* <TR>
* <TD> LODelay</TD>
* <TD> std::vector<double > </TD>
* <TD> numReceptor </TD>
* <TD> the local oscillator delay. </TD>
* </TR>
* <TR>
* <TD> crossPolarizationDelay</TD>
* <TD> double </TD>
* <TD> </TD>
* <TD> the cross polarization delay. </TD>
* </TR>
* </TABLE>
*/
class DelayModelTable : public Representable {
friend class ASDM;
public:
/**
* Return the list of field names that make up key key
* as an array of strings.
* @return a vector of string.
*/
static const std::vector<std::string>& getKeyName();
virtual ~DelayModelTable();
/**
* Return the container to which this table belongs.
*
* @return the ASDM containing this table.
*/
ASDM &getContainer() const;
/**
* Return the number of rows in the table.
*
* @return the number of rows in an unsigned int.
*/
unsigned int size() const;
/**
* Return the name of this table.
*
* This is a instance method of the class.
*
* @return the name of this table in a string.
*/
std::string getName() const;
/**
* Return the name of this table.
*
* This is a static method of the class.
*
* @return the name of this table in a string.
*/
static std::string name() ;
/**
* Return the version information about this table.
*
*/
std::string getVersion() const ;
/**
* Return the names of the attributes of this table.
*
* @return a vector of string
*/
static const std::vector<std::string>& getAttributesNames();
/**
* Return the default sorted list of attributes names in the binary representation of the table.
*
* @return a const reference to a vector of string
*/
static const std::vector<std::string>& defaultAttributesNamesInBin();
/**
* Return this table's Entity.
*/
Entity getEntity() const;
/**
* Set this table's Entity.
* @param e An entity.
*/
void setEntity(Entity e);
/**
* Produces an XML representation conform
* to the schema defined for DelayModel (DelayModelTable.xsd).
*
* @returns a string containing the XML representation.
* @throws ConversionException
*/
std::string toXML() ;
#ifndef WITHOUT_ACS
// Conversion Methods
/**
* Convert this table into a DelayModelTableIDL CORBA structure.
*
* @return a pointer to a DelayModelTableIDL
*/
asdmIDL::DelayModelTableIDL *toIDL() ;
/**
* Fills the CORBA data structure passed in parameter
* with the content of this table.
*
* @param x a reference to the asdmIDL::DelayModelTableIDL to be populated
* with the content of this.
*/
void toIDL(asdmIDL::DelayModelTableIDL& x) const;
#endif
#ifndef WITHOUT_ACS
/**
* Populate this table from the content of a DelayModelTableIDL Corba structure.
*
* @throws DuplicateKey Thrown if the method tries to add a row having a key that is already in the table.
* @throws ConversionException
*/
void fromIDL(asdmIDL::DelayModelTableIDL x) ;
#endif
//
// ====> Row creation.
//
/**
* Create a new row with default values.
* @return a pointer on a DelayModelRow
*/
DelayModelRow *newRow();
/**
* Create a new row initialized to the specified values.
* @return a pointer on the created and initialized row.
* @param antennaId
* @param spectralWindowId
* @param timeInterval
* @param numPoly
* @param phaseDelay
* @param phaseDelayRate
* @param groupDelay
* @param groupDelayRate
* @param fieldId
*/
DelayModelRow *newRow(Tag antennaId, Tag spectralWindowId, ArrayTimeInterval timeInterval, int numPoly, std::vector<double > phaseDelay, std::vector<double > phaseDelayRate, std::vector<double > groupDelay, std::vector<double > groupDelayRate, Tag fieldId);
/**
* Create a new row using a copy constructor mechanism.
*
* The method creates a new DelayModelRow owned by this. Each attribute of the created row
* is a (deep) copy of the corresponding attribute of row. The method does not add
* the created row to this, its simply parents it to this, a call to the add method
* has to be done in order to get the row added (very likely after having modified
* some of its attributes).
* If row is null then the method returns a new DelayModelRow with default values for its attributes.
*
* @param row the row which is to be copied.
*/
DelayModelRow *newRow(DelayModelRow *row);
//
// ====> Append a row to its table.
//
/**
* Add a row.
* @param x a pointer to the DelayModelRow to be added.
*
* @return a pointer to a DelayModelRow. If the table contains a DelayModelRow whose attributes (key and mandatory values) are equal to x ones
* then returns a pointer on that DelayModelRow, otherwise returns x.
*
* @throw DuplicateKey { thrown when the table contains a DelayModelRow with a key equal to the x one but having
* and a value section different from x one }
*
* @note The row is inserted in the table in such a way that all the rows having the same value of
* ( antennaId, spectralWindowId ) are stored by ascending time.
* @see method getByContext.
*/
DelayModelRow* add(DelayModelRow* x) ;
//
// ====> Methods returning rows.
//
/**
* Get a collection of pointers on the rows of the table.
* @return Alls rows in a vector of pointers of DelayModelRow. The elements of this vector are stored in the order
* in which they have been added to the DelayModelTable.
*/
std::vector<DelayModelRow *> get() ;
/**
* Get a const reference on the collection of rows pointers internally hold by the table.
* @return A const reference of a vector of pointers of DelayModelRow. The elements of this vector are stored in the order
* in which they have been added to the DelayModelTable.
*
*/
const std::vector<DelayModelRow *>& get() const ;
/**
* Returns all the rows sorted by ascending startTime for a given context.
* The context is defined by a value of ( antennaId, spectralWindowId ).
*
* @return a pointer on a vector<DelayModelRow *>. A null returned value means that the table contains
* no DelayModelRow for the given ( antennaId, spectralWindowId ).
*
* @throws IllegalAccessException when a call is done to this method when it's called while the dataset has been imported with the
* option checkRowUniqueness set to false.
*/
std::vector <DelayModelRow*> *getByContext(Tag antennaId, Tag spectralWindowId);
/**
* Returns a DelayModelRow* given a key.
* @return a pointer to the row having the key whose values are passed as parameters, or 0 if
* no row exists for that key.
* @param antennaId
* @param spectralWindowId
* @param timeInterval
*
*/
DelayModelRow* getRowByKey(Tag antennaId, Tag spectralWindowId, ArrayTimeInterval timeInterval);
/**
* Look up the table for a row whose all attributes
* are equal to the corresponding parameters of the method.
* @return a pointer on this row if any, null otherwise.
*
* @param antennaId
* @param spectralWindowId
* @param timeInterval
* @param numPoly
* @param phaseDelay
* @param phaseDelayRate
* @param groupDelay
* @param groupDelayRate
* @param fieldId
*/
DelayModelRow* lookup(Tag antennaId, Tag spectralWindowId, ArrayTimeInterval timeInterval, int numPoly, std::vector<double > phaseDelay, std::vector<double > phaseDelayRate, std::vector<double > groupDelay, std::vector<double > groupDelayRate, Tag fieldId);
void setUnknownAttributeBinaryReader(const std::string& attributeName, BinaryAttributeReaderFunctor* barFctr);
BinaryAttributeReaderFunctor* getUnknownAttributeBinaryReader(const std::string& attributeName) const;
private:
/**
* Create a DelayModelTable.
* <p>
* This constructor is private because only the
* container can create tables. All tables must know the container
* to which they belong.
* @param container The container to which this table belongs.
*/
DelayModelTable (ASDM & container);
ASDM & container;
bool archiveAsBin; // If true archive binary else archive XML
bool fileAsBin ; // If true file binary else file XML
std::string version ;
Entity entity;
/**
* If this table has an autoincrementable attribute then check if *x verifies the rule of uniqueness and throw exception if not.
* Check if *x verifies the key uniqueness rule and throw an exception if not.
* Append x to its table.
* @throws DuplicateKey
*/
DelayModelRow* checkAndAdd(DelayModelRow* x, bool skipCheckUniqueness=false) ;
/**
* Brutally append an DelayModelRow x to the collection of rows already stored in this table. No uniqueness check is done !
*
* @param DelayModelRow* x a pointer onto the DelayModelRow to be appended.
*/
void append(DelayModelRow* x) ;
/**
* Brutally append an DelayModelRow x to the collection of rows already stored in this table. No uniqueness check is done !
*
* @param DelayModelRow* x a pointer onto the DelayModelRow to be appended.
*/
void addWithoutCheckingUnique(DelayModelRow* x) ;
/**
* Insert a DelayModelRow* in a vector of DelayModelRow* so that it's ordered by ascending time.
*
* @param DelayModelRow* x . The pointer to be inserted.
* @param vector <DelayModelRow*>& row . A reference to the vector where to insert x.
*
*/
DelayModelRow * insertByStartTime(DelayModelRow* x, std::vector<DelayModelRow* >& row);
// A data structure to store the pointers on the table's rows.
// In all cases we maintain a private vector of DelayModelRow s.
std::vector<DelayModelRow * > privateRows;
typedef std::vector <DelayModelRow* > TIME_ROWS;
std::map<std::string, TIME_ROWS > context;
/**
* Returns a string built by concatenating the ascii representation of the
* parameters values suffixed with a "_" character.
*/
std::string Key(Tag antennaId, Tag spectralWindowId) ;
/**
* Fills the vector vout (passed by reference) with pointers on elements of vin
* whose attributes are equal to the corresponding parameters of the method.
*
*/
void getByKeyNoAutoIncNoTime(std::vector <DelayModelRow*>& vin, std::vector <DelayModelRow*>& vout, Tag antennaId, Tag spectralWindowId);
void error() ; //throw(ConversionException);
/**
* Populate this table from the content of a XML document that is required to
* be conform to the XML schema defined for a DelayModel (DelayModelTable.xsd).
* @throws ConversionException
*
*/
void fromXML(std::string& xmlDoc) ;
std::map<std::string, BinaryAttributeReaderFunctor *> unknownAttributes2Functors;
/**
* Private methods involved during the build of this table out of the content
* of file(s) containing an external representation of a DelayModel table.
*/
void setFromMIMEFile(const std::string& directory);
/*
void openMIMEFile(const std::string& directory);
*/
void setFromXMLFile(const std::string& directory);
/**
* Serialize this into a stream of bytes and encapsulates that stream into a MIME message.
* @returns a string containing the MIME message.
*
* @param byteOrder a const pointer to a static instance of the class ByteOrder.
*
*/
std::string toMIME(const asdm::ByteOrder* byteOrder=asdm::ByteOrder::Machine_Endianity);
/**
* Extracts the binary part of a MIME message and deserialize its content
* to fill this with the result of the deserialization.
* @param mimeMsg the string containing the MIME message.
* @throws ConversionException
*/
void setFromMIME(const std::string & mimeMsg);
/**
* Private methods involved during the export of this table into disk file(s).
*/
std::string MIMEXMLPart(const asdm::ByteOrder* byteOrder=asdm::ByteOrder::Machine_Endianity);
/**
* Stores a representation (binary or XML) of this table into a file.
*
* Depending on the boolean value of its private field fileAsBin a binary serialization of this (fileAsBin==true)
* will be saved in a file "DelayModel.bin" or an XML representation (fileAsBin==false) will be saved in a file "DelayModel.xml".
* The file is always written in a directory whose name is passed as a parameter.
* @param directory The name of directory where the file containing the table's representation will be saved.
*
*/
void toFile(std::string directory);
/**
* Load the table in memory if necessary.
*/
bool loadInProgress;
void checkPresenceInMemory() {
if (!presentInMemory && !loadInProgress) {
loadInProgress = true;
setFromFile(getContainer().getDirectory());
presentInMemory = true;
loadInProgress = false;
}
}
/**
* Reads and parses a file containing a representation of a DelayModelTable as those produced by the toFile method.
* This table is populated with the result of the parsing.
* @param directory The name of the directory containing the file te be read and parsed.
* @throws ConversionException If any error occurs while reading the
* files in the directory or parsing them.
*
*/
void setFromFile(const std::string& directory);
};
} // End namespace asdm
#endif /* DelayModelTable_CLASS */
| [
"[email protected]"
] | |
1a60f766cabf468fc30a050f33ac52f938edeef1 | 1d33d0914df7b271d3f011e204607866a6c28652 | /catchBottle/DevicePlugins/Robotiq/SDK_2-Finger/Src/checksum.cpp | cdc4213b807c65cd1ae0ab864b7d73450e295330 | [] | no_license | spark-fire/first-program-copy | 02a901f21a269386a6dc1a17b3a3d48a7cb72c99 | 8d428b37d4bbb6544691763c6dd561e09749fc48 | refs/heads/master | 2021-08-18T16:21:56.723062 | 2017-11-23T07:52:47 | 2017-11-23T07:52:47 | 111,779,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,526 | cpp | #include "checksum.h"
using namespace Checksum;
quint16 Checksum::crc16ForModbus(const QByteArray &data)
{
static const quint16 crc16Table[] =
{
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
quint8 buf;
quint16 crc16 = 0xFFFF;
for ( int i = 0; i < data.size(); ++i )
{
buf = data.at( i ) ^ crc16;
crc16 >>= 8;
crc16 ^= crc16Table[ buf ];
}
return crc16;
}
quint16 Checksum::crc16ForX25(const QByteArray &data)
{
return qChecksum( data.data(), data.size() );
}
quint32 Checksum::crc32(const QByteArray &data)
{
static const quint32 crc32Table[] =
{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
quint32 crc32 = 0xffffffffL;
for ( int i = 0; i < data.size(); ++i )
{
crc32 = crc32Table[ ( crc32 ^ data.constData()[ i ]) & 0xff ] ^ ( crc32 >> 8 );
}
return (crc32 ^ 0xffffffffL);
}
| [
"[email protected]"
] | |
e55bad328d4dd3eae04c308cd75ffbbd4e402cb9 | 92cbab92136412f58bc8a0ae33b495f24060b73e | /el6-64/libtango8-devel-8.1.2-16.el6.maxlab.x86_64/usr/include/tango/Xstring.h | e95866c1ac198d4356e68fbb68b1b865cd96f33c | [] | no_license | soleil-ica/binaries-backup | baea47f410874c9379db2abf891cfb9d3824c702 | 17f053bb15deb6d134c4918bdf6bacb7e613d1f5 | refs/heads/master | 2021-01-19T04:34:12.211925 | 2018-02-22T12:53:16 | 2018-02-22T12:53:16 | 62,545,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,384 | h | //
// Copyright (C) : 2004,2005,2006,2007,2008,2009,2010,2011,2012,2013
// Synchrotron SOLEIL
// L'Orme des Merisiers
// Saint-Aubin - BP 48 - France
//
// This file is part of Tango.
//
// Tango is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tango 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 Tango. If not, see <http://www.gnu.org/licenses/>.
#ifndef XSTRING_H
#define XSTRING_H
#include <sstream>
#include <string>
template<class T> class XString{
public:
static T convertFromString(const std::string& s)
{
std::istringstream in(s);
T x;
if (in >> x)
return x;
// some sort of error handling goes here...
return 0;
}
//
static std::string convertToString(const T & t)
{
std::ostringstream out ;
if (out << std::fixed << t )
return out.str();
// some sort of error handling goes here...
return 0;
}
};
#endif
| [
"[email protected]"
] | |
fb991d1e7fe448a5f4443b393b33d319b2173e9b | fac52aacf1a7145d46f420bb2991528676e3be3f | /SDK/Zombie_Trucker_Jacket_04_classes.h | a594e764265d3fb447bc50492b503361fb191836 | [] | no_license | zH4x-SDK/zSCUM-SDK | 2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed | 711376eb272b220521fec36d84ca78fc11d4802a | refs/heads/main | 2023-07-15T16:02:22.649492 | 2021-08-27T13:44:21 | 2021-08-27T13:44:21 | 400,522,163 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 673 | h | #pragma once
// Name: SCUM, Version: 4.20.3
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Zombie_Trucker_Jacket_04.Zombie_Trucker_Jacket_04_C
// 0x0000 (0x0928 - 0x0928)
class AZombie_Trucker_Jacket_04_C : public AClothesItem
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Zombie_Trucker_Jacket_04.Zombie_Trucker_Jacket_04_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
1ffa2e88fbc3614f62dfde5a7bbd3b7a22be590b | 924704a1d4c0dc8497c372fe1b869c5ba36291b2 | /Sorting Algorithms/quick_sort.cpp | 7d99ee791b0fa4a87b9797d0a0d60759ee1fcc8d | [] | no_license | suchita08/CPP | c387cf2882ad1eeebef5acff64d942d95190ef39 | 3b402a73c2a4bfd1e206d01aec26e1c166aca461 | refs/heads/master | 2023-01-14T02:50:42.861418 | 2020-11-16T13:12:56 | 2020-11-16T13:12:56 | 276,922,683 | 0 | 1 | null | 2020-10-01T08:44:52 | 2020-07-03T14:45:30 | C++ | UTF-8 | C++ | false | false | 904 | cpp | #include<bits/stdc++.h>
using namespace std;
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
int partition (int arr[], int start, int end)
{
int pivot = arr[end];
int i = (start - 1);
for (int j =start; j <=end - 1; j++)
{
if (arr[j] < pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[end]);
return (i + 1);
}
void quick_sort(int arr[], int low, int high)
{
if (low < high)
{
int p = partition(arr, low, high);
quick_sort(arr, low, p - 1);
quick_sort(arr, p + 1, high);
}
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
cout<<"Array after sorting"<<"\n";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
} | [
"[email protected]"
] | |
69e2fa6dc843947331a00c27627b508b594abdc0 | 33152af93821a3baee32ebe9e9184adb515b7ef7 | /zircon/system/ulib/disk_inspector/test/loader_test.cc | 4accfa82fa3ebcd847018f1cd0b27c7611451eda | [
"BSD-3-Clause",
"MIT"
] | permissive | casey/fuchsia | bca750f13f1beba94b73d75b1e660bc3eb912ec3 | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | refs/heads/master | 2021-06-20T01:46:38.891626 | 2020-04-09T23:41:46 | 2020-04-09T23:41:46 | 254,491,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,472 | cc | // Copyright 2020 The Fuchsia 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 "disk_inspector/loader.h"
#include <storage/buffer/array_buffer.h>
#include <fs/transaction/block_transaction.h>
#include <zxtest/zxtest.h>
namespace disk_inspector {
namespace {
constexpr uint64_t kTestBlockSize = 8192;
class MockTransactionHandler : public fs::TransactionHandler {
public:
explicit MockTransactionHandler(storage::ArrayBuffer* mock_device) : mock_device_(mock_device) {}
MockTransactionHandler(const MockTransactionHandler&) = delete;
MockTransactionHandler(MockTransactionHandler&&) = default;
MockTransactionHandler& operator=(const MockTransactionHandler&) = delete;
MockTransactionHandler& operator=(MockTransactionHandler&&) = default;
// TransactionHandler interface:
uint64_t BlockNumberToDevice(uint64_t block_num) const final { return block_num; }
zx_status_t RunOperation(const storage::Operation& operation,
storage::BlockBuffer* buffer) final {
ValidateOperation(operation, buffer);
switch (operation.type) {
case storage::OperationType::kRead:
memcpy(buffer->Data(operation.vmo_offset), mock_device_->Data(operation.dev_offset),
operation.length * mock_device_->BlockSize());
break;
case storage::OperationType::kWrite:
memcpy(mock_device_->Data(operation.dev_offset), buffer->Data(operation.vmo_offset),
operation.length * mock_device_->BlockSize());
break;
default:
return ZX_ERR_NOT_SUPPORTED;
}
return ZX_OK;
}
block_client::BlockDevice* GetDevice() final { return nullptr; }
void ValidateOperation(const storage::Operation& operation, storage::BlockBuffer* buffer) {
ASSERT_NOT_NULL(mock_device_);
ASSERT_GE(buffer->capacity(), operation.vmo_offset + operation.length,
"Operation goes past input buffer length\n");
ASSERT_GE(mock_device_->capacity(), operation.dev_offset + operation.length,
"Operation goes past device buffer length\n");
ASSERT_NE(operation.type, storage::OperationType::kTrim, "Trim operation is not supported\n");
}
private:
storage::ArrayBuffer* mock_device_;
};
TEST(InspectorLoader, RunReadOperation) {
uint64_t block_length = 3;
storage::ArrayBuffer device(block_length, kTestBlockSize);
memset(device.Data(0), 'a', device.BlockSize());
memset(device.Data(1), 'b', device.BlockSize());
memset(device.Data(2), 'c', device.BlockSize());
MockTransactionHandler handler(&device);
Loader loader(&handler);
storage::ArrayBuffer client_buffer(block_length, kTestBlockSize);
memset(client_buffer.Data(0), 'd', client_buffer.capacity() * device.BlockSize());
ASSERT_OK(loader.RunReadOperation(&client_buffer, 0, 0, 1));
ASSERT_OK(loader.RunReadOperation(&client_buffer, 2, 2, 1));
storage::ArrayBuffer expected(block_length, kTestBlockSize);
memset(expected.Data(0), 'a', expected.BlockSize());
memset(expected.Data(1), 'd', expected.BlockSize());
memset(expected.Data(2), 'c', expected.BlockSize());
EXPECT_BYTES_EQ(client_buffer.Data(0), expected.Data(0), kTestBlockSize * block_length);
}
TEST(InspectorLoader, RunReadOperationBufferSizeAssertFail) {
ASSERT_DEATH(([] {
uint64_t block_length = 2;
storage::ArrayBuffer device(block_length, kTestBlockSize);
MockTransactionHandler handler(&device);
Loader loader(&handler);
storage::ArrayBuffer client_buffer(0, kTestBlockSize);
// Buffer too small. Should assert crash here.
loader.RunReadOperation(&client_buffer, 0, 0, block_length);
}),
"Failed to crash on buffer too small\n");
}
TEST(InspectorLoader, RunWriteOperation) {
uint64_t block_length = 3;
storage::ArrayBuffer device(block_length, kTestBlockSize);
memset(device.Data(0), 'a', device.BlockSize());
memset(device.Data(1), 'b', device.BlockSize());
memset(device.Data(2), 'c', device.BlockSize());
MockTransactionHandler handler(&device);
Loader loader(&handler);
storage::ArrayBuffer client_buffer(block_length, kTestBlockSize);
memset(client_buffer.Data(0), 'd', client_buffer.capacity() * device.BlockSize());
ASSERT_OK(loader.RunWriteOperation(&client_buffer, 0, 0, 1));
ASSERT_OK(loader.RunWriteOperation(&client_buffer, 2, 2, 1));
storage::ArrayBuffer expected(block_length, kTestBlockSize);
memset(expected.Data(0), 'd', expected.BlockSize());
memset(expected.Data(1), 'b', expected.BlockSize());
memset(expected.Data(2), 'd', expected.BlockSize());
EXPECT_BYTES_EQ(device.Data(0), expected.Data(0), kTestBlockSize * block_length);
}
TEST(InspectorLoader, RunWriteOperationBufferSizeAssertFail) {
ASSERT_DEATH(([] {
uint64_t block_length = 2;
storage::ArrayBuffer device(block_length, kTestBlockSize);
MockTransactionHandler handler(&device);
Loader loader(&handler);
storage::ArrayBuffer client_buffer(0, kTestBlockSize);
// Buffer too small. Should assert crash here.
loader.RunWriteOperation(&client_buffer, 0, 0, block_length);
}),
"Failed to crash on buffer too small\n");
}
} // namespace
} // namespace disk_inspector
| [
"[email protected]"
] | |
8ab1686db9b9169feb66cb79bcc4268d197c97b0 | 140d78334109e02590f04769ec154180b2eaf78d | /aws-cpp-sdk-lightsail/source/LightsailErrorMarshaller.cpp | d0a399ec40ea9642d68af36fc74e3d00ee1826f6 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | coderTong/aws-sdk-cpp | da140feb7e5495366a8d2a6a02cf8b28ba820ff6 | 5cd0c0a03b667c5a0bd17394924abe73d4b3754a | refs/heads/master | 2021-07-08T07:04:40.181622 | 2017-08-22T21:50:00 | 2017-08-22T21:50:00 | 101,145,374 | 0 | 1 | Apache-2.0 | 2021-05-04T21:06:36 | 2017-08-23T06:24:37 | C++ | UTF-8 | C++ | false | false | 1,082 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/core/client/AWSError.h>
#include <aws/lightsail/LightsailErrorMarshaller.h>
#include <aws/lightsail/LightsailErrors.h>
using namespace Aws::Client;
using namespace Aws::Lightsail;
AWSError<CoreErrors> LightsailErrorMarshaller::FindErrorByName(const char* errorName) const
{
AWSError<CoreErrors> error = LightsailErrorMapper::GetErrorForName(errorName);
if(error.GetErrorType() != CoreErrors::UNKNOWN)
{
return error;
}
return AWSErrorMarshaller::FindErrorByName(errorName);
} | [
"[email protected]"
] | |
57c9a205c19c840f95d0c06c3b1a4e2ca5d80417 | 00898a0e0ac2ae92cd112d2febf8d2b16fb65da4 | /Project_code/PLC-Comm/include/QtDeclarative/5.5.0/QtDeclarative/private/qdeclarativecustomparser_p.h | 525b75e5af6160d4b6c2d04e8f03d22a51193474 | [] | no_license | yisea123/AM-project | 24dd643a2f2086ea739cf48a4c6e8f95c11e42a7 | f1f7386a04985fcbd5d4fc00707cc5c3726c4ff4 | refs/heads/master | 2020-09-01T23:47:58.300736 | 2018-09-24T11:57:57 | 2018-09-24T11:57:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,473 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QDECLARATIVECUSTOMPARSER_H
#define QDECLARATIVECUSTOMPARSER_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include "private/qdeclarativemetatype_p.h"
#include "qdeclarativeerror.h"
#include "private/qdeclarativeparser_p.h"
#include "private/qdeclarativebinding_p.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qxmlstream.h>
QT_BEGIN_NAMESPACE
QT_MODULE(Declarative)
class QDeclarativeCompiler;
class QDeclarativeCustomParserPropertyPrivate;
class Q_DECLARATIVE_EXPORT QDeclarativeCustomParserProperty
{
public:
QDeclarativeCustomParserProperty();
QDeclarativeCustomParserProperty(const QDeclarativeCustomParserProperty &);
QDeclarativeCustomParserProperty &operator=(const QDeclarativeCustomParserProperty &);
~QDeclarativeCustomParserProperty();
QByteArray name() const;
QDeclarativeParser::Location location() const;
bool isList() const;
// Will be one of QDeclarativeParser::Variant, QDeclarativeCustomParserProperty or
// QDeclarativeCustomParserNode
QList<QVariant> assignedValues() const;
private:
friend class QDeclarativeCustomParserNodePrivate;
friend class QDeclarativeCustomParserPropertyPrivate;
QDeclarativeCustomParserPropertyPrivate *d;
};
class QDeclarativeCustomParserNodePrivate;
class Q_DECLARATIVE_EXPORT QDeclarativeCustomParserNode
{
public:
QDeclarativeCustomParserNode();
QDeclarativeCustomParserNode(const QDeclarativeCustomParserNode &);
QDeclarativeCustomParserNode &operator=(const QDeclarativeCustomParserNode &);
~QDeclarativeCustomParserNode();
QByteArray name() const;
QDeclarativeParser::Location location() const;
QList<QDeclarativeCustomParserProperty> properties() const;
private:
friend class QDeclarativeCustomParserNodePrivate;
QDeclarativeCustomParserNodePrivate *d;
};
class Q_DECLARATIVE_EXPORT QDeclarativeCustomParser
{
public:
enum Flag {
NoFlag = 0x00000000,
AcceptsAttachedProperties = 0x00000001
};
Q_DECLARE_FLAGS(Flags, Flag)
QDeclarativeCustomParser() : compiler(0), object(0), m_flags(NoFlag) {}
QDeclarativeCustomParser(Flags f) : compiler(0), object(0), m_flags(f) {}
virtual ~QDeclarativeCustomParser() {}
void clearErrors();
Flags flags() const { return m_flags; }
virtual QByteArray compile(const QList<QDeclarativeCustomParserProperty> &)=0;
virtual void setCustomData(QObject *, const QByteArray &)=0;
QList<QDeclarativeError> errors() const { return exceptions; }
protected:
void error(const QString& description);
void error(const QDeclarativeCustomParserProperty&, const QString& description);
void error(const QDeclarativeCustomParserNode&, const QString& description);
int evaluateEnum(const QByteArray&) const;
const QMetaObject *resolveType(const QByteArray&) const;
QDeclarativeBinding::Identifier rewriteBinding(const QString&, const QByteArray&);
private:
QList<QDeclarativeError> exceptions;
QDeclarativeCompiler *compiler;
QDeclarativeParser::Object *object;
Flags m_flags;
friend class QDeclarativeCompiler;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QDeclarativeCustomParser::Flags);
#if 0
#define QML_REGISTER_CUSTOM_TYPE(URI, VERSION_MAJ, VERSION_MIN, NAME, TYPE, CUSTOMTYPE) \
qmlRegisterCustomType<TYPE>(#URI, VERSION_MAJ, VERSION_MIN, #NAME, #TYPE, new CUSTOMTYPE)
#endif
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QDeclarativeCustomParserProperty)
Q_DECLARE_METATYPE(QDeclarativeCustomParserNode)
#endif
| [
"[email protected]"
] | |
afc7ba48447e52a54643b652003763becc4b5d7a | cd584fbc26ecf1dbc2d2bf97ff5d169502aa18c3 | /2011/LAMPS_DPA/DPA03/draw_x.cc | f7ffd4210a61f1f88edd939d683465899dd66d7c | [] | no_license | SongkyoLee/KUNPL | 10b63177354c2416a28c8ddb9761113ad93613fe | f3200a70fa07a3d1873d67e1c52a2d502b506679 | refs/heads/master | 2016-09-12T15:15:17.911319 | 2016-05-09T12:07:44 | 2016-05-09T12:07:44 | 58,053,105 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,244 | cc | #include "TFile.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TH2.h"
#include "TF1.h"
#include "TH1.h"
#include "TStyle.h"
#include "TMath.h"
#include "TROOT.h"
#include "Riostream.h"
#include <fstream>
#define XMIN 900
#define XMAX 980
#define Nbin 40
#define Nevent 1000
Double_t linfunc(Double_t* x, Double_t* par)
{
return par[0] + par[1]*x[0];
}
void draw_mass_Eloss()
{
////-------------------- read rootfile --------------------
TFile* f = new TFile("rawData.root", "READ");
TTree* t1 = (TTree*)f -> Get("SimulationData");
Int_t eventID; t1->SetBranchAddress("eventID", &eventID);
Double_t energyDeposit; t1->SetBranchAddress("energyDeposit", &energyDeposit);
Double_t hitTime; t1->SetBranchAddress("hitTime", &hitTime);
Int_t isDC; t1->SetBranchAddress("isDC", &isDC);
Int_t detID; t1->SetBranchAddress("detID", &detID);
Double_t x; t1->SetBranchAddress("x", &x);
Double_t y; t1->SetBranchAddress("y", &y);
Double_t z; t1->SetBranchAddress("z", &z);
Int_t isToF; t1->SetBranchAddress("isToF", &isToF);
Int_t detNum; t1->SetBranchAddress("detNum", &detNum);
TCanvas *c1 = new TCanvas ("c1", "histogram");
TH1F* h1 = new TH1F("h1", "mass ditribution", Nbin, XMIN, XMAX);
TF1* g1 = new TF1("g1", "gaus", XMIN, XMAX);
gStyle->SetOptStat("n");
gStyle->SetOptFit(0001);
// TCanvas* cf2 = new TCanvas("cf2", "linear fit for DC3&4");
TF1* fit1 = new TF1("fit1", linfunc, 0.0, 7.5, 2);
// fit1->SetLineWidth(1);
// fit1->SetLineColor(2);
// fit1->SetParameters(1,1);
////-------------------- get data --------------------
for (Int_t i=0; i<Nevent; i++)
{
TH2D* hf2 = new TH2D("hf2", "for DC3&4", 1000, 3000, 7500, 1000, 0, 5000);
Int_t entryNum = t1->GetEntries(Form("eventID == %d", i)); // entryNum per event
TTree* t1event = t1->CopyTree(Form("eventID == %d", i)); //make new tree for one event
Double_t ex[2]={0,0}; Double_t ey[2]={0,0}; Double_t ez[2]={0,0};
/*Double_t eDep1=0;*/ Double_t eDep2=0; Double_t eDep3=0;
Double_t minTof = 100; //default value (to find mininum tof)
for (Int_t k=0; k<entryNum; k++)
{
t1event->GetEntry(k);
if (isDC == 1) //for totalLength(mm) : position info. from DC
{
// if (detID == 0 && energyDeposit>eDep1)
// { eDep1=energyDeposit; x1=x*1e-3; y1=y*1e-3; z1=z*1e-3+0.8;}
if (detID == 3 && energyDeposit>eDep2)
{ eDep2=energyDeposit; ex[0]=x; ey[0]=y; ez[0]=z;}
else if (detID == 4 && energyDeposit>eDep3)
{ eDep3=energyDeposit; ex[1]=x; ey[1]=y; ez[1]=z;}
}
if (isToF == 1) //for tof(ns) : time of flight from ToF wall
{
if(x == 1 && minTof>hitTime) { minTof = hitTime; }
}
}
for (Int_t q=0; q<2; q++) hf2->Fill(ez[q], ex[q]);
// cf2->cd();
// hf2->SetMarkerStyle(20);
// hf2->SetMarkerSize(1);
// hf2->Draw();
hf2->Fit(fit1, "QNO");
Double_t a2 = fit1->GetParameter(1); //slope
Double_t b2 = fit1->GetParameter(0); //intercept
delete hf2;
delete t1event; //1214
////-------------------- analysis--------------------
Double_t z1 = 2.243; //mm -> m
Double_t x1 = 0;
Double_t z2 = (3.657-b2*1e-3)/(a2+1);
Double_t x2 = 3.657-z2;
Double_t z3 = (8.183-b2*1e-3)/(a2+1);
Double_t x3 = 8.183-z3;
Double_t a22 = (-1/a2); //slope
Double_t b22 = (x2+(z2/a2)); //intercept
Double_t z0 = z1; //center of the circle
Double_t x0 = a22*z0+b22;
Double_t length1 = TMath::Sqrt(x1*x1 + z1*z1);
Double_t length3 = TMath::Sqrt((x3-x2)*(x3-x2) + (z3-z2)*(z3-z2));
Double_t theta = TMath::ATan((x2-x1)/(z2-z1));
Double_t radius = TMath::Sqrt((z0-z1)*(z0-z1)+(x0-x1)*(x0-x1));
Double_t arc = radius*2*theta;
Double_t p = 0.3*radius*1000; //GeV/c -> MeV/c
Double_t totalLength = length1 + arc + length3;
Double_t v = (totalLength*100)/(minTof*1e-9); //m/ns -> cm/s
Double_t c = 2.99792458*(1e+10); // cm/s
Double_t gamma = 1/TMath::Sqrt(1-((v*v)/(c*c)));
Double_t mass = p*c/(gamma*v);
//std::cout << " " <<std::endl;
//std::cout << " z1 = " << z1 << ", x1 = " << x1 << std::endl;
//std::cout << " z2 = " << z2 << ", x2 = " << x2 << std::endl;
//std::cout << " z3 = " << z3 << ", x3 = " << x3 << std::endl;
//std::cout << " " <<std::endl;
//std::cout << " theta = " << theta << " (rad)" << std::endl;
//std::cout << " radius = " << radius << " (m)" << std::endl;
//std::cout << " arc = " << arc << " (m)" << std::endl;
//std::cout << " " <<std::endl;
//std::cout << " length1 = " << length1 << " (m)" << std::endl;
//std::cout << " length3 = " << length3 << " (m)" << std::endl;
//std::cout << " " <<std::endl;
//std::cout << " travel length = " << totalLength << " (m)" << std::endl;
//std::cout << " time of flight = " << minTof << " (ns)" << std::endl;
//std::cout << " velocity = " << v << " (cm/s)" << std::endl;
//std::cout << " " <<std::endl;
//std::cout << "p = " << p << " MeV/c, m = " << mass << " MeV/c^2" << std::endl;
//std::cout << " " <<std::endl;
h1->Fill(mass);
//h1->Fill(p);
}
h1->Draw();
h1->Fit(g1,"R");
h1->GetXaxis()->SetTitle("mass (MeV/c^2)");
//h1->GetXaxis()->SetTitle("p (MeV/c)");
h1->GetYaxis()->SetTitle("counts");
c1->SaveAs("mass_hist_Eloss.png");
}
| [
"[email protected]"
] | |
bb9769f8483f51d324d524d6d7a29829e068ddff | ffa66ab4b13172986b56fe8f5a4814f676a89901 | /sprint04/t02/app/src/dragonborn.h | 10b010a17e0dd4b312a14670f1dd5207ae0738e4 | [] | no_license | zhukovskyV/cpp_marathon | c1359228835a0fd35e949dc9b231dd33b0c59b3f | 9d7727fcdca1329408e28e19eaf2ca9d682118f8 | refs/heads/master | 2022-12-26T21:04:28.114484 | 2020-10-11T15:01:27 | 2020-10-11T15:01:27 | 303,145,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | h | #ifndef DRAGONBORN_H
#define DRAGONBORN_H
#include <map>
#include <iostream>
class Dragonborn final{
public:
enum class Actions {
Shout,
Magic,
Weapon,
Invalid
};
void executeAction(const Actions action);
private:
void shoutThuum() const;
void attackWithMagic() const;
void attackWithWeapon() const;
};
#endif
| [
"[email protected]"
] | |
7f2982d3d2d66cdf5a8751b3cd7fbbf6258abad2 | 94c4e4e0fadcb9eb6e824c6765bedb01dedf3a9b | /HW/task2/cash.cpp | dcefdb122c6e8d3a960954db3812d7fe965ed5d5 | [] | no_license | RobertVoropaev/OOP | 1054ffee96d632a57654316ce2fc1a2fedb45941 | 227fa5e0601ecff6195babe04eb43cc14b346dcf | refs/heads/master | 2020-12-31T09:39:46.315351 | 2020-03-21T17:08:35 | 2020-03-21T17:08:35 | 238,981,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 923 | cpp | //
// Created by RobertVoropaev on 15.05.2016.
//
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> M1;
map<int, int> M2;
int M, x;
int n = 0;
cin >> M;
for(int i = 0; cin >> x; i--) {
if(M1.find(x) == M1.end()) {
cout << '1' << ' ';
if(n == M) {
M1.erase(M1.find(M2.rbegin()->second));
M1[x] = i;
M2.erase(M2.rbegin()->first);
M2.insert(pair<int, int>(i, x));
}
else {
n++;
M1.insert(pair<int, int>(x, i));
M2.insert(pair<int, int>(i, x));
}
}
else {
cout << '0' << ' ';
M2.erase(M1.find(x)->second);
M2.insert(pair<int, int>(i, x));
M1[x] = i;
}
}
return 0;
}
| [
"[email protected]"
] | |
ed373f74ea6d67b66819a131f2acf29594bbf68a | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp | 30cc33ab3c3b5b42f80d3369096250208b726dd7 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 22,229 | cpp | /*
* Copyright (C) 2009, 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/loader/WorkerThreadableLoader.h"
#include "core/dom/Document.h"
#include "core/dom/ExecutionContextTask.h"
#include "core/loader/DocumentThreadableLoader.h"
#include "core/timing/WorkerGlobalScopePerformance.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerLoaderProxy.h"
#include "platform/CrossThreadFunctional.h"
#include "platform/heap/SafePoint.h"
#include "platform/network/ResourceError.h"
#include "platform/network/ResourceRequest.h"
#include "platform/network/ResourceResponse.h"
#include "platform/network/ResourceTimingInfo.h"
#include "platform/weborigin/SecurityPolicy.h"
#include "wtf/debug/Alias.h"
#include <memory>
namespace blink {
namespace {
std::unique_ptr<Vector<char>> createVectorFromMemoryRegion(
const char* data,
unsigned dataLength) {
std::unique_ptr<Vector<char>> buffer =
wrapUnique(new Vector<char>(dataLength));
memcpy(buffer->data(), data, dataLength);
return buffer;
}
} // namespace
class WorkerThreadableLoader::AsyncTaskForwarder final
: public WorkerThreadableLoader::TaskForwarder {
public:
explicit AsyncTaskForwarder(PassRefPtr<WorkerLoaderProxy> loaderProxy)
: m_loaderProxy(loaderProxy) {
DCHECK(isMainThread());
}
~AsyncTaskForwarder() override { DCHECK(isMainThread()); }
void forwardTask(const WebTraceLocation& location,
std::unique_ptr<ExecutionContextTask> task) override {
DCHECK(isMainThread());
m_loaderProxy->postTaskToWorkerGlobalScope(location, std::move(task));
}
void forwardTaskWithDoneSignal(
const WebTraceLocation& location,
std::unique_ptr<ExecutionContextTask> task) override {
DCHECK(isMainThread());
m_loaderProxy->postTaskToWorkerGlobalScope(location, std::move(task));
}
void abort() override { DCHECK(isMainThread()); }
private:
RefPtr<WorkerLoaderProxy> m_loaderProxy;
};
struct WorkerThreadableLoader::TaskWithLocation final {
TaskWithLocation(const WebTraceLocation& location,
std::unique_ptr<ExecutionContextTask> task)
: m_location(location), m_task(std::move(task)) {}
TaskWithLocation(TaskWithLocation&& task)
: TaskWithLocation(task.m_location, std::move(task.m_task)) {}
~TaskWithLocation() = default;
WebTraceLocation m_location;
std::unique_ptr<ExecutionContextTask> m_task;
};
// Observing functions and wait() need to be called on the worker thread.
// Setting functions and signal() need to be called on the main thread.
// All observing functions must be called after wait() returns, and all
// setting functions must be called before signal() is called.
class WorkerThreadableLoader::WaitableEventWithTasks final
: public ThreadSafeRefCounted<WaitableEventWithTasks> {
public:
static PassRefPtr<WaitableEventWithTasks> create() {
return adoptRef(new WaitableEventWithTasks);
}
void signal() {
DCHECK(isMainThread());
CHECK(!m_isSignalCalled);
m_isSignalCalled = true;
m_event.signal();
}
void wait() {
DCHECK(!isMainThread());
CHECK(!m_isWaitDone);
m_event.wait();
m_isWaitDone = true;
}
// Observing functions
bool isAborted() const {
DCHECK(!isMainThread());
CHECK(m_isWaitDone);
return m_isAborted;
}
Vector<TaskWithLocation> take() {
DCHECK(!isMainThread());
CHECK(m_isWaitDone);
return std::move(m_tasks);
}
// Setting functions
void append(TaskWithLocation task) {
DCHECK(isMainThread());
CHECK(!m_isSignalCalled);
m_tasks.append(std::move(task));
}
void setIsAborted() {
DCHECK(isMainThread());
CHECK(!m_isSignalCalled);
m_isAborted = true;
}
private:
WaitableEventWithTasks() {}
WaitableEvent m_event;
Vector<TaskWithLocation> m_tasks;
bool m_isAborted = false;
bool m_isSignalCalled = false;
bool m_isWaitDone = false;
};
class WorkerThreadableLoader::SyncTaskForwarder final
: public WorkerThreadableLoader::TaskForwarder {
public:
explicit SyncTaskForwarder(PassRefPtr<WaitableEventWithTasks> eventWithTasks)
: m_eventWithTasks(eventWithTasks) {
DCHECK(isMainThread());
}
~SyncTaskForwarder() override { DCHECK(isMainThread()); }
void forwardTask(const WebTraceLocation& location,
std::unique_ptr<ExecutionContextTask> task) override {
DCHECK(isMainThread());
m_eventWithTasks->append(TaskWithLocation(location, std::move(task)));
}
void forwardTaskWithDoneSignal(
const WebTraceLocation& location,
std::unique_ptr<ExecutionContextTask> task) override {
DCHECK(isMainThread());
m_eventWithTasks->append(TaskWithLocation(location, std::move(task)));
m_eventWithTasks->signal();
}
void abort() override {
DCHECK(isMainThread());
m_eventWithTasks->setIsAborted();
m_eventWithTasks->signal();
}
private:
RefPtr<WaitableEventWithTasks> m_eventWithTasks;
};
WorkerThreadableLoader::WorkerThreadableLoader(
WorkerGlobalScope& workerGlobalScope,
ThreadableLoaderClient* client,
const ThreadableLoaderOptions& options,
const ResourceLoaderOptions& resourceLoaderOptions,
BlockingBehavior blockingBehavior)
: m_workerGlobalScope(&workerGlobalScope),
m_workerLoaderProxy(workerGlobalScope.thread()->workerLoaderProxy()),
m_client(client),
m_threadableLoaderOptions(options),
m_resourceLoaderOptions(resourceLoaderOptions),
m_blockingBehavior(blockingBehavior) {
DCHECK(client);
}
void WorkerThreadableLoader::loadResourceSynchronously(
WorkerGlobalScope& workerGlobalScope,
const ResourceRequest& request,
ThreadableLoaderClient& client,
const ThreadableLoaderOptions& options,
const ResourceLoaderOptions& resourceLoaderOptions) {
(new WorkerThreadableLoader(workerGlobalScope, &client, options,
resourceLoaderOptions, LoadSynchronously))
->start(request);
}
WorkerThreadableLoader::~WorkerThreadableLoader() {
DCHECK(!m_mainThreadLoaderHolder);
DCHECK(!m_client);
}
void WorkerThreadableLoader::start(const ResourceRequest& originalRequest) {
ResourceRequest request(originalRequest);
if (!request.didSetHTTPReferrer())
request.setHTTPReferrer(SecurityPolicy::generateReferrer(
m_workerGlobalScope->getReferrerPolicy(), request.url(),
m_workerGlobalScope->outgoingReferrer()));
DCHECK(!isMainThread());
RefPtr<WaitableEventWithTasks> eventWithTasks;
if (m_blockingBehavior == LoadSynchronously)
eventWithTasks = WaitableEventWithTasks::create();
m_workerLoaderProxy->postTaskToLoader(
BLINK_FROM_HERE,
createCrossThreadTask(
&MainThreadLoaderHolder::createAndStart,
wrapCrossThreadPersistent(this), m_workerLoaderProxy,
wrapCrossThreadPersistent(
m_workerGlobalScope->thread()->getWorkerThreadLifecycleContext()),
request, m_threadableLoaderOptions, m_resourceLoaderOptions,
eventWithTasks));
if (m_blockingBehavior == LoadAsynchronously)
return;
eventWithTasks->wait();
if (eventWithTasks->isAborted()) {
// This thread is going to terminate.
cancel();
return;
}
for (const auto& task : eventWithTasks->take()) {
// Store the program counter where the task is posted from, and alias
// it to ensure it is stored in the crash dump.
const void* programCounter = task.m_location.program_counter();
WTF::debug::alias(&programCounter);
// m_clientTask contains only CallClosureTasks. So, it's ok to pass
// the nullptr.
task.m_task->performTask(nullptr);
}
}
void WorkerThreadableLoader::overrideTimeout(
unsigned long timeoutMilliseconds) {
DCHECK(!isMainThread());
if (!m_mainThreadLoaderHolder)
return;
m_workerLoaderProxy->postTaskToLoader(
BLINK_FROM_HERE,
createCrossThreadTask(&MainThreadLoaderHolder::overrideTimeout,
m_mainThreadLoaderHolder, timeoutMilliseconds));
}
void WorkerThreadableLoader::cancel() {
DCHECK(!isMainThread());
if (m_mainThreadLoaderHolder) {
m_workerLoaderProxy->postTaskToLoader(
BLINK_FROM_HERE, createCrossThreadTask(&MainThreadLoaderHolder::cancel,
m_mainThreadLoaderHolder));
m_mainThreadLoaderHolder = nullptr;
}
if (!m_client)
return;
// If the client hasn't reached a termination state, then transition it
// by sending a cancellation error.
// Note: no more client callbacks will be done after this method -- the
// clearClient() call ensures that.
ResourceError error(String(), 0, String(), String());
error.setIsCancellation(true);
didFail(error);
DCHECK(!m_client);
}
void WorkerThreadableLoader::didStart(
MainThreadLoaderHolder* mainThreadLoaderHolder) {
DCHECK(!isMainThread());
DCHECK(!m_mainThreadLoaderHolder);
DCHECK(mainThreadLoaderHolder);
if (!m_client) {
// The thread is terminating.
m_workerLoaderProxy->postTaskToLoader(
BLINK_FROM_HERE, createCrossThreadTask(&MainThreadLoaderHolder::cancel,
wrapCrossThreadPersistent(
mainThreadLoaderHolder)));
return;
}
m_mainThreadLoaderHolder = mainThreadLoaderHolder;
}
void WorkerThreadableLoader::didSendData(
unsigned long long bytesSent,
unsigned long long totalBytesToBeSent) {
DCHECK(!isMainThread());
if (!m_client)
return;
m_client->didSendData(bytesSent, totalBytesToBeSent);
}
void WorkerThreadableLoader::didReceiveResponse(
unsigned long identifier,
std::unique_ptr<CrossThreadResourceResponseData> responseData,
std::unique_ptr<WebDataConsumerHandle> handle) {
DCHECK(!isMainThread());
if (!m_client)
return;
ResourceResponse response(responseData.get());
m_client->didReceiveResponse(identifier, response, std::move(handle));
}
void WorkerThreadableLoader::didReceiveData(
std::unique_ptr<Vector<char>> data) {
DCHECK(!isMainThread());
CHECK_LE(data->size(), std::numeric_limits<unsigned>::max());
if (!m_client)
return;
m_client->didReceiveData(data->data(), data->size());
}
void WorkerThreadableLoader::didReceiveCachedMetadata(
std::unique_ptr<Vector<char>> data) {
DCHECK(!isMainThread());
if (!m_client)
return;
m_client->didReceiveCachedMetadata(data->data(), data->size());
}
void WorkerThreadableLoader::didFinishLoading(unsigned long identifier,
double finishTime) {
DCHECK(!isMainThread());
if (!m_client)
return;
auto* client = m_client;
m_client = nullptr;
m_mainThreadLoaderHolder = nullptr;
client->didFinishLoading(identifier, finishTime);
}
void WorkerThreadableLoader::didFail(const ResourceError& error) {
DCHECK(!isMainThread());
if (!m_client)
return;
auto* client = m_client;
m_client = nullptr;
m_mainThreadLoaderHolder = nullptr;
client->didFail(error);
}
void WorkerThreadableLoader::didFailAccessControlCheck(
const ResourceError& error) {
DCHECK(!isMainThread());
if (!m_client)
return;
auto* client = m_client;
m_client = nullptr;
m_mainThreadLoaderHolder = nullptr;
client->didFailAccessControlCheck(error);
}
void WorkerThreadableLoader::didFailRedirectCheck() {
DCHECK(!isMainThread());
if (!m_client)
return;
auto* client = m_client;
m_client = nullptr;
m_mainThreadLoaderHolder = nullptr;
client->didFailRedirectCheck();
}
void WorkerThreadableLoader::didDownloadData(int dataLength) {
DCHECK(!isMainThread());
if (!m_client)
return;
m_client->didDownloadData(dataLength);
}
void WorkerThreadableLoader::didReceiveResourceTiming(
std::unique_ptr<CrossThreadResourceTimingInfoData> timingData) {
DCHECK(!isMainThread());
if (!m_client)
return;
std::unique_ptr<ResourceTimingInfo> info(
ResourceTimingInfo::adopt(std::move(timingData)));
WorkerGlobalScopePerformance::performance(*m_workerGlobalScope)
->addResourceTiming(*info);
m_client->didReceiveResourceTiming(*info);
}
DEFINE_TRACE(WorkerThreadableLoader) {
visitor->trace(m_workerGlobalScope);
ThreadableLoader::trace(visitor);
}
void WorkerThreadableLoader::MainThreadLoaderHolder::createAndStart(
WorkerThreadableLoader* workerLoader,
PassRefPtr<WorkerLoaderProxy> passLoaderProxy,
WorkerThreadLifecycleContext* workerThreadLifecycleContext,
std::unique_ptr<CrossThreadResourceRequestData> request,
const ThreadableLoaderOptions& options,
const ResourceLoaderOptions& resourceLoaderOptions,
PassRefPtr<WaitableEventWithTasks> eventWithTasks,
ExecutionContext* executionContext) {
DCHECK(isMainThread());
TaskForwarder* forwarder;
RefPtr<WorkerLoaderProxy> loaderProxy = passLoaderProxy;
if (eventWithTasks)
forwarder = new SyncTaskForwarder(std::move(eventWithTasks));
else
forwarder = new AsyncTaskForwarder(loaderProxy);
MainThreadLoaderHolder* mainThreadLoaderHolder =
new MainThreadLoaderHolder(forwarder, workerThreadLifecycleContext);
if (mainThreadLoaderHolder->wasContextDestroyedBeforeObserverCreation()) {
// The thread is already terminating.
forwarder->abort();
mainThreadLoaderHolder->m_forwarder = nullptr;
return;
}
mainThreadLoaderHolder->m_workerLoader = workerLoader;
forwarder->forwardTask(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didStart,
wrapCrossThreadPersistent(workerLoader),
wrapCrossThreadPersistent(mainThreadLoaderHolder)));
mainThreadLoaderHolder->start(*toDocument(executionContext),
std::move(request), options,
resourceLoaderOptions);
}
WorkerThreadableLoader::MainThreadLoaderHolder::~MainThreadLoaderHolder() {
DCHECK(isMainThread());
DCHECK(!m_workerLoader);
}
void WorkerThreadableLoader::MainThreadLoaderHolder::overrideTimeout(
unsigned long timeoutMilliseconds) {
DCHECK(isMainThread());
if (!m_mainThreadLoader)
return;
m_mainThreadLoader->overrideTimeout(timeoutMilliseconds);
}
void WorkerThreadableLoader::MainThreadLoaderHolder::cancel() {
DCHECK(isMainThread());
m_workerLoader = nullptr;
if (!m_mainThreadLoader)
return;
m_mainThreadLoader->cancel();
m_mainThreadLoader = nullptr;
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didSendData(
unsigned long long bytesSent,
unsigned long long totalBytesToBeSent) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.get();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTask(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didSendData, workerLoader,
bytesSent, totalBytesToBeSent));
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didReceiveResponse(
unsigned long identifier,
const ResourceResponse& response,
std::unique_ptr<WebDataConsumerHandle> handle) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.get();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTask(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didReceiveResponse,
workerLoader, identifier, response,
passed(std::move(handle))));
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didReceiveData(
const char* data,
unsigned dataLength) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.get();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTask(
BLINK_FROM_HERE,
createCrossThreadTask(
&WorkerThreadableLoader::didReceiveData, workerLoader,
passed(createVectorFromMemoryRegion(data, dataLength))));
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didDownloadData(
int dataLength) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.get();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTask(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didDownloadData,
workerLoader, dataLength));
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didReceiveCachedMetadata(
const char* data,
int dataLength) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.get();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTask(
BLINK_FROM_HERE,
createCrossThreadTask(
&WorkerThreadableLoader::didReceiveCachedMetadata, workerLoader,
passed(createVectorFromMemoryRegion(data, dataLength))));
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didFinishLoading(
unsigned long identifier,
double finishTime) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.release();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTaskWithDoneSignal(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didFinishLoading,
workerLoader, identifier, finishTime));
m_forwarder = nullptr;
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didFail(
const ResourceError& error) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.release();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTaskWithDoneSignal(
BLINK_FROM_HERE, createCrossThreadTask(&WorkerThreadableLoader::didFail,
workerLoader, error));
m_forwarder = nullptr;
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didFailAccessControlCheck(
const ResourceError& error) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.release();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTaskWithDoneSignal(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didFailAccessControlCheck,
workerLoader, error));
m_forwarder = nullptr;
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didFailRedirectCheck() {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.release();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTaskWithDoneSignal(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didFailRedirectCheck,
workerLoader));
m_forwarder = nullptr;
}
void WorkerThreadableLoader::MainThreadLoaderHolder::didReceiveResourceTiming(
const ResourceTimingInfo& info) {
DCHECK(isMainThread());
CrossThreadPersistent<WorkerThreadableLoader> workerLoader =
m_workerLoader.get();
if (!workerLoader || !m_forwarder)
return;
m_forwarder->forwardTask(
BLINK_FROM_HERE,
createCrossThreadTask(&WorkerThreadableLoader::didReceiveResourceTiming,
workerLoader, info));
}
void WorkerThreadableLoader::MainThreadLoaderHolder::contextDestroyed() {
DCHECK(isMainThread());
if (m_forwarder) {
m_forwarder->abort();
m_forwarder = nullptr;
}
cancel();
}
DEFINE_TRACE(WorkerThreadableLoader::MainThreadLoaderHolder) {
visitor->trace(m_forwarder);
visitor->trace(m_mainThreadLoader);
WorkerThreadLifecycleObserver::trace(visitor);
}
WorkerThreadableLoader::MainThreadLoaderHolder::MainThreadLoaderHolder(
TaskForwarder* forwarder,
WorkerThreadLifecycleContext* context)
: WorkerThreadLifecycleObserver(context), m_forwarder(forwarder) {
DCHECK(isMainThread());
}
void WorkerThreadableLoader::MainThreadLoaderHolder::start(
Document& document,
std::unique_ptr<CrossThreadResourceRequestData> request,
const ThreadableLoaderOptions& options,
const ResourceLoaderOptions& originalResourceLoaderOptions) {
DCHECK(isMainThread());
ResourceLoaderOptions resourceLoaderOptions = originalResourceLoaderOptions;
resourceLoaderOptions.requestInitiatorContext = WorkerContext;
m_mainThreadLoader = DocumentThreadableLoader::create(document, this, options,
resourceLoaderOptions);
m_mainThreadLoader->start(ResourceRequest(request.get()));
}
} // namespace blink
| [
"[email protected]"
] | |
3114778db19d83dcadbb7cfbee8ff2335c0598ca | 9fe0a8d3607fb70d8004477f925316c053957351 | /crm_r_loine/source/crm_dialog/dlg_message.cpp | 24460e7b4d3004875b45473fbeb8ecf793114278 | [] | no_license | dekalo64/RLine | f0b43d4a3427cd1dd0c8730a3de95c63ff199ca7 | 650b9db4d1708e250dd67ebc63d3699e89ef2b6c | refs/heads/master | 2020-12-25T18:20:08.117341 | 2014-01-06T12:51:22 | 2014-01-06T12:51:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,980 | cpp | #include "source/crm_dialog/dlg_message.h"
CMessage::CMessage(QWidget *parent, const QString title, const QString text):
QMessageBox(parent)
{
setWindowFlags(Qt::Drawer);
setWindowTitle(title);
setText(text);
QPixmap pixmap("data/picture/additionally/alert.png");
setIconPixmap(pixmap);
QFont font(QFont("Arial", 8));
font.setBold (true);
setFont(font);
setStyleSheet("QMessageBox {"
"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
"stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,"
"stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);"
"}"
"QPushButton {"
"border: 1px solid #515151;"
"border-radius: 2px;"
"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
"stop: 0 #FFFFFF, stop: 0.5 #FFFFFF,"
"stop: 0.51 #FFFFFF, stop: 1 #e3e3e3);"
"color: #515151;"
"min-width: 80px;"
"min-height: 25px;"
"font: bold;"
"font-family: Arial;"
"}"
"QPushButton:pressed {"
"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
"stop: 0 #e3e3e3, stop: 0.50 #FFFFFF,"
"stop: 0.51 #FFFFFF, stop: 1 #e3e3e3);"
"color: #515151;"
"}");
setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), qApp->desktop()->availableGeometry()));
}
CMessage::~CMessage()
{
}
void CMessage::closeEvent(QCloseEvent *event)
{
event->accept();
}
| [
"[email protected]"
] | |
a727fb12e0aabe538407832b9d1cfbfd4825627a | 27771fdde45b6af5d80cfae07d9fbecd3d9b2ac2 | /Trabalho final parte 1/codigo/Save.cpp | 148201e83799feb91bfcc97098b3fbe5fa8f2d70 | [] | no_license | TheZambi/AEDA | 0a55be585a53d82df11a40d55e9305d9e061d515 | ea8be213ab81d8d4f54f322c9357af2eabc910ad | refs/heads/master | 2023-04-17T01:40:28.481192 | 2021-05-01T11:36:11 | 2021-05-01T11:36:11 | 363,391,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,901 | cpp | #include "Save.h"
extern Company *comp;
void saveAirports() {
ofstream newAirportsFile;
string s = "Airports.txt";
newAirportsFile.open("newAirports.txt");
if (comp->getAirports().size() != 0) {
for (size_t i = 0; i < comp->getAirports().size() - 1; i++) {
newAirportsFile << comp->getAirports().at(i)->getLocal().getCountry() << endl;
newAirportsFile << comp->getAirports().at(i)->getLocal().getCity() << endl;
newAirportsFile << comp->getAirports().at(i)->getLocal().getLatit() << endl;
newAirportsFile << comp->getAirports().at(i)->getLocal().getLon() << endl;
newAirportsFile << comp->getAirports().at(i)->flightTxt << endl;
newAirportsFile << comp->getAirports().at(i)->planesTxt << endl;
newAirportsFile << comp->getAirports().at(i)->employeeTxt << endl;
newAirportsFile << comp->getAirports().at(i)->manager.name << endl;
newAirportsFile << comp->getAirports().at(i)->manager.birthDate->getDate() << endl;
newAirportsFile << comp->getAirports().at(i)->manager.salary << endl;
newAirportsFile << "::::::::::\n";
}
size_t size = comp->getAirports().size()- 1;
newAirportsFile << comp->getAirports().at(size)->getLocal().getCountry() << endl;
newAirportsFile << comp->getAirports().at(size)->getLocal().getCity() << endl;
newAirportsFile << comp->getAirports().at(size)->getLocal().getLatit() << endl;
newAirportsFile << comp->getAirports().at(size)->getLocal().getLon() << endl;
newAirportsFile << comp->getAirports().at(size)->flightTxt << endl;
newAirportsFile << comp->getAirports().at(size)->planesTxt << endl;
newAirportsFile << comp->getAirports().at(size)->employeeTxt << endl;
newAirportsFile << comp->getAirports().at(size)->manager.name << endl;
newAirportsFile << comp->getAirports().at(size)->manager.birthDate->getDate() << endl;
newAirportsFile << comp->getAirports().at(size)->manager.salary << endl;
}
const char* fileName = s.c_str();
newAirportsFile.close();
remove(fileName);
rename("newAirports.txt", fileName);
}
void SaveFlights() {
ofstream newFlightsFile;
if (comp->getAirports().size() == 0)
return;
for (size_t i = 0; i < comp->getAirports().size(); i++) {
newFlightsFile.open("newFlights.txt");
if (comp->getAirports().at(i)->flights.size() != 0){
for (size_t j = 0; j < comp->getAirports().at(i)->flights.size()-1; j++) {
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getId() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getPredictedSchedule().getDepartureDate() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getPredictedSchedule().getArrivalDate() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getPredictedSchedule().getStartHour().getHours() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getPredictedSchedule().getStartHour().getMinutes() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getPredictedSchedule().getEndHour().getHours() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getPredictedSchedule().getEndHour().getMinutes() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(j)->getDestination() << endl;
newFlightsFile << ":::::::::::\n";
}
size_t size = comp->getAirports().at(i)->flights.size() - 1;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getId() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getPredictedSchedule().getDepartureDate() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getPredictedSchedule().getArrivalDate() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getPredictedSchedule().getStartHour().getHours() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getPredictedSchedule().getStartHour().getMinutes() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getPredictedSchedule().getEndHour().getHours() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getPredictedSchedule().getEndHour().getMinutes() << endl;
newFlightsFile << comp->getAirports().at(i)->flights.at(size)->getDestination() << endl;
}
const char* fileName = comp->getAirports().at(i)->flightTxt.c_str();
newFlightsFile.close();
remove(fileName);
rename("newFlights.txt", fileName);
}
}
void SaveEmployees() {
ofstream newEmployeesFile;
if (comp->getAirports().size() == 0)
return;
for (size_t i = 0; i < comp->getAirports().size(); i++) {
newEmployeesFile.open("newEmployees.txt");
if(comp->getAirports().at(i)->employees.size() != 0) {
for (size_t j = 0; j < comp->getAirports().at(i)->employees.size() - 1; j++) {
if (comp->getAirports().at(i)->employees.at(j)->getType() == "Pilot") {
string flights = "";
size_t size = comp->getAirports().at(i)->employees.at(j)->getFlights().size();
if (size > 0)
{
for (size_t k = 0; k < size; k++)
{
if (k < (size - 1))
flights += to_string(comp->getAirports().at(i)->employees.at(j)->getFlights().at(k)->getId()) + ", ";
else
flights += to_string(comp->getAirports().at(i)->employees.at(j)->getFlights().at(k)->getId());
}
}
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getCategory() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getPlaneTypes() << endl;
newEmployeesFile << flights << endl;
newEmployeesFile << "::::::::::\n";
}
else if (comp->getAirports().at(i)->employees.at(j)->getType() == "Flight Crew") {
string flights = "";
size_t size = comp->getAirports().at(i)->employees.at(j)->getFlights().size();
if (size > 0)
{
for (size_t k = 0; k < size; k++)
{
if (k < (size - 1))
flights += to_string(comp->getAirports().at(i)->employees.at(j)->getFlights().at(k)->getId()) + ", ";
else
flights += to_string(comp->getAirports().at(i)->employees.at(j)->getFlights().at(k)->getId());
}
}
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getCategory() << endl;
newEmployeesFile << flights << endl;
newEmployeesFile << "::::::::::\n";
}
else if (comp->getAirports().at(i)->employees.at(j)->getType() == "Admin") {
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getDepartment() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getFunction() << endl;
newEmployeesFile << "::::::::::\n";
}
else if (comp->getAirports().at(i)->employees.at(j)->getType() == "Base Crew") {
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getCategory() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getSchedule()->getStartHour().getHours() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getSchedule()->getStartHour().getMinutes() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getSchedule()->getEndHour().getHours() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(j)->getSchedule()->getEndHour().getMinutes() << endl;
newEmployeesFile << "::::::::::\n";
}
}
size_t EmpSize = comp->getAirports().at(i)->employees.size() - 1;
if (comp->getAirports().at(i)->employees.at(EmpSize)->getType() == "Pilot") {
string flights = "";
size_t size = comp->getAirports().at(i)->employees.at(EmpSize)->getFlights().size();
if (size > 0)
{
for (size_t k = 0; k < size; k++)
{
if (k < (size - 1))
flights += to_string(comp->getAirports().at(i)->employees.at(EmpSize)->getFlights().at(k)->getId()) + ", ";
else
flights += to_string(comp->getAirports().at(i)->employees.at(EmpSize)->getFlights().at(k)->getId());
}
}
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getCategory() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getPlaneTypes() << endl;
newEmployeesFile << flights << endl;
}
else if (comp->getAirports().at(i)->employees.at(EmpSize)->getType() == "Flight Crew") {
string flights = "";
size_t size = comp->getAirports().at(i)->employees.at(EmpSize)->getFlights().size();
if (size > 0)
{
for (size_t k = 0; k < size; k++)
{
if (k < (size - 1))
flights += to_string(comp->getAirports().at(i)->employees.at(EmpSize)->getFlights().at(k)->getId()) + ", ";
else
flights += to_string(comp->getAirports().at(i)->employees.at(EmpSize)->getFlights().at(k)->getId());
}
}
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getCategory() << endl;
newEmployeesFile << flights << endl;
}
else if (comp->getAirports().at(i)->employees.at(EmpSize)->getType() == "Admin") {
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getDepartment() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getFunction() << endl;
}
else if (comp->getAirports().at(i)->employees.at(EmpSize)->getType() == "Base Crew") {
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getType() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getName() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getDate() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getCategory() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getSchedule()->getStartHour().getHours() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getSchedule()->getStartHour().getMinutes() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getSchedule()->getEndHour().getHours() << endl;
newEmployeesFile << comp->getAirports().at(i)->employees.at(EmpSize)->getSchedule()->getEndHour().getMinutes() << endl;
}
}
const char* fileName = comp->getAirports().at(i)->employeeTxt.c_str();
newEmployeesFile.close();
remove(fileName);
rename("newEmployees.txt", fileName);
}
}
void SavePlanes() {
ofstream newPlanesFile;
for (size_t i = 0; i < comp->getAirports().size(); i++) {
newPlanesFile.open("newPlanes.txt");
if (comp->getAirports().at(i)->planes.size() != 0) {
for (size_t j = 0; j < comp->getAirports().at(i)->planes.size() - 1; j++) {
string flights = "";
size_t size = comp->getAirports().at(i)->planes.at(j)->getFlights().size();
if (size > 0)
{
for (size_t k = 0; k < size; k++)
{
if (k < (size - 1))
flights += to_string(comp->getAirports().at(i)->planes.at(j)->getFlights().at(k)->getId()) + ", ";
else
flights += to_string(comp->getAirports().at(i)->planes.at(j)->getFlights().at(k)->getId());
}
}
newPlanesFile << comp->getAirports().at(i)->planes.at(j)->getType() << endl;
newPlanesFile << comp->getAirports().at(i)->planes.at(j)->getCapacity() << endl;
newPlanesFile << flights << endl;
newPlanesFile << ":::::::::::\n";
}
size_t PlaneSize = comp->getAirports().at(i)->planes.size() - 1;
string flights = "";
size_t size = comp->getAirports().at(i)->planes.at(PlaneSize)->getFlights().size();
if (size > 0)
{
for (size_t i = 0; i < size; i++)
{
if (i < (size - 1))
flights += to_string(comp->getAirports().at(i)->planes.at(PlaneSize)->getFlights().at(i)->getId()) + ", ";
else
flights += to_string(comp->getAirports().at(i)->planes.at(PlaneSize)->getFlights().at(i)->getId());
}
}
newPlanesFile << comp->getAirports().at(i)->planes.at(PlaneSize)->getType() << endl;
newPlanesFile << comp->getAirports().at(i)->planes.at(PlaneSize)->getCapacity() << endl;
newPlanesFile << flights << endl;
}
const char* fileName = comp->getAirports().at(i)->planesTxt.c_str();
newPlanesFile.close();
remove(fileName);
rename("newPlanes.txt", fileName);
}
} | [
"[email protected]"
] | |
d22822bf9a607fdac46865a726c37d211219f387 | 70e99b8bce54db216e3068992ffe3c010f63f43c | /day1/day1-1.cpp | 0212fdc4798b2d46edd7513ca9445ac8295693d5 | [] | no_license | yuanLeeMidori/advent-of-code-self-practice | 73ac5c8da792b8b2319bf2b9b764d01b1658dd86 | e6f79357aebf70d3e2b207bb726eb5b503d93fec | refs/heads/master | 2023-02-21T21:36:08.047362 | 2021-01-25T04:09:20 | 2021-01-25T04:09:20 | 332,625,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *args[]) {
char *filename;
string line;
int num;
vector<int> numList;
filename = args[1];
int sum;
cout << "file name: " << filename << endl;
ifstream file(filename);
if (file.is_open()) {
while (getline(file, line)) {
num++;
int x = stoi(line);
numList.push_back(x);
}
for (int i = 0; i <= num; i++) {
for (int j = 1; j < num; j++) {
sum = numList[i] + numList[i + j];
if (sum == 2020) {
cout << numList[i] << " + " << numList[i + j] << endl;
cout << numList[i] << " x " << numList[i + j] << " = " << numList[i] * numList[i + j] << endl;
}
}
}
file.close();
} else {
cout << "file can't open" << endl;
}
return 0;
} | [
"[email protected]"
] | |
31d4f4d7fc53b7830cdbf1986f04fedb69a1d59e | 39bd6fdcfe5abb5b0346a84e2cfe1e1eae6ea47b | /Source/RenderingTechnique.h | 180c4726af60a5f8bbc6df4ca88c9325c2aa5e42 | [] | no_license | apozTrof/shader | ef190dc3a12d2ef5db3cfee5954585a9f91d96a2 | 8763561fd501f0481547d678bde50ea5ed18eaef | refs/heads/master | 2021-01-01T04:05:48.157742 | 2016-04-21T02:33:18 | 2016-04-21T02:33:18 | 56,735,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,051 | h | #ifndef RENDERINGTECHNIQUE_H_
#define RENDERINGTECHNIQUE_H_
//Generic rendering technique class interface. This class
//controls the rendering for the geometry. Place the required
//shaders or textures related to a given rendering technique
//in a class derived from this.
class RenderingTechnique
{
public:
//The constructor is called once when the application
//starts.
RenderingTechnique(){};
//The destructor is called when the application closes.
virtual ~RenderingTechnique(){};
//This method is called before rendering the
//geometry. (Load shader or textures, configure
//the shader's uniform variables, etc.)
virtual void PreRender() = 0;
//This method is called after rendering the
//geometry. (Unload shader or textures here)
virtual void PostRender() = 0;
//If the technique is active, this method receives the
//user's keyboard input. The pressed key is passed through
//the aKey argument.
virtual void ReceiveInput(char aKey) = 0;
};
#endif //RENDERINGTECHNIQUE_H_
| [
"[email protected]"
] | |
257863984c74e71477abf4d65aedcbb557ba4a8b | 964eb24f302be56f1c57a8c6b80382d60c371ba1 | /SH/fd/fd.cpp | 4891f81c9bbf803bfd9c8ba36d57e0b3c4198869 | [] | no_license | eminenceG/FD | 4a41da9be2627f09cb7a8f7da2ee38914a8754aa | 922d9ca430e664dfab79343be192ee52de2acbd3 | refs/heads/master | 2021-01-19T08:59:35.556256 | 2017-04-09T12:45:18 | 2017-04-09T12:45:18 | 87,707,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,866 | cpp | #include"fd.h"
#include"../param/const.h"
#include"../param/param.h"
#include"../material/material.h"
#include"../field/field.h"
#include"../cpml/cpml.h"
#include<algorithm>
using namespace std;
#define topabsorb false
#define TxDIFF \
Tx_x=g_coef[ord][0]*( Tx(ix,iz) - Tx(ix-1,iz) )\
-g_coef[ord][1]*( Tx(ix+1,iz) - Tx(ix-2,iz) )\
+g_coef[ord][2]*( Tx(ix+2,iz) - Tx(ix-3,iz) )\
-g_coef[ord][3]*( Tx(ix+3,iz) - Tx(ix-4,iz) );
#define TzDIFF \
Tz_z=g_coef[ord][0]*( Tz(ix,iz+1) - Tz(ix,iz) )\
-g_coef[ord][1]*( Tz(ix,iz+2) - Tz(ix,iz-1) )\
+g_coef[ord][2]*( Tz(ix,iz+3) - Tz(ix,iz-2) )\
-g_coef[ord][3]*( Tz(ix,iz+4) - Tz(ix,iz-3) );
#define DxV \
dxV=g_coef[ord][0]*( V(ix+1,iz) - V(ix,iz) )\
-g_coef[ord][1]*( V(ix+2,iz) - V(ix-1,iz) )\
+g_coef[ord][2]*( V(ix+3,iz) - V(ix-2,iz) )\
-g_coef[ord][3]*( V(ix+4,iz) - V(ix-3,iz) );
#define DzV \
dzV=g_coef[ord][0]*( V(ix,iz) - V(ix,iz-1) )\
-g_coef[ord][1]*( V(ix,iz+1) - V(ix,iz-2) )\
+g_coef[ord][2]*( V(ix,iz+2) - V(ix,iz-3) )\
-g_coef[ord][3]*( V(ix,iz+3) - V(ix,iz-4) );
#define Tx(ix,iz) Tx[ix+(iz)*nx]
#define Tz(ix,iz) Tz[ix+(iz)*nx]
#define V(ix,iz) V[ix+(iz)*nx]
void step_stress(FIELD & fld,MATERIAL & mat,CPML & cpml)
{
int ord,idx;
float dxV,dzV;
int nx=fld.nx;
int nz=fld.nz;
int npml=cpml.npml;
float * __restrict__ Tx=fld.Tx;
float * __restrict__ Tz=fld.Tz;
float * __restrict__ V=fld.V;
float * __restrict__ MUX=mat.MUX;
float * __restrict__ MUZ=mat.MUZ;
float * __restrict__ psi_V_x=cpml.psi.V_x;
float * __restrict__ psi_V_z=cpml.psi.V_z;
float * __restrict__ b_V_x=cpml.b.V_x;
float * __restrict__ b_V_z=cpml.b.V_z;
float * __restrict__ c_V_x=cpml.c.V_x;
float * __restrict__ c_V_z=cpml.c.V_z;
float * __restrict__ k_V_x=cpml.k.V_x;
float * __restrict__ k_V_z=cpml.k.V_z;
ord=ORD8;
for(int iz=0;iz<nz;iz++){
for(int ix=0;ix<nx;ix++){
int in_idx=ix+iz*nx;
int ord=ix;
ord=min(ord,nx-1-ix);
ord=min(ord,nz-1-iz);
ord=min(ord,ORD8);
float MUX_ix_iz= MUX[in_idx];
float MUZ_ix_iz= MUZ[in_idx];
DxV;
DzV;
if(ix<npml){
//left pml
idx=ix+iz*2*npml;
psi_V_x[idx] = b_V_x[ix] * psi_V_x[idx] + c_V_x[ix] * dxV;
Tx[in_idx] += MUX_ix_iz*( dxV * k_V_x[ix] + psi_V_x[idx] );
}else if(ix>=nx-npml){
//right pml
idx=npml+nx-1-ix+iz*2*npml;
psi_V_x[idx] = b_V_x[ix] * psi_V_x[idx] + c_V_x[ix] * dxV;
Tx[in_idx] += MUX_ix_iz*( dxV * k_V_x[ix] + psi_V_x[idx] );
}else{
Tx[in_idx] += MUX_ix_iz*( dxV );
}
if(iz<npml && topabsorb){
//top pml
idx=(iz*nx)+ix;
psi_V_z[idx] = b_V_z[iz] * psi_V_z[idx] + c_V_z[iz] * dzV;
Tz[in_idx] += MUZ_ix_iz*( dzV * k_V_z[iz] + psi_V_z[idx] ) ;
}else if(iz>=nz-npml){
// bottom
idx=(npml+nz-1-iz)*nx+ix;
psi_V_z[idx] = b_V_z[iz] * psi_V_z[idx] + c_V_z[iz] * dzV;
Tz[in_idx] += MUZ_ix_iz*( dzV * k_V_z[iz] + psi_V_z[idx] ) ;
}else{
Tz[in_idx] += MUZ_ix_iz*( dzV );
}
}
}
}
void step_velocity(FIELD & fld,MATERIAL & mat,CPML & cpml)
{
int ord,idx;
float Tx_x,Tz_z;
int nx=fld.nx;
int nz=fld.nz;
int npml=cpml.npml;
float * __restrict__ Tx=fld.Tx;
float * __restrict__ Tz=fld.Tz;
float * __restrict__ V=fld.V;
float * __restrict__ BV=mat.BV;
float * __restrict__ psi_Tx_x=cpml.psi.Tx_x;
float * __restrict__ psi_Tz_z=cpml.psi.Tz_z;
float * __restrict__ b_Tx_x=cpml.b.Tx_x;
float * __restrict__ b_Tz_z=cpml.b.Tz_z;
float * __restrict__ c_Tx_x=cpml.c.Tx_x;
float * __restrict__ c_Tz_z=cpml.c.Tz_z;
float * __restrict__ k_Tx_x=cpml.k.Tx_x;
float * __restrict__ k_Tz_z=cpml.k.Tz_z;
for(int i=0;i<nx;i++){
/* stress imaging */
Tz[i]=-Tz[i+nx];
}
ord=ORD8;
for(int iz=0;iz<nz;iz++){
for(int ix=0;ix<nx;ix++){
int in_idx=ix+iz*nx;
float BV_ix_iz= mat.BV[in_idx];
ord=ix; // maybe top layer can also use 8th ,this reduce dispersion
ord=min(ord,nx-1-ix);
ord=min(ord,nz-1-iz);
ord=min(ord,ORD8);
TxDIFF;
TzDIFF;
if(ix<npml){
//left pml
idx=ix+iz*2*npml;
psi_Tx_x[idx] = b_Tx_x[ix] * psi_Tx_x[idx] + c_Tx_x[ix] * Tx_x;
V[in_idx] += BV_ix_iz*( Tx_x * k_Tx_x[ix] + psi_Tx_x[idx] );
}else if(ix>=nx-npml){
//right pml
idx=npml+nx-1-ix+iz*2*npml;
psi_Tx_x[idx] = b_Tx_x[ix] * psi_Tx_x[idx] + c_Tx_x[ix] * Tx_x;
V[in_idx] += BV_ix_iz*( Tx_x * k_Tx_x[ix] + psi_Tx_x[idx] );
}else{
V[in_idx] += BV_ix_iz*( Tx_x );
}
if(iz<npml && topabsorb){
//top pml
idx=(iz*nx)+ix;
psi_Tz_z[idx] = b_Tz_z[iz] * psi_Tz_z[idx] + c_Tz_z[iz] * Tz_z;
V[in_idx] += BV_ix_iz*(Tz_z * k_Tz_z[iz] + psi_Tz_z[idx] );
}else if(iz>=nz-npml){
// bottom
idx=(npml+nz-1-iz)*nx+ix;
psi_Tz_z[idx] = b_Tz_z[iz] * psi_Tz_z[idx] + c_Tz_z[iz] * Tz_z;
V[in_idx] += BV_ix_iz*(Tz_z * k_Tz_z[iz] + psi_Tz_z[idx] );
}else{
V[in_idx] += BV_ix_iz*(Tz_z);
}
}
}
}
| [
"[email protected]"
] | |
c0209d9dadd38ccf58241b1e35c5fc96a2d915d6 | 647f2a81d22bbb498563eaac09d0498fe10d4f27 | /kratos/geometries/sphere_3d_1.h | 3acfd993bd2c6c41d8d50d45bd7294a8b37a8212 | [
"BSD-3-Clause"
] | permissive | pinebai/MyKratos7.0 | 8b87579cc0b61b8d0f5194f881d747ce4fe41e7e | e977752722e8ef1b606f25618c4bf8fd04c434cc | refs/heads/master | 2022-05-21T19:01:40.496529 | 2020-04-28T14:27:43 | 2020-04-28T14:27:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,480 | h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Riccardo Rossi
// Janosch Stascheit
// Felix Nagel
// contributors: Hoang Giang Bui
// Josep Maria Carbonell
//
#if !defined(KRATOS_SPHERE_3D_1_H_INCLUDED )
#define KRATOS_SPHERE_3D_1_H_INCLUDED
// System includes
// External includes
// Project includes
#include "geometries/geometry.h"
#include "integration/line_gauss_legendre_integration_points.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
*/
template<class TPointType>
class Sphere3D1 : public Geometry<TPointType>
{
public:
///@}
///@name Type Definitions
///@{
/// Geometry as base class.
typedef Geometry<TPointType> BaseType;
/// Pointer definition of Sphere3D1
KRATOS_CLASS_POINTER_DEFINITION( Sphere3D1 );
/** Integration methods implemented in geometry.
*/
typedef GeometryData::IntegrationMethod IntegrationMethod;
/** A Vector of counted pointers to Geometries. Used for
returning edges of the geometry.
*/
typedef typename BaseType::GeometriesArrayType GeometriesArrayType;
/** Redefinition of template parameter TPointType.
*/
typedef TPointType PointType;
/** Type used for indexing in geometry class.std::size_t used for indexing
point or integration point access methods and also all other
methods which need point or integration point index.
*/
typedef typename BaseType::IndexType IndexType;
/** This typed used to return size or dimension in
geometry. Dimension, WorkingDimension, PointsNumber and
... return this type as their results.
*/
typedef typename BaseType::SizeType SizeType;
/** Array of counted pointers to point. This type used to hold
geometry's points.
*/
typedef typename BaseType::PointsArrayType PointsArrayType;
/** This type used for representing an integration point in
geometry. This integration point is a point with an
additional weight component.
*/
typedef typename BaseType::IntegrationPointType IntegrationPointType;
/** A Vector of IntegrationPointType which used to hold
integration points related to an integration
method. IntegrationPoints functions used this type to return
their results.
*/
typedef typename BaseType::IntegrationPointsArrayType IntegrationPointsArrayType;
/** A Vector of IntegrationPointsArrayType which used to hold
integration points related to different integration method
implemented in geometry.
*/
typedef typename BaseType::IntegrationPointsContainerType IntegrationPointsContainerType;
/** A third order tensor used as shape functions' values
continer.
*/
typedef typename BaseType::ShapeFunctionsValuesContainerType ShapeFunctionsValuesContainerType;
/** A fourth order tensor used as shape functions' local
gradients container in geometry.
*/
typedef typename BaseType::ShapeFunctionsLocalGradientsContainerType ShapeFunctionsLocalGradientsContainerType;
/** A third order tensor to hold jacobian matrices evaluated at
integration points. Jacobian and InverseOfJacobian functions
return this type as their result.
*/
typedef typename BaseType::JacobiansType JacobiansType;
/** A third order tensor to hold shape functions' local
gradients. ShapefunctionsLocalGradients function return this
type as its result.
*/
typedef typename BaseType::ShapeFunctionsGradientsType ShapeFunctionsGradientsType;
/** Type of the normal vector used for normal to edges in geomety.
*/
typedef typename BaseType::NormalType NormalType;
/**
* Type of coordinates array
*/
typedef typename BaseType::CoordinatesArrayType CoordinatesArrayType;
///@}
///@name Life Cycle
///@{
// Sphere3D1( const PointType& FirstPoint)
// : BaseType( PointsArrayType(), &msGeometryData )
// {
// BaseType::Points().push_back( typename PointType::Pointer( new PointType( FirstPoint ) ) );
// }
Sphere3D1( typename PointType::Pointer pFirstPoint )
: BaseType( PointsArrayType(), &msGeometryData )
{
BaseType::Points().push_back( pFirstPoint );
}
Sphere3D1( const PointsArrayType& ThisPoints )
: BaseType( ThisPoints, &msGeometryData )
{
if ( BaseType::PointsNumber() != 1 )
KRATOS_ERROR << "Invalid points number. Expected 1, given " << BaseType::PointsNumber() << std::endl;
}
/** Copy constructor.
Construct this geometry as a copy of given geometry.
@note This copy constructor don't copy the points and new
geometry shares points with given source geometry. It's
obvious that any change to this new geometry's point affect
source geometry's points too.
*/
Sphere3D1( Sphere3D1 const& rOther )
: BaseType( rOther )
{
}
/** Copy constructor from a geometry with other point type.
Construct this geometry as a copy of given geometry which
has different type of points. The given goemetry's
TOtherPointType* must be implicity convertible to this
geometry PointType.
@note This copy constructor don't copy the points and new
geometry shares points with given source geometry. It's
obvious that any change to this new geometry's point affect
source geometry's points too.
*/
template<class TOtherPointType> Sphere3D1( Sphere3D1<TOtherPointType> const& rOther )
: BaseType( rOther )
{
}
/// Destructor. Do nothing!!!
~Sphere3D1() override {}
GeometryData::KratosGeometryFamily GetGeometryFamily() const override
{
return GeometryData::Kratos_Point;
}
GeometryData::KratosGeometryType GetGeometryType() const override
{
return GeometryData::Kratos_Sphere3D1;
}
///@}
///@name Operators
///@{
/** Assignment operator.
@note This operator don't copy the points and this
geometry shares points with given source geometry. It's
obvious that any change to this geometry's point affect
source geometry's points too.
@see Clone
@see ClonePoints
*/
Sphere3D1& operator=( const Sphere3D1& rOther )
{
BaseType::operator=( rOther );
return *this;
}
/** Assignment operator for geometries with different point type.
@note This operator don't copy the points and this
geometry shares points with given source geometry. It's
obvious that any change to this geometry's point affect
source geometry's points too.
@see Clone
@see ClonePoints
*/
template<class TOtherPointType>
Sphere3D1& operator=( Sphere3D1<TOtherPointType> const & rOther )
{
BaseType::operator=( rOther );
return *this;
}
///@}
///@name Operations
///@{
typename BaseType::Pointer Create( PointsArrayType const& ThisPoints ) const override
{
return typename BaseType::Pointer( new Sphere3D1( ThisPoints ) );
}
// Geometry< Point<3> >::Pointer Clone() const override
// {
// Geometry< Point<3> >::PointsArrayType NewPoints;
// //making a copy of the nodes TO POINTS (not Nodes!!!)
// for ( IndexType i = 0 ; i < this->size() ; i++ )
// {
// NewPoints.push_back(Kratos::make_shared< Point<3> >(( *this )[i]));
// }
// //creating a geometry with the new points
// Geometry< Point<3> >::Pointer p_clone( new Sphere3D1< Point<3> >( NewPoints ) );
// return p_clone;
// }
/**
* @brief Lumping factors for the calculation of the lumped mass matrix
* @param rResult Vector containing the lumping factors
* @param LumpingMethod The lumping method considered. The three methods available are:
* - The row sum method
* - Diagonal scaling
* - Evaluation of M using a quadrature involving only the nodal points and thus automatically yielding a diagonal matrix for standard element shape function
*/
Vector& LumpingFactors(
Vector& rResult,
const typename BaseType::LumpingMethods LumpingMethod = BaseType::LumpingMethods::ROW_SUM
) const override
{
if(rResult.size() != 1)
rResult.resize( 1, false );
rResult[0] = 1.0;
return rResult;
}
///@}
///@name Informations
///@{
/** This method calculate and return Length or charactereistic
length of this geometry depending to it's dimension. For one
dimensional geometry for example Line it returns length of it
and for the other geometries it gives Characteristic length
otherwise.
@return double value contains length or Characteristic
length
@see Area()
@see Volume()
@see DomainSize()
*/
double Length() const override
{
std::cout<<"This method (Length) has no meaning for this type of geometry (Sphere)."<<std::endl;
return 0.0;
}
/** This method calculate and return area or surface area of
this geometry depending to it's dimension. For one dimensional
geometry it returns zero, for two dimensional it gives area
and for three dimensional geometries it gives surface area.
@return double value contains area or surface
area.
@see Length()
@see Volume()
@see DomainSize()
*/
double Area() const override
{
std::cout<<"This method (Area) has no meaning for this type of geometry (Sphere)."<<std::endl;
return 0.00;
}
/** This method calculate and return length, area or volume of
this geometry depending to it's dimension. For one dimensional
geometry it returns its length, for two dimensional it gives area
and for three dimensional geometries it gives its volume.
@return double value contains length, area or volume.
@see Length()
@see Area()
@see Volume()
*/
double DomainSize() const override
{
std::cout<<"This method (DomainSize) has no meaning for this type of geometry (Sphere)."<<std::endl;
return 0.0;
}
// virtual void Bounding_Box(BoundingBox<TPointType, BaseType>& rResult) const
// {
// //rResult.Geometry() = *(this);
// BaseType::Bounding_Box(rResult.LowPoint(), rResult.HighPoint());
// }
///@}
///@name Jacobian
///@{
/** Jacobians for given method. This method
calculate jacobians matrices in all integrations points of
given integration method.
@param ThisMethod integration method which jacobians has to
be calculated in its integration points.
@return JacobiansType a Vector of jacobian
matrices \f$ J_i \f$ where \f$ i=1,2,...,n \f$ is the integration
point index of given integration method.
@see DeterminantOfJacobian
@see InverseOfJacobian
*/
JacobiansType& Jacobian( JacobiansType& rResult, IntegrationMethod ThisMethod ) const override
{
std::cout<<"This method (Jacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** Jacobians for given method. This method
calculate jacobians matrices in all integrations points of
given integration method.
@param ThisMethod integration method which jacobians has to
be calculated in its integration points.
@return JacobiansType a Vector of jacobian
matrices \f$ J_i \f$ where \f$ i=1,2,...,n \f$ is the integration
point index of given integration method.
@param DeltaPosition Matrix with the nodes position increment which describes
the configuration where the jacobian has to be calculated.
@see DeterminantOfJacobian
@see InverseOfJacobian
*/
JacobiansType& Jacobian( JacobiansType& rResult, IntegrationMethod ThisMethod, Matrix & DeltaPosition ) const override
{
std::cout<<"This method (Jacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** Jacobian in specific integration point of given integration
method. This method calculate jacobian matrix in given
integration point of given integration method.
@param IntegrationPointIndex index of integration point which jacobians has to
be calculated in it.
@param ThisMethod integration method which jacobians has to
be calculated in its integration points.
@return Matrix<double> Jacobian matrix \f$ J_i \f$ where \f$
i \f$ is the given integration point index of given
integration method.
@see DeterminantOfJacobian
@see InverseOfJacobian
*/
Matrix& Jacobian( Matrix& rResult, IndexType IntegrationPointIndex, IntegrationMethod ThisMethod ) const override
{
std::cout<<"This method (Jacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** Jacobian in given point. This method calculate jacobian
matrix in given point.
@param rPoint point which jacobians has to
be calculated in it.
@return Matrix of double which is jacobian matrix \f$ J \f$ in given point.
@see DeterminantOfJacobian
@see InverseOfJacobian
*/
Matrix& Jacobian( Matrix& rResult, const CoordinatesArrayType& rPoint ) const override
{
std::cout<<"This method (Jacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** Determinant of jacobians for given integration method. This
method calculate determinant of jacobian in all
integrations points of given integration method.
@return Vector of double which is vector of determinants of
jacobians \f$ |J|_i \f$ where \f$ i=1,2,...,n \f$ is the
integration point index of given integration method.
@see Jacobian
@see InverseOfJacobian
*/
Vector& DeterminantOfJacobian( Vector& rResult, IntegrationMethod ThisMethod ) const override
{
std::cout<<"This method (DeterminantOfJacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** Determinant of jacobian in specific integration point of
given integration method. This method calculate determinant
of jacobian in given integration point of given integration
method.
@param IntegrationPointIndex index of integration point which jacobians has to
be calculated in it.
@param IntegrationPointIndex index of integration point
which determinant of jacobians has to be calculated in it.
@return Determinamt of jacobian matrix \f$ |J|_i \f$ where \f$
i \f$ is the given integration point index of given
integration method.
@see Jacobian
@see InverseOfJacobian
*/
double DeterminantOfJacobian( IndexType IntegrationPointIndex, IntegrationMethod ThisMethod ) const override
{
std::cout<<"This method (DeterminantOfJacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return 0.0;
}
/** Determinant of jacobian in given point. This method calculate determinant of jacobian
matrix in given point.
@param rPoint point which determinant of jacobians has to
be calculated in it.
@return Determinamt of jacobian matrix \f$ |J| \f$ in given
point.
@see DeterminantOfJacobian
@see InverseOfJacobian
*/
double DeterminantOfJacobian( const CoordinatesArrayType& rPoint ) const override
{
std::cout<<"This method (DeterminantOfJacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return 0.0;
}
/** Inverse of jacobians for given integration method. This method
calculate inverse of jacobians matrices in all integrations points of
given integration method.
@param ThisMethod integration method which inverse of jacobians has to
be calculated in its integration points.
@return Inverse of jacobian
matrices \f$ J^{-1}_i \f$ where \f$ i=1,2,...,n \f$ is the integration
point index of given integration method.
@see Jacobian
@see DeterminantOfJacobian
*/
JacobiansType& InverseOfJacobian( JacobiansType& rResult, IntegrationMethod ThisMethod ) const override
{
std::cout<<"This method (InverseOfJacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** Inverse of jacobian in specific integration point of given integration
method. This method calculate Inverse of jacobian matrix in given
integration point of given integration method.
@param IntegrationPointIndex index of integration point which inverse of jacobians has to
be calculated in it.
@param ThisMethod integration method which inverse of jacobians has to
be calculated in its integration points.
@return Inverse of jacobian matrix \f$ J^{-1}_i \f$ where \f$
i \f$ is the given integration point index of given
integration method.
@see Jacobian
@see DeterminantOfJacobian
*/
Matrix& InverseOfJacobian( Matrix& rResult, IndexType IntegrationPointIndex, IntegrationMethod ThisMethod ) const override
{
std::cout<<"This method (InverseOfJacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** Inverse of jacobian in given point. This method calculate inverse of jacobian
matrix in given point.
@param rPoint point which inverse of jacobians has to
be calculated in it.
@return Inverse of jacobian matrix \f$ J^{-1} \f$ in given point.
@see DeterminantOfJacobian
@see InverseOfJacobian
*/
Matrix& InverseOfJacobian( Matrix& rResult, const CoordinatesArrayType& rPoint ) const override
{
std::cout<<"This method (InverseOfJacobian) has no meaning for this type of geometry (Sphere)."<<std::endl;
return rResult;
}
/** EdgesNumber
@return SizeType containes number of this geometry edges.
*/
SizeType EdgesNumber() const override
{
return 1;
}
///@}
///@name Shape Function
///@{
double ShapeFunctionValue( IndexType ShapeFunctionIndex,
const CoordinatesArrayType& rPoint ) const override
{
std::cout<<"This method (ShapeFunctionValue) has no meaning for this type of geometry (Sphere)."<<std::endl;
return 0;
}
Matrix& ShapeFunctionsLocalGradients( Matrix& rResult,
const CoordinatesArrayType& rPoint ) const override
{
std::cout<<"This method (ShapeFunctionsLocalGradients) has no meaning for this type of geometry (Sphere)."<<std::endl;
return( rResult );
}
ShapeFunctionsGradientsType& ShapeFunctionsIntegrationPointsGradients( ShapeFunctionsGradientsType& rResult, IntegrationMethod ThisMethod ) const override
{
std::cout<<"This method (ShapeFunctionsLocalGradients) has no meaning for this type of geometry (Sphere)."<<std::endl;
return( rResult );
}
/** Turn back information as a string.
@return String contains information about this geometry.
@see PrintData()
@see PrintInfo()
*/
std::string Info() const override
{
return "a sphere with 1 nodes in its center, in 3D space";
}
/** Print information about this object.
@param rOStream Stream to print into it.
@see PrintData()
@see Info()
*/
void PrintInfo( std::ostream& rOStream ) const override
{
rOStream << "a sphere with 1 nodes in its center, in 3D space";
}
/** Print geometry's data into given stream. Prints it's points
by the order they stored in the geometry and then center
point of geometry.
@param rOStream Stream to print into it.
@see PrintInfo()
@see Info()
*/
void PrintData( std::ostream& rOStream ) const override
{
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
static const GeometryData msGeometryData;
///@}
///@name Member Variables
///@{
///@}
///@name Serialization
///@{
friend class Serializer;
void save( Serializer& rSerializer ) const override
{
KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, BaseType );
}
void load( Serializer& rSerializer ) override
{
KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, BaseType );
}
Sphere3D1(): BaseType( PointsArrayType(), &msGeometryData ) {}
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
static Matrix CalculateShapeFunctionsIntegrationPointsValues( typename BaseType::IntegrationMethod ThisMethod )
{
const IntegrationPointsContainerType& all_integration_points = AllIntegrationPoints();
const IntegrationPointsArrayType& IntegrationPoints = all_integration_points[ThisMethod];
const int integration_points_number = IntegrationPoints.size();
Matrix N( integration_points_number, 1 );
//std::cout<<"This method (CalculateShapeFunctionsIntegrationPointsValues) has no meaning for this type of geometry (Sphere)."<<std::endl;
return N;
}
static ShapeFunctionsGradientsType CalculateShapeFunctionsIntegrationPointsLocalGradients( typename BaseType::IntegrationMethod ThisMethod )
{
const IntegrationPointsContainerType& all_integration_points = AllIntegrationPoints();
const IntegrationPointsArrayType& IntegrationPoints = all_integration_points[ThisMethod];
ShapeFunctionsGradientsType DN_De( IntegrationPoints.size() );
std::fill( DN_De.begin(), DN_De.end(), Matrix( 2, 1 ) );
//std::cout<<"This method (CalculateShapeFunctionsIntegrationPointsLocalGradients) has no meaning for this type of geometry (Sphere)."<<std::endl;
return DN_De;
}
static const IntegrationPointsContainerType AllIntegrationPoints()
{
IntegrationPointsContainerType integration_points = {{
Quadrature<LineGaussLegendreIntegrationPoints1, 1, IntegrationPoint<3> >::GenerateIntegrationPoints(),
Quadrature<LineGaussLegendreIntegrationPoints2, 1, IntegrationPoint<3> >::GenerateIntegrationPoints(),
Quadrature<LineGaussLegendreIntegrationPoints3, 1, IntegrationPoint<3> >::GenerateIntegrationPoints(),
Quadrature<LineGaussLegendreIntegrationPoints4, 1, IntegrationPoint<3> >::GenerateIntegrationPoints(),
Quadrature<LineGaussLegendreIntegrationPoints5, 1, IntegrationPoint<3> >::GenerateIntegrationPoints()
}
};
return integration_points;
}
static const ShapeFunctionsValuesContainerType AllShapeFunctionsValues()
{
ShapeFunctionsValuesContainerType shape_functions_values = {{
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsValues( GeometryData::GI_GAUSS_1 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsValues( GeometryData::GI_GAUSS_2 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsValues( GeometryData::GI_GAUSS_3 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsValues( GeometryData::GI_GAUSS_4 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsValues( GeometryData::GI_GAUSS_5 )
}
};
return shape_functions_values;
}
static const ShapeFunctionsLocalGradientsContainerType AllShapeFunctionsLocalGradients()
{
ShapeFunctionsLocalGradientsContainerType shape_functions_local_gradients = {{
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsLocalGradients( GeometryData::GI_GAUSS_1 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsLocalGradients( GeometryData::GI_GAUSS_2 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsLocalGradients( GeometryData::GI_GAUSS_3 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsLocalGradients( GeometryData::GI_GAUSS_4 ),
Sphere3D1<TPointType>::CalculateShapeFunctionsIntegrationPointsLocalGradients( GeometryData::GI_GAUSS_5 ),
}
};
return shape_functions_local_gradients;
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Private Friends
///@{
template<class TOtherPointType> friend class Sphere3D1;
///@}
///@name Un accessible methods
///@{
///@}
}; // Class Geometry
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
/// input stream function
template<class TPointType>
inline std::istream& operator >> ( std::istream& rIStream,
Sphere3D1<TPointType>& rThis );
/// output stream function
template<class TPointType>
inline std::ostream& operator << ( std::ostream& rOStream,
const Sphere3D1<TPointType>& rThis )
{
rThis.PrintInfo( rOStream );
rOStream << std::endl;
rThis.PrintData( rOStream );
return rOStream;
}
template<class TPointType>
const GeometryData Sphere3D1<TPointType>::msGeometryData( 3,
3,
1,
GeometryData::GI_GAUSS_1,
Sphere3D1<TPointType>::AllIntegrationPoints(),
Sphere3D1<TPointType>::AllShapeFunctionsValues(),
AllShapeFunctionsLocalGradients() );
} // namespace Kratos.
#endif // KRATOS_SPHERE_3D_1_H_INCLUDED defined
| [
"[email protected]"
] | |
3ab409e44519b8b90357ac10a33f9b3f0b96217a | 530bf81293952d3c1cccbdfab746737797d6d378 | /test/amigo.cpp | 0cb21400eeac743bfdb66cbf3afecdfd9cc31970 | [] | no_license | svddries/mwm | dc71704100f391932f725a8298e40e34e09885f1 | 51cce806fa957aea5058c4c24bdaf04e9da65ddd | refs/heads/master | 2021-01-10T03:13:29.179346 | 2015-12-08T10:56:24 | 2015-12-08T10:56:24 | 47,267,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,692 | cpp | #include <mwm/ros/image_buffer.h>
#include <opencv2/highgui/highgui.hpp>
#include <rgbd/Image.h>
#include <rgbd/View.h>
#include <ros/init.h>
#include <mwm/world_model.h>
#include <mwm/rendering.h>
#include <mwm/projection_matrix.h>
#include <mwm/visualization/viewer.h>
#include "timer.h"
// ----------------------------------------------------------------------------------------------------
struct Image
{
cv::Mat depth;
cv::Mat rgb;
mwm::ProjectionMatrix P;
geo::Pose3D pose;
};
// ----------------------------------------------------------------------------------------------------
void updateTriangles(mwm::WorldModel& wm, const Image& image)
{
int width = image.depth.cols;
int height = image.depth.rows;
int step = 10;
// - - - - - - - - - - - - - - - - - - - - - - - - - -
cv::Mat vertex_map(height / step, width / step, CV_32SC1, cv::Scalar(-1));
cv::Mat vertex_map_z(height / step, width / step, CV_32FC1, 0.0);
geo::Pose3D sensor_pose_inv = image.pose.inverse();
const std::vector<geo::Vec3>& vertices = wm.vertices();
for(unsigned int i = 0; i < vertices.size(); ++i)
{
const geo::Vec3& p = vertices[i];
geo::Vec3 p_sensor = sensor_pose_inv * p;
float vz = -p_sensor.z;
if (vz < 0) // Filter vertices that are behind the camera
continue;
geo::Vec2i p_2d = image.P.project3Dto2D(p_sensor);
if (p_2d.x < 0 || p_2d.y < 0 || p_2d.x >= width || p_2d.y >= height)
continue;
int vx = p_2d.x / step;
int vy = p_2d.y / step;
int vi = vertex_map.at<int>(vy, vx);
if (vi <= 0 || vertex_map_z.at<float>(vy, vx) < vz)
{
vertex_map.at<int>(p_2d.y / step, p_2d.x / step) = i;
vertex_map_z.at<float>(p_2d.y / step, p_2d.x / step) = -p_sensor.z;
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - -
// Add missing vertices
cv::Mat vertex_map_new(height / step, width / step, CV_8UC1, cv::Scalar(0));
for(int y = 0; y < vertex_map.rows - 1; ++y)
{
for(int x = 0; x < vertex_map.cols - 1; ++x)
{
int ix = step * (x + 0.5);
int iy = step * (y + 0.5);
float d = image.depth.at<float>(iy, ix);
if (d != d || d <= 0.5 || d > 5)
continue;
int i = vertex_map.at<int>(y, x);
if (i >= 0 && std::abs(vertex_map_z.at<float>(y, x) - d) < 0.2)
continue;
geo::Vec3 p_sensor = image.P.project2Dto3D(ix, iy) * d;
geo::Vec3 p = image.pose * p_sensor;
vertex_map.at<int>(y, x) = wm.addVertex(p);
vertex_map_z.at<float>(y, x) = d;
vertex_map_new.at<unsigned char>(y, x) = 1;
}
}
// cv::imshow("vertices", vertex_map_z / 10);
// cv::imshow("vertices_new", vertex_map_new * 255);
// cv::waitKey(3);
// - - - - - - - - - - - - - - - - - - - - - - - - - -
float d_thr = 0.2;
for(int y = 0; y < vertex_map.rows - 1; ++y)
{
for(int x = 0; x < vertex_map.cols - 1; ++x)
{
// int ix = (0.5 + step) * x;
// int iy = (0.5 + step) * y;
// float d = depth_image.at<float>(iy, ix);
// if (d != d || d == 0)
// continue;
int i1 = vertex_map.at<int>(y, x);
int i2 = vertex_map.at<int>(y, x + 1);
int i3 = vertex_map.at<int>(y + 1, x);
int i4 = vertex_map.at<int>(y + 1, x + 1);
float z1 = vertex_map_z.at<float>(y, x);
float z2 = vertex_map_z.at<float>(y, x + 1);
float z3 = vertex_map_z.at<float>(y + 1, x);
float z4 = vertex_map_z.at<float>(y + 1, x + 1);
float z1z2 = std::abs(z1 - z2);
float z1z3 = std::abs(z1 - z3);
float z2z3 = std::abs(z2 - z3);
float z2z4 = std::abs(z2 - z4);
float z3z4 = std::abs(z3 - z4);
bool is_new1 = (vertex_map_new.at<unsigned char>(y, x) == 1);
bool is_new2 = (vertex_map_new.at<unsigned char>(y, x) == 1);
bool is_new3 = (vertex_map_new.at<unsigned char>(y, x) == 1);
bool is_new4 = (vertex_map_new.at<unsigned char>(y, x) == 1);
if (i1 >= 0 && i2 >= 0 && i3 >= 0 && (is_new1 || is_new2 || is_new3)
&& z1z2 < d_thr && z1z3 < d_thr && z2z3 < d_thr)
{
float f = (float)image.rgb.cols / vertex_map.cols;
int x_rgb = f * x;
int y_rgb = f * y;
cv::Vec3b clr = image.rgb.at<cv::Vec3b>(y_rgb, x_rgb);
wm.addTriangle(i2, i1, i3, clr);
}
if (i2 >= 0 && i3 >= 0 && i4 >= 0 && (is_new2 || is_new3 || is_new4)
&& z2z4 < d_thr && z3z4 < d_thr && z2z3 < d_thr)
{
float f = (float)image.rgb.cols / vertex_map.cols;
int x_rgb = f * x;
int y_rgb = f * y;
cv::Vec3b clr = image.rgb.at<cv::Vec3b>(y_rgb, x_rgb);
wm.addTriangle(i2, i3, i4, clr);
}
}
}
}
// ----------------------------------------------------------------------------------------------------
void update(mwm::WorldModel& wm, const Image& image)
{
int width = image.depth.cols;
int height = image.depth.rows;
// cv::Mat depth = image.depth.clone();
// - - - - - - - - - - - - - - - - - - - - - - - - - -
geo::Pose3D sensor_pose_inv = image.pose.inverse();
geo::Vec3 Rx = sensor_pose_inv.R.getRow(0);
geo::Vec3 Ry = sensor_pose_inv.R.getRow(1);
geo::Vec3 Rz = sensor_pose_inv.R.getRow(2);
int step = 10;
double depth_res = 0.1;
double z_min = 0.5;
double z_max = 5;
cv::Mat vertex_map_z_min(image.depth.rows / step, image.depth.cols / step, CV_32FC1, 0.0);
const std::vector<geo::Vec3>& points = wm.points();
for(unsigned int i = 0; i < points.size(); ++i)
{
const geo::Vec3& p_world = points[i];
geo::Vec3 p_sensor;
p_sensor.z = Rz.dot(p_world) + sensor_pose_inv.t.z;
float vz = -p_sensor.z;
if (vz < z_min || vz > z_max) // Filter vertices that are behind the camera
continue;
p_sensor.x = Rx.dot(p_world) + sensor_pose_inv.t.x;
p_sensor.y = Ry.dot(p_world) + sensor_pose_inv.t.y;
int p_2d_x = image.P.project3Dto2DX(p_sensor);
if (p_2d_x < 0 || p_2d_x >= width)
continue;
int p_2d_y = image.P.project3Dto2DY(p_sensor);
if (p_2d_y < 0 || p_2d_y >= height)
continue;
float z = image.depth.at<float>(p_2d_y, p_2d_x);
if (z == z && z > 0)
{
if (vz < z - 0.1)
{
// Remove vertex
}
else
{
if (vz < z + 0.1)
{
// Update vertex
// float vz_new = vz;//(0.1 * z + 0.9 * vz);
// geo::Vec3 p_new = image.P.project2Dto3D(p_2d_x, p_2d_y) * vz_new;
// wm.setPoint(i, image.pose * p_new);
}
// else vertex is occluded
int vmx = p_2d_x / step;
int vmy = p_2d_y / step;
float& vz_old = vertex_map_z_min.at<float>(vmy, vmx);
if (vz_old == 0 || vz < vz_old)
vz_old = vz;
}
}
}
// cv::imshow("vertex_map_z_min", vertex_map_z_min / 10);
// cv::waitKey(3);
// - - - - - - - - - - - - - - - - - - - - - - - - - -
// Add missing vertices
float f = (float)image.rgb.cols / image.depth.cols;
for(int y = step / 2; y < image.depth.rows; y += step)
{
for(int x = step / 2; x < image.depth.cols; x += step)
{
float z = image.depth.at<float>(y, x);
if (z < z_min || z > z_max || z != z)
continue;
int vmx = x / step;
int vmy = y / step;
float vmz = vertex_map_z_min.at<float>(vmy, vmx);
// std::cout << vmx << ", " << vmy << ": " << vmz << std::endl;
if (vmz > 0 && z > vmz - 0.1)
continue;
geo::Vec3 p_sensor = image.P.project2Dto3D(x, y) * z;
geo::Vec3 p = image.pose * p_sensor;
int x_rgb = f * x;
int y_rgb = f * y;
cv::Vec3b color = image.rgb.at<cv::Vec3b>(y_rgb, x_rgb);
wm.addPoint(p, color, 1);
}
}
}
// ----------------------------------------------------------------------------------------------------
int main(int argc, char **argv)
{
ros::init(argc, argv, "mwm_test_amigo");
mwm::ImageBuffer image_buffer;
image_buffer.initialize("/amigo/top_kinect/rgbd");
mwm::Viewer viewer("world model", 640, 480);
mwm::WorldModel wm;
while(ros::ok())
{
geo::Pose3D sensor_pose;
rgbd::ImageConstPtr rgbd_image;
if (!image_buffer.waitForRecentImage("/amigo/odom", rgbd_image, sensor_pose, 1.0))
continue;
Image image;
image.pose = sensor_pose;
image.depth = rgbd_image->getDepthImage();
image.rgb = rgbd_image->getRGBImage();
rgbd::View view(*rgbd_image, image.depth.cols);
const geo::DepthCamera& cam_model = view.getRasterizer();
image.P.setFocalLengths(cam_model.getFocalLengthX(), cam_model.getFocalLengthY());
image.P.setOpticalCenter(cam_model.getOpticalCenterX(), cam_model.getOpticalCenterY());
image.P.setOpticalTranslation(cam_model.getOpticalTranslationX(), cam_model.getOpticalTranslationY());
std::cout << "-----------------" << std::endl;
Timer timer;
updateTriangles(wm, image);
std::cout << "Update took " << timer.getElapsedTimeInMilliSec() << " ms" << std::endl;
std::cout << wm.points().size() << " points" << std::endl;
// std::cout << "Num vertices: " << wm.vertices().size() << std::endl;
// std::cout << "Num triangles: " << wm.triangles().size() << std::endl;
// cv::Mat rendered_depth_image(image.depth.rows, image.depth.cols, CV_32FC1, 0.0);
// timer.reset();
// mwm::render::Result res(rendered_depth_image);
// mwm::render::renderDepth(wm, image.P, image.pose, res);
// std::cout << "Rendering took " << timer.getElapsedTimeInMilliSec() << " ms" << std::endl;
viewer.tick(wm);
cv::imshow("depth", image.depth / 10);
// cv::imshow("rendered_depth_image", rendered_depth_image / 10);
cv::waitKey(3);
}
return 0;
}
| [
"[email protected]"
] | |
0e2211936359eceb35ad22aac68c49fc69c8d91a | 7a6938191deb8018f5d7d2a91b2c73e346fd76b7 | /gamepadble632/gamepadble632.ino | 048909b2af57496ccac99aa2a46aebc0c562652e | [] | no_license | rupin/ESPJoystick | 3f14c87d443ae42d22a9c0b4337e690a23b3cba6 | 7b600834e0462e91a5729e4f4fc1d5f5d14b30f1 | refs/heads/master | 2020-05-03T13:53:06.998576 | 2019-05-07T15:41:20 | 2019-05-07T15:41:20 | 178,663,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,832 | ino | //https://github.com/nkolban/esp32-snippets/issues/632
/*Button and Byte Map
Byte 1
LSB A B C X Y Z L1 R1 MSB
*/
#include <Arduino.h>
#include <SparkFunMPU9250-DMP.h>
#include<Math.h>
#define MSB 1
#define LSB 0
MPU9250_DMP imu;
/**
Create a new BLE server.
*/
#include "BLEDevice.h"
#include "BLEServer.h"
#include "BLEUtils.h"
#include "BLE2902.h"
#include "BLEHIDDevice.h"
#define ABUTTON 26
#define BBUTTON 25
#define CBUTTON 32
#define XBUTTON 4
#define YBUTTON 15
#define ZBUTTON 27
#define L1_BUTTON 34
#define R1_BUTTON 35
#define ANALOG_X 36
#define ANALOG_Y 39
#define PULSE_PIN 27
#define PULSE_MIN_DURATION 0
#define PULSE_MAX_DURATION 2048
#define JOYSTICK_ANALOG_MAX 255
#define JOYSTICK_ANALOG_MIN 0
#define UNPRESSED_BUTTON_VALUE 0
#define SAMPLE_COUNT 4 //Must be a power of two
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
uint32_t connectedDelay = millis();
boolean reconnected = false;
boolean userSignalledConnected = false;
uint32_t lastInterruptTime = 0;
uint32_t pulseDuration = 0;
#define BUTTONCOUNT 8
int buttonArray[BUTTONCOUNT] = {R1_BUTTON, L1_BUTTON, ZBUTTON, YBUTTON, XBUTTON, CBUTTON, BBUTTON, ABUTTON };
byte buttonIndex = 0;
static BLEHIDDevice* hid;
BLECharacteristic* device1;
BLECharacteristic* device1o;
boolean device_connected = false;
uint16_t orientationData[6];
const uint8_t reportMap[] = {
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
0x09, 0x04, // USAGE (Joystick)
0xa1, 0x01, // COLLECTION (Application)
0x85, 0x01, // REPORT_ID (1)
0x05, 0x09, // USAGE_PAGE (Button)
0x19, 0x01, // USAGE_MINIMUM (Button 1)
0x29, 0x10, // USAGE_MAXIMUM (Button 16)
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x25, 0x01, // LOGICAL_MAXIMUM (1)
0x95, 0x08, // REPORT_COUNT (16)
0x75, 0x02, // REPORT_SIZE (1)
0x81, 0x02, // INPUT (Data,Var,Abs)
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
0x09, 0x30, // USAGE (X)
0x09, 0x31, // USAGE (Y)
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x26, 0xFF,0x00, // LOGICAL_MAXIMUM (100)
0x75, 0x08, // REPORT_SIZE (8)
0x95, 0x02, // REPORT_COUNT (2)
0x81, 0x02, // INPUT (Data,Var,Abs)
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
0x09, 0x33, // USAGE (RX)
0x09, 0x34, // USAGE (RY)
0x09, 0x35, // USAGE (RZ)
0x15, 0x00, // LOGICAL_MINIMUM (0) //See https://www.microchip.com/forums/m413261.aspx
0x26, 0x01, 0x68,// LOGICAL_MAXIMUM (360) //Sequence of Bytes here (MSB, LSB) should be same sequence in sending data.
0x75, 0x10, // REPORT_SIZE (16)
0x95, 0x03, // REPORT_COUNT (3)
0x81, 0x02, // INPUT (Data,Var,Abs)
0xc0 // END COLLECTION (Application)
};
class MyCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
BLE2902* desc1 = (BLE2902*)device1->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc1->setNotifications(true);
device_connected = true;
}
void onDisconnect(BLEServer* pServer) {
//connected = false;
BLE2902* desc1 = (BLE2902*)device1->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc1->setNotifications(false);
device_connected = false;
userSignalledConnected = false;
}
};
void taskServer() {
BLEDevice::init("ESP32");
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyCallbacks());
hid = new BLEHIDDevice(pServer);
device1 = hid->inputReport(1); // <-- input REPORTID from report map
// device2 = hid->inputReport(2); // <-- input REPORTID from report map
//device2o = hid->outputReport(2); // <-- output REPORTID from report map
std::string name = "ElectronicCats";
hid->manufacturer()->setValue(name);
hid->pnp(0x02, 0x0810, 0xe501, 0x0106);
hid->hidInfo(0x00, 0x02);
hid->reportMap((uint8_t*)reportMap, sizeof(reportMap));
hid->startServices();
BLESecurity *pSecurity = new BLESecurity();
// pSecurity->setKeySize();
pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND);
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->setAppearance(HID_GAMEPAD);
pAdvertising->addServiceUUID(hid->hidService()->getUUID());
pAdvertising->start();
hid->setBatteryLevel(7);
// delay(portMAX_DELAY);
}
void IRAM_ATTR handleInterrupt();
void setup() {
//
Serial.begin(115200);
Serial.println("Starting");
for (buttonIndex = 0; buttonIndex < BUTTONCOUNT; buttonIndex++)
{
pinMode(buttonArray[buttonIndex], INPUT);
}
pinMode(PULSE_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(PULSE_PIN), handleInterrupt, RISING);
// IMU Code
if (imu.begin() != INV_SUCCESS)
{
while (1)
{
Serial.println("Unable to communicate with MPU-9250");
Serial.println("Check connections, and try again.");
Serial.println();
delay(5000);
}
}
imu.dmpBegin(DMP_FEATURE_6X_LP_QUAT | // Enable 6-axis quat
DMP_FEATURE_GYRO_CAL, // Use gyro calibration
100); // Set DMP FIFO rate to 10 Hz
// DMP_FEATURE_LP_QUAT can also be used. It uses the
// accelerometer in low-power mode to estimate quat's.
// DMP_FEATURE_LP_QUAT and 6X_LP_QUAT are mutually exclusive
//xTaskCreate(taskServer, "server", 20000, NULL, 5, NULL);
taskServer();
Serial.println("starting");
}
uint8_t lButtonState;
byte lastButtonState;
byte X_Joystick;
byte Y_Joystick;
uint8_t userSignal;
void loop() {
updateIMUData();
if (!userSignalledConnected) //User has not as yet signalled that pairing is completed on phone
{
userSignal = getButtonState();
if (userSignal != UNPRESSED_BUTTON_VALUE)
{
userSignalledConnected = true;
}
}
if (userSignalledConnected) //Only when the user signals, do we start sending data
{
lButtonState = getButtonState();
X_Joystick = getAnalogChannelValue(ANALOG_X);
Y_Joystick = getAnalogChannelValue(ANALOG_Y);
uint8_t a[] = {lButtonState,
0x00,
X_Joystick,
Y_Joystick,
orientationData[0],
orientationData[1],
orientationData[2],
orientationData[3],
orientationData[4],
orientationData[5]
};
device1->setValue(a, sizeof(a));
device1->notify();
lastButtonState = lButtonState;
//delay(1);
}
delay(1);
}
uint8_t getButtonState()
{
byte buttonState = 0;
byte currentButtonPressed;
for (buttonIndex = 0; buttonIndex < BUTTONCOUNT; buttonIndex++)
{
currentButtonPressed = digitalRead(buttonArray[buttonIndex]);
buttonState = buttonState | currentButtonPressed;
buttonState = buttonState << 1; // Push left by 1 bit
}
buttonState = buttonState >> 1;
return buttonState;
}
byte getAnalogChannelValue(const int analogpin)
{
uint8_t i;
uint32_t joystickValue = 0;
for (i = 0; i < SAMPLE_COUNT; i++)
{
joystickValue = joystickValue + analogRead(analogpin);
}
if (SAMPLE_COUNT == 2)
{
joystickValue = joystickValue >> 1; //shifting by 1 means division by 2
}
if (SAMPLE_COUNT == 4)
{
joystickValue = joystickValue >> 2; //shifting by 2 means division by 4
}
//We have now averaged the value of the joystick which is in range 0-4095(12 bits), we have to bring it in range 0-255(8 bits)
//Hence shift by 4 places
joystickValue = joystickValue >> 4;
return (byte)joystickValue;
}
byte getFrequency()
{
if (millis() - lastInterruptTime > PULSE_MAX_DURATION)
{
return 127;// Midpoint value for a Joystick With full range 0-255
}
else
{
// PULSE_MAX_DURATION is 2048 milliseconds/2.048 seconds. To bring it to range 0-128, we need to shift it by 4 bits.
//This is faster than the map function.
return pulseDuration >> 4;
}
}
void IRAM_ATTR handleInterrupt()
{
portENTER_CRITICAL_ISR(&mux);
pulseDuration = millis() - lastInterruptTime;
lastInterruptTime = millis();
portEXIT_CRITICAL_ISR(&mux);
}
void updateIMUData()
{
// Check for new data in the FIFO
if ( imu.fifoAvailable() )
{
// Use dmpUpdateFifo to update the ax, gx, mx, etc. values
if ( imu.dmpUpdateFifo() == INV_SUCCESS)
{
// computeEulerAngles can be used -- after updating the
// quaternion values -- to estimate roll, pitch, and yaw
imu.computeEulerAngles();
uint16_t pitchData = (uint16_t)imu.pitch;
uint16_t rollData = (uint16_t)imu.roll;
uint16_t yawData = (uint16_t)imu.yaw;
// uint16_t pitchData = 45;
// uint16_t rollData = 35;
// uint16_t yawData = 22;
//Serial.println(pitchData);
orientationData[0] = getByte(pitchData, MSB);
orientationData[1] = getByte(pitchData, LSB);
orientationData[2] = getByte(rollData, MSB);
orientationData[3] = getByte(rollData, LSB);
orientationData[4] = getByte(yawData, MSB);
orientationData[5] = getByte(yawData, LSB);
for (byte i = 0; i < 6; i++)
{
Serial.print(orientationData[i]);
Serial.print("\t");
}
Serial.println();
}
}
}
uint8_t getByte(uint16_t sentData, uint8_t whichByte)
{
uint8_t retVal = 0;
if (whichByte == MSB)
{
retVal = (sentData & 0xFF00) >> 8;
return retVal;
}
if (whichByte == LSB)
{
retVal = sentData & 0x00FF;
return retVal;
}
}
| [
"[email protected]"
] | |
38a52f4196bfd3795fd3e9b4518855dc4d13d8fc | 929f5243e45e76bed48ab9e86b768261286d0458 | /src/qt/addresstablemodel.h | c0ea99ccbcae8968ccddc1e07fae478aea60dd82 | [
"MIT"
] | permissive | quishtv/QUISH | 19ac12bb52edbc8f8db1783c61fd439d43f2465a | 4a48136592a97e726234eda2ff2a48746c12d6eb | refs/heads/master | 2022-05-07T02:36:24.577218 | 2020-02-19T11:22:54 | 2020-02-19T11:22:54 | 241,603,363 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,387 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2019 The PIVX developers
// Copyright (c) 2020 The QUISH developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_ADDRESSTABLEMODEL_H
#define BITCOIN_QT_ADDRESSTABLEMODEL_H
#include <QAbstractTableModel>
#include <QStringList>
class AddressTablePriv;
class WalletModel;
class CWallet;
/**
Qt model of the address book in the core. This allows views to access and modify the address book.
*/
class AddressTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit AddressTableModel(CWallet* wallet, WalletModel* parent = 0);
~AddressTableModel();
enum ColumnIndex {
Label = 0, /**< User specified label */
Address = 1, /**< Bitcoin address */
Date = 2 /**< Address creation date */
};
enum RoleIndex {
TypeRole = Qt::UserRole /**< Type of address (#Send or #Receive) */
};
/** Return status of edit/insert operation */
enum EditStatus {
OK, /**< Everything ok */
NO_CHANGES, /**< No changes were made during edit operation */
INVALID_ADDRESS, /**< Unparseable address */
DUPLICATE_ADDRESS, /**< Address already in address book */
WALLET_UNLOCK_FAILURE, /**< Wallet could not be unlocked to create new receiving address */
KEY_GENERATION_FAILURE /**< Generating a new public key for a receiving address failed */
};
static const QString Send; /**< Specifies send address */
static const QString Receive; /**< Specifies receive address */
static const QString Zerocoin; /**< Specifies stealth address */
static const QString Delegators; /**< Specifies cold staking addresses which delegated tokens to this wallet */
static const QString ColdStaking; /**< Specifies cold staking own addresses */
static const QString ColdStakingSend; /**< Specifies send cold staking addresses (simil 'contacts')*/
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex& parent) const;
int columnCount(const QModelIndex& parent) const;
int sizeSend() const;
int sizeRecv() const;
int sizeDell() const;
int sizeColdSend() const;
void notifyChange(const QModelIndex &index);
QVariant data(const QModelIndex& index, int role) const;
bool setData(const QModelIndex& index, const QVariant& value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex& parent) const;
bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex& index) const;
/*@}*/
/* Add an address to the model.
Returns the added address on success, and an empty string otherwise.
*/
QString addRow(const QString& type, const QString& label, const QString& address);
/* Look up label for address in address book, if not found return empty string.
*/
QString labelForAddress(const QString& address) const;
/* Look up row index of an address in the model.
Return -1 if not found.
*/
int lookupAddress(const QString& address) const;
/*
* Look up purpose for address in address book, if not found return empty string
*/
std::string purposeForAddress(const std::string& address) const;
/**
* Checks if the address is whitelisted
*/
bool isWhitelisted(const std::string& address) const;
/**
* Return last unused address
*/
QString getAddressToShow() const;
EditStatus getEditStatus() const { return editStatus; }
private:
WalletModel* walletModel;
CWallet* wallet;
AddressTablePriv* priv;
QStringList columns;
EditStatus editStatus;
/** Notify listeners that data changed. */
void emitDataChanged(int index);
public slots:
/* Update address list from core.
*/
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status);
void updateEntry(const QString &pubCoin, const QString &isUsed, int status);
friend class AddressTablePriv;
};
#endif // BITCOIN_QT_ADDRESSTABLEMODEL_H
| [
"[email protected]"
] | |
0bd0cce30cf038c858e2d9a1a4e3ea3c101934a8 | ba3dd4cadc14ce59cb89464a60d81b35a874908e | /data_compression/L1/tests/gzipc/gzip_compress_test.cpp | 4edfc2e1c152d1609bf100306f239c544b54bf65 | [
"Zlib",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | 3togo/Vitis_Libraries | 65039ce75c191a023c85f603fc607c4b246e02a1 | fb6af2d541725e5404c6ed80bef787693e5861bf | refs/heads/master | 2023-03-17T17:08:14.643457 | 2022-04-27T03:03:11 | 2022-04-27T03:03:11 | 236,109,543 | 1 | 0 | null | 2020-01-25T01:05:24 | 2020-01-25T01:05:24 | null | UTF-8 | C++ | false | false | 3,896 | cpp | /*
* Copyright 2021 Xilinx, 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 <ap_int.h>
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>
#include "cmdlineparser.h"
#include "kernel_stream_utils.hpp"
#include "ap_axi_sdata.h"
#include "hls_stream.h"
#include "zlib_compress.hpp"
#define GMEM_DWIDTH 64
#define STRATEGY 0
#define NUM_BLOCKS 8
#define BLOCK_SIZE_IN_KB 32
#define TUSER_DWIDTH 32
typedef ap_axiu<GMEM_DWIDTH, 0, 0, 0> in_dT;
typedef ap_axiu<GMEM_DWIDTH, TUSER_DWIDTH, 0, 0> out_dT;
typedef ap_axiu<32, 0, 0, 0> size_dT;
const uint32_t c_size = (GMEM_DWIDTH / 8);
void gzipcMulticoreStreaming(hls::stream<in_dT>& inStream, hls::stream<out_dT>& outStream) {
#pragma HLS INTERFACE AXIS port = inStream
#pragma HLS INTERFACE AXIS port = outStream
#pragma HLS INTERFACE ap_ctrl_none port = return
#pragma HLS DATAFLOW
xf::compression::gzipMulticoreCompressAxiStream<STRATEGY, BLOCK_SIZE_IN_KB, NUM_BLOCKS, TUSER_DWIDTH>(inStream,
outStream);
}
int main(int argc, char* argv[]) {
std::string inputFileName = argv[1];
std::string outputFileName = argv[2];
// File Handling
std::fstream inFile;
inFile.open(inputFileName.c_str(), std::fstream::binary | std::fstream::in);
if (!inFile.is_open()) {
std::cout << "Cannot open the input file!!" << inputFileName << std::endl;
exit(0);
}
std::ofstream outFile;
outFile.open(outputFileName.c_str(), std::fstream::binary | std::fstream::out);
hls::stream<in_dT> inStream("inStream");
hls::stream<out_dT> outStream("outStream");
hls::stream<size_dT> outSizeStream("outSizeStream");
size_dT inSize;
inFile.seekg(0, std::ios::end); // reaching to end of file
const uint32_t inFileSize = (uint32_t)inFile.tellg();
inFile.seekg(0, std::ios::beg);
auto numItr = 1;
in_dT inData;
for (int z = 0; z < numItr; z++) {
inFile.seekg(0, std::ios::beg);
// Input File back to back
for (uint32_t i = 0; i < inFileSize; i += c_size) {
ap_uint<GMEM_DWIDTH> v;
bool last = false;
uint32_t rSize = c_size;
if (i + c_size >= inFileSize) {
rSize = inFileSize - i;
last = true;
}
inFile.read((char*)&v, rSize);
inData.data = v;
inData.keep = -1;
inData.last = false;
if (last) {
uint32_t num = 0;
inData.last = true;
for (int b = 0; b < rSize; b++) {
num |= 1UL << b;
}
inData.keep = num;
}
inStream << inData;
}
// Compression Call
gzipcMulticoreStreaming(inStream, outStream);
uint32_t byteCounter = 0;
// Write file
out_dT val;
do {
val = outStream.read();
ap_uint<GMEM_DWIDTH> o = val.data;
auto w_size = c_size;
if (val.keep != -1) w_size = __builtin_popcount(val.keep);
byteCounter += w_size;
outFile.write((char*)&o, w_size);
} while (!val.last);
}
inFile.close();
outFile.close();
}
| [
"[email protected]"
] | |
ea853e66b2809d2afd5f423032d459205e3d09c8 | 6d754001b497400e2cda378f39c22c1009e81b29 | /LeetCode/MyCode/73. set_matrix_zeros.h | d6681cbabb979b6f18d1570ef8e330bf6287101b | [] | no_license | guzhaolun/LeetCode | 43c318d951f9495e3d8ebdc7331359625ce42e14 | 36ad79a8ee2074f412326e22a1e9cd86b3fc1a56 | refs/heads/master | 2020-06-03T21:12:23.354790 | 2015-10-02T14:56:09 | 2015-10-02T14:56:09 | 34,769,163 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | h | #include <vector>
using namespace std;
class Solution73
{
public:
void setmatrixZeros(vector<vector<int>>& matrix)
{
if (matrix.empty())
return;
int m = matrix.size();
int n = matrix[0].size();
bool firstrow = false;
bool firstcolumn = false;
for (int i = 0; i<n; i++)
if (matrix[0][i] == 0)
firstrow = true;
for (int i = 0; i<m; i++)
if (matrix[i][0] == 0)
firstcolumn = true;
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
if (matrix[i][j] == 0)
{
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
for (int i = 1; i < m; i++)
{
if (matrix[i][0] == 0)
fill(&matrix[i][0], &matrix[i][0] + n, 0);
}
for (int i = 1; i < n; i++)
{
if (matrix[0][i] == 0)
{
for (int j = 1; j < m; j++)
matrix[j][i] = 0;
}
}
if (firstrow)
fill(&matrix[0][0], &matrix[0][0] + n, 0);
if (firstcolumn)
for (int i = 0; i<m; i++)
matrix[i][0] = 0;
}
}; | [
"[email protected]"
] | |
bbe24f2aa36397e4f923c64e28bc2b7d376be106 | 7a671688586aa69b00bcad2c4497630eb0185bff | /Instanced_Example/Main.cpp | 56999077391abd0d9b1d071e97b29dba45282e51 | [] | no_license | JasonCPark/cs488 | 902b5de9ece9ba72d3888dd69cf4a9c6cac068f4 | 135ee258372cdcb7e1674fcfabe111447533fdc7 | refs/heads/master | 2020-04-27T19:58:44.299839 | 2019-03-09T03:21:12 | 2019-03-09T03:21:12 | 174,641,533 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 188 | cpp | #include "InstancedExample.hpp"
int main( int argc, char **argv )
{
CS488Window::launch( argc, argv, new InstancedExample(), 1024, 768,
"Instanced Rendering Example" );
return 0;
}
| [
"[email protected]"
] | |
30f484fd4f3fe8f5afa22b2b3accc02dd4a73d9d | dccf5f6339baba548a83a7d390b63e285c9f0581 | /content/browser/web_package/signed_exchange_certificate_chain.h | 05daf2b617b4254a43d5b2570bbe8125d5378770 | [
"BSD-3-Clause"
] | permissive | Trailblazer01010111/chromium | 83843c9e45abb74a1a23df7302c1b274e460aee2 | 3fd9a73f1e93ce041a4580c20e30903ab090e95c | refs/heads/master | 2022-12-06T22:58:46.158304 | 2018-05-12T09:55:21 | 2018-05-12T09:55:21 | 133,138,333 | 1 | 0 | null | 2018-05-12T11:07:57 | 2018-05-12T11:07:56 | null | UTF-8 | C++ | false | false | 1,632 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERTIFICATE_CHAIN_H_
#define CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERTIFICATE_CHAIN_H_
#include <memory>
#include "base/containers/span.h"
#include "base/memory/scoped_refptr.h"
#include "base/optional.h"
#include "base/strings/string_piece_forward.h"
#include "content/common/content_export.h"
namespace net {
class X509Certificate;
} // namespace net
namespace content {
// SignedExchangeCertificateChain contains all information in signed exchange
// certificate chain.
// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#cert-chain-format
class CONTENT_EXPORT SignedExchangeCertificateChain {
public:
static std::unique_ptr<SignedExchangeCertificateChain> Parse(
base::span<const uint8_t> cert_response_body);
// Parses a TLS 1.3 Certificate message containing X.509v3 certificates and
// returns a vector of cert_data. Returns nullopt when failed to parse.
static base::Optional<std::vector<base::StringPiece>> GetCertChainFromMessage(
base::span<const uint8_t> message);
~SignedExchangeCertificateChain();
const scoped_refptr<net::X509Certificate>& cert() const { return cert_; }
private:
explicit SignedExchangeCertificateChain(
scoped_refptr<net::X509Certificate> cert);
scoped_refptr<net::X509Certificate> cert_;
};
} // namespace content
#endif // CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERTIFICATE_CHAIN_H_
| [
"[email protected]"
] | |
fd2ed01d46ab328ed39987896a56111187cf0ac2 | a6a4822ff0e33959e86f4bdd9dd09da0d4c08cab | /PED/p/p1/p1/practica 1 PED/practica 1/src/tads_poro/tad10TPoro.cpp | c203f92203cb7bd260295f33211c762b5fc5da8f | [] | no_license | amd48/Programacion-y-Estructuras-de-Datos | e211e656f6b8f5ea08e60907530af698d3d5dfeb | 26b3d65ba3c4b8fe09fc19d6148852cfe22aaa41 | refs/heads/master | 2021-01-03T19:44:59.439395 | 2020-02-13T09:39:33 | 2020-02-13T09:39:33 | 240,212,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | #include <iostream>
using namespace std;
#include "tporo.h"
int
main(void)
{
TPoro a;
TPoro b(0, 0, 0, NULL);
a.Posicion(0,0);
a.Volumen(0);
a.Color(NULL);
if(a==b)
cout << "IGUALES" << endl;
else
cout << "DISTINTOS" << endl;
a.Color("rojo");
b.Color("ROJO");
if(a==b)
cout << "IGUALES" << endl;
else
cout << "DISTINTOS" << endl;
}
| [
"[email protected]"
] | |
7cdcbf7fcb5f1a9584e1f184423825183649619d | f9e76089dee5038d2991c3780848954595a4a3dd | /CodeaTemplate/Codify/sfxr.cpp | cb9aafc46589adbd4a29844369d0c7d33ebc12ac | [
"Apache-2.0"
] | permissive | profburke/Codea-Runtime | b21f7824ac18b36a2cee3fe704018b4f6b6f0fba | c7e04bc85a6923df32500b14278aa76e149df1a4 | refs/heads/master | 2020-04-21T05:41:40.919695 | 2016-06-09T01:49:10 | 2016-06-09T01:49:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,378 | cpp | /*
* sfxr.cpp
* sfxr
*
* Original code by Tomas Pettersson 2007.
*
* Modifications are copyright Christopher Gassib 2009.
* This file is released under the MIT license as described in readme.txt
*
*/
#include "sfxr_Prefix.pch"
#include "sfxr.h"
#include <algorithm>
//#define SFXR_LOG(x) printf( "get %-50s %10f\n" , #x, (float)(x) )
#define SFXR_LOG(x) while(false){}
#define PARAM_SCALE 2.0f
#define PARAM_OFFSET -1.0f
#define PARAM_SCALE_GET 1.0f/(PARAM_SCALE)
#define PARAM_OFFSET_GET -1.0f*(PARAM_OFFSET)
static int clampToChar(int a)
{
return std::max(-127, std::min(a, 127));
}
const unsigned int sfxr::fileVersion;
const unsigned int sfxr::fileVersionFull;
const float PI = 3.14159265f;
// Galois Linear feedback shift register function.
// Straight from wikipedia.
inline unsigned int lfsr()
{
static unsigned int seed = 1;
return seed = (seed >> 1u) ^ (0u - (seed & 1u) & 0xd0000001u);
}
// Floating point noise function using the LFSR function above.
// Return values are in the range of -1.0 to 1.0.
inline float flfsr()
{
const float max = std::numeric_limits<unsigned int>::max();
return (static_cast<float>(lfsr()) / max * 2.0f) - 1.0f;
}
inline int rnd(int n)
{
return rand() % (n + 1);
}
inline float frnd(const float range)
{
return static_cast<double>(rand()) / static_cast<double>(RAND_MAX) * range;
}
sfxr::sfxr()
: playing_sample(false), master_vol(0.05f), sound_vol(0.5f), filesample(0.0f),
fileacc(0), wav_freq(44100), wav_bits(16), mute_stream(false), phase(0),
fperiod(0.0), fmaxperiod(0.0), fslide(0.0), fdslide(0.0), period(0),
square_duty(0.0f), square_slide(0.0f), env_stage(0), env_time(0), env_vol(0.0f),
fphase(0.0f), fdphase(0.0f), iphase(0), ipp(0), fltp(0.0f), fltdp(0.0f),
fltw(0.0f), fltw_d(0.0f), fltdmp(0.0f), fltphp(0.0f), flthp(0.0f), flthp_d(0.0f),
vib_phase(0.0f), vib_speed(0.0f), vib_amp(0.0f), rep_time(0), rep_limit(0),
arp_time(0), arp_limit(0), arp_mod(0.0), file_sampleswritten(0)
{
srand(time(NULL));
ResetParams();
memset(env_length, 0, sizeof(env_length));
memset(phaser_buffer, 0, sizeof(phaser_buffer));
memset(noise_buffer, 0, sizeof(noise_buffer));
}
sfxr::sfxr(const sfxr& original)
: playing_sample(original.playing_sample), master_vol(original.master_vol), sound_vol(original.sound_vol),
filesample(original.filesample), fileacc(original.fileacc), wav_freq(original.wav_freq),
wav_bits(original.wav_bits), mute_stream(original.mute_stream), phase(original.phase),
fperiod(original.fperiod), fmaxperiod(original.fmaxperiod), fslide(original.fslide),
fdslide(original.fdslide), period(original.period), square_duty(original.square_duty),
square_slide(original.square_slide), env_stage(original.env_stage), env_time(original.env_time),
env_vol(original.env_vol), fphase(original.fphase), fdphase(original.fdphase), iphase(original.iphase),
ipp(original.ipp), fltp(original.fltp), fltdp(original.fltdp), fltw(original.fltw),
fltw_d(original.fltw_d), fltdmp(original.fltdmp), fltphp(original.fltphp), flthp(original.flthp),
flthp_d(original.flthp_d), vib_phase(original.vib_phase), vib_speed(original.vib_speed),
vib_amp(original.vib_amp), rep_time(original.rep_time), rep_limit(original.rep_limit),
arp_time(original.arp_time), arp_limit(original.arp_limit), arp_mod(original.arp_mod),
file_sampleswritten(original.file_sampleswritten), wave_type(original.wave_type),
p_base_freq(original.p_base_freq), p_freq_limit(original.p_freq_limit), p_freq_ramp(original.p_freq_ramp),
p_freq_dramp(original.p_freq_dramp), p_duty(original.p_duty), p_duty_ramp(original.p_duty_ramp),
p_vib_strength(original.p_vib_strength), p_vib_speed(original.p_vib_speed),
p_vib_delay(original.p_vib_delay), p_env_attack(original.p_env_attack),
p_env_sustain(original.p_env_sustain), p_env_decay(original.p_env_decay),
p_env_punch(original.p_env_punch), filter_on(original.filter_on),
p_lpf_resonance(original.p_lpf_resonance), p_lpf_freq(original.p_lpf_freq),
p_lpf_ramp(original.p_lpf_ramp), p_hpf_freq(original.p_hpf_freq), p_hpf_ramp(original.p_hpf_ramp),
p_pha_offset(original.p_pha_offset), p_pha_ramp(original.p_pha_ramp),
p_repeat_speed(original.p_repeat_speed), p_arp_speed(original.p_arp_speed), p_arp_mod(original.p_arp_mod)
{
memcpy(env_length, original.env_length, sizeof(env_length));
memcpy(phaser_buffer, original.phaser_buffer, sizeof(phaser_buffer));
memcpy(noise_buffer, original.phaser_buffer, sizeof(noise_buffer));
}
sfxr::~sfxr()
{
}
sfxr& sfxr::operator =(const sfxr& rhs)
{
if (&rhs == this)
{
return *this;
}
playing_sample = rhs.playing_sample;
master_vol = rhs.master_vol;
sound_vol = rhs.sound_vol;
filesample = rhs.filesample;
fileacc = rhs.fileacc;
wav_freq = rhs.wav_freq;
wav_bits = rhs.wav_bits;
mute_stream = rhs.mute_stream;
phase = rhs.phase;
fperiod = rhs.fperiod;
fmaxperiod = rhs.fmaxperiod;
fslide = rhs.fslide;
fdslide = rhs.fdslide;
period = rhs.period;
square_duty = rhs.square_duty;
square_slide = rhs.square_slide;
env_stage = rhs.env_stage;
env_time = rhs.env_time;
env_vol = rhs.env_vol;
fphase = rhs.fphase;
fdphase = rhs.fdphase;
iphase = rhs.iphase;
ipp = rhs.ipp;
fltp = rhs.fltp;
fltdp = rhs.fltdp;
fltw = rhs.fltw;
fltw_d = rhs.fltw_d;
fltdmp = rhs.fltdmp;
fltphp = rhs.fltphp;
flthp = rhs.flthp;
flthp_d = rhs.flthp_d;
vib_phase = rhs.vib_phase;
vib_speed = rhs.vib_speed;
vib_amp = rhs.vib_amp;
rep_time = rhs.rep_time;
rep_limit = rhs.rep_limit;
arp_time = rhs.arp_time;
arp_limit = rhs.arp_limit;
arp_mod = rhs.arp_mod;
file_sampleswritten = rhs.file_sampleswritten;
wave_type = rhs.wave_type;
p_base_freq = rhs.p_base_freq;
p_freq_limit = rhs.p_freq_limit;
p_freq_ramp = rhs.p_freq_ramp;
p_freq_dramp = rhs.p_freq_dramp;
p_duty = rhs.p_duty;
p_duty_ramp = rhs.p_duty_ramp;
p_vib_strength = rhs.p_vib_strength;
p_vib_speed = rhs.p_vib_speed;
p_vib_delay = rhs.p_vib_delay;
p_env_attack = rhs.p_env_attack;
p_env_sustain = rhs.p_env_sustain;
p_env_decay = rhs.p_env_decay;
p_env_punch = rhs.p_env_punch;
filter_on = rhs.filter_on;
p_lpf_resonance = rhs.p_lpf_resonance;
p_lpf_freq = rhs.p_lpf_freq;
p_lpf_ramp = rhs.p_lpf_ramp;
p_hpf_freq = rhs.p_hpf_freq;
p_hpf_ramp = rhs.p_hpf_ramp;
p_pha_offset = rhs.p_pha_offset;
p_pha_ramp = rhs.p_pha_ramp;
p_repeat_speed = rhs.p_repeat_speed;
p_arp_speed = rhs.p_arp_speed;
p_arp_mod = rhs.p_arp_mod;
memcpy(env_length, rhs.env_length, sizeof(env_length));
memcpy(phaser_buffer, rhs.phaser_buffer, sizeof(phaser_buffer));
memcpy(noise_buffer, rhs.phaser_buffer, sizeof(noise_buffer));
return *this;
}
bool sfxr::IsPlaying()
{
return playing_sample && !mute_stream;
}
// This is a replacement for the original sfxr callback function.
int sfxr::operator ()(unsigned char* sampleBuffer, int byteCount)
{
if (playing_sample && !mute_stream)
{
unsigned int l = byteCount/sizeof(sint16);
float fbuf[l];
memset(fbuf, 0, sizeof(fbuf));
int samplesWritten = SynthSample(l, fbuf, NULL);
int samplesLeft = samplesWritten;
while (samplesLeft--)
{
float f = fbuf[samplesLeft];
if (f < -1.0) f = -1.0;
if (f > 1.0) f = 1.0;
((sint16*)sampleBuffer)[samplesLeft] = (sint16)(f * 32767);
}
return samplesWritten*sizeof(sint16);
}
memset(sampleBuffer, 0, byteCount);
return 0;
}
bool sfxr::LoadSettings(std::istream& stream)
{
int start = stream.tellg();
unsigned char version = 0;
stream.read(reinterpret_cast<char*>(&version), sizeof(version));
if(version != fileVersionFull)
{
if (version == fileVersion)
{
stream.seekg(start);
return LoadSettingsShort(stream);
}
return false;
}
stream.read(reinterpret_cast<char*>(&wave_type), sizeof(wave_type));
stream.read(reinterpret_cast<char*>(&sound_vol), sizeof(sound_vol));
stream.read(reinterpret_cast<char*>(&p_base_freq), sizeof(p_base_freq));
stream.read(reinterpret_cast<char*>(&p_freq_limit), sizeof(p_freq_limit));
stream.read(reinterpret_cast<char*>(&p_freq_ramp), sizeof(p_freq_ramp));
stream.read(reinterpret_cast<char*>(&p_freq_dramp), sizeof(p_freq_dramp));
stream.read(reinterpret_cast<char*>(&p_duty), sizeof(p_duty));
stream.read(reinterpret_cast<char*>(&p_duty_ramp), sizeof(p_duty_ramp));
stream.read(reinterpret_cast<char*>(&p_vib_strength), sizeof(p_vib_strength));
stream.read(reinterpret_cast<char*>(&p_vib_speed), sizeof(p_vib_speed));
stream.read(reinterpret_cast<char*>(&p_vib_delay), sizeof(p_vib_delay));
stream.read(reinterpret_cast<char*>(&p_env_attack), sizeof(p_env_attack));
stream.read(reinterpret_cast<char*>(&p_env_sustain), sizeof(p_env_sustain));
stream.read(reinterpret_cast<char*>(&p_env_decay), sizeof(p_env_decay));
stream.read(reinterpret_cast<char*>(&p_env_punch), sizeof(p_env_punch));
stream.read(reinterpret_cast<char*>(&filter_on), sizeof(filter_on));
stream.read(reinterpret_cast<char*>(&p_lpf_resonance), sizeof(p_lpf_resonance));
stream.read(reinterpret_cast<char*>(&p_lpf_freq), sizeof(p_lpf_freq));
stream.read(reinterpret_cast<char*>(&p_lpf_ramp), sizeof(p_lpf_ramp));
stream.read(reinterpret_cast<char*>(&p_hpf_freq), sizeof(p_hpf_freq));
stream.read(reinterpret_cast<char*>(&p_hpf_ramp), sizeof(p_hpf_ramp));
stream.read(reinterpret_cast<char*>(&p_pha_offset), sizeof(p_pha_offset));
stream.read(reinterpret_cast<char*>(&p_pha_ramp), sizeof(p_pha_ramp));
stream.read(reinterpret_cast<char*>(&p_repeat_speed), sizeof(p_repeat_speed));
stream.read(reinterpret_cast<char*>(&p_arp_speed), sizeof(p_arp_speed));
stream.read(reinterpret_cast<char*>(&p_arp_mod), sizeof(p_arp_mod));
return stream.good();
}
bool sfxr::SaveSettings(std::ostream& stream) const
{
unsigned char version = fileVersionFull;
stream.write(reinterpret_cast<const char*>(&version), sizeof(version));
stream.write(reinterpret_cast<const char*>(&wave_type), sizeof(wave_type));
stream.write(reinterpret_cast<const char*>(&sound_vol), sizeof(sound_vol));
stream.write(reinterpret_cast<const char*>(&p_base_freq), sizeof(p_base_freq));
stream.write(reinterpret_cast<const char*>(&p_freq_limit), sizeof(p_freq_limit));
stream.write(reinterpret_cast<const char*>(&p_freq_ramp), sizeof(p_freq_ramp));
stream.write(reinterpret_cast<const char*>(&p_freq_dramp), sizeof(p_freq_dramp));
stream.write(reinterpret_cast<const char*>(&p_duty), sizeof(p_duty));
stream.write(reinterpret_cast<const char*>(&p_duty_ramp), sizeof(p_duty_ramp));
stream.write(reinterpret_cast<const char*>(&p_vib_strength), sizeof(p_vib_strength));
stream.write(reinterpret_cast<const char*>(&p_vib_speed), sizeof(p_vib_speed));
stream.write(reinterpret_cast<const char*>(&p_vib_delay), sizeof(p_vib_delay));
stream.write(reinterpret_cast<const char*>(&p_env_attack), sizeof(p_env_attack));
stream.write(reinterpret_cast<const char*>(&p_env_sustain), sizeof(p_env_sustain));
stream.write(reinterpret_cast<const char*>(&p_env_decay), sizeof(p_env_decay));
stream.write(reinterpret_cast<const char*>(&p_env_punch), sizeof(p_env_punch));
stream.write(reinterpret_cast<const char*>(&filter_on), sizeof(filter_on));
stream.write(reinterpret_cast<const char*>(&p_lpf_resonance), sizeof(p_lpf_resonance));
stream.write(reinterpret_cast<const char*>(&p_lpf_freq), sizeof(p_lpf_freq));
stream.write(reinterpret_cast<const char*>(&p_lpf_ramp), sizeof(p_lpf_ramp));
stream.write(reinterpret_cast<const char*>(&p_hpf_freq), sizeof(p_hpf_freq));
stream.write(reinterpret_cast<const char*>(&p_hpf_ramp), sizeof(p_hpf_ramp));
stream.write(reinterpret_cast<const char*>(&p_pha_offset), sizeof(p_pha_offset));
stream.write(reinterpret_cast<const char*>(&p_pha_ramp), sizeof(p_pha_ramp));
stream.write(reinterpret_cast<const char*>(&p_repeat_speed), sizeof(p_repeat_speed));
stream.write(reinterpret_cast<const char*>(&p_arp_speed), sizeof(p_arp_speed));
stream.write(reinterpret_cast<const char*>(&p_arp_mod), sizeof(p_arp_mod));
return stream.good();
}
bool sfxr::LoadSettingsShort(std::istream& stream)
{
unsigned char version = 0;
stream.read(reinterpret_cast<char*>(&version), sizeof(version));
if(version != fileVersion)
{
return false;
}
#define PROCESS_VAR(var)\
{\
char c;\
stream.read(reinterpret_cast<char*>(&c), sizeof(c));\
var = ((typeof(var))(c))/128.f;\
}
#define PROCESS_SET(func)\
{\
char c;\
stream.read(reinterpret_cast<char*>(&c), sizeof(c));\
(func)( ((float)(c))/128.f );\
}
#define PROCESS_SET_NORMWITH(func,norm)\
{\
char c;\
stream.read(reinterpret_cast<char*>(&c), sizeof(c));\
(func)(((float)(c))/(norm));\
}
#define PROCESS_VAR_UNNORM(var)\
{\
char c;\
stream.read(reinterpret_cast<char*>(&c), sizeof(c));\
var = ((typeof(var))(c));\
}
PROCESS_VAR_UNNORM(wave_type)
PROCESS_VAR(sound_vol)
PROCESS_SET(SetStartFrequency) //PROCESS_VAR(p_base_freq)
PROCESS_SET(SetMinimumFrequency) //PROCESS_VAR(p_freq_limit)
PROCESS_SET(SetSlide) //PROCESS_VAR(p_freq_ramp)
PROCESS_SET(SetDeltaSlide) //PROCESS_VAR(p_freq_dramp)
PROCESS_SET(SetSquareDuty) //PROCESS_VAR(p_duty)
PROCESS_SET(SetDutySweep) //PROCESS_VAR(p_duty_ramp)
PROCESS_SET(SetVibratoDepth) //PROCESS_VAR(p_vib_strength)
PROCESS_SET(SetVibratoSpeed) //PROCESS_VAR(p_vib_speed)
PROCESS_SET(SetVibratoDelay) //PROCESS_VAR(p_vib_delay) //TODO: NEEDS FIX
//PROCESS_SET_NORMWITH(SetAttackTime,25) //PROCESS_VAR(p_env_attack)
//PROCESS_SET_NORMWITH(SetSustainTime,25) //PROCESS_VAR(p_env_sustain)
//PROCESS_SET_NORMWITH(SetDecayTime,25) //PROCESS_VAR(p_env_decay)
stream.read(reinterpret_cast<char*>(&p_env_attack), sizeof(p_env_attack));
stream.read(reinterpret_cast<char*>(&p_env_sustain), sizeof(p_env_sustain));
stream.read(reinterpret_cast<char*>(&p_env_decay), sizeof(p_env_decay));
PROCESS_SET(SetSustainPunch) //PROCESS_VAR(p_env_punch)
PROCESS_VAR_UNNORM(filter_on)
PROCESS_SET(SetLowPassFilterResonance) //PROCESS_VAR(p_lpf_resonance)
PROCESS_SET(SetLowPassFilterCutoff) //PROCESS_VAR(p_lpf_freq)
PROCESS_SET(SetLowPassFilterCutoffSweep) //PROCESS_VAR(p_lpf_ramp)
PROCESS_SET(SetHighPassFilterCutoff) //PROCESS_VAR(p_hpf_freq)
PROCESS_SET(SetHighPassFilterCutoffSweep) //PROCESS_VAR(p_hpf_ramp)
PROCESS_SET(SetPhaserOffset) //PROCESS_VAR(p_pha_offset)
PROCESS_SET(SetPhaserSweep) //PROCESS_VAR(p_pha_ramp)
PROCESS_SET(SetRepeatSpeed) //PROCESS_VAR(p_repeat_speed)
PROCESS_SET(SetChangeSpeed) //PROCESS_VAR(p_arp_speed)
PROCESS_SET(SetChangeAmount) //PROCESS_VAR(p_arp_mod)
#undef PROCESS_VAR
#undef PROCESS_SET
#undef PROCESS_SET_NORMWITH
#undef PROCESS_VAR_UNNORM
return stream.good();
}
bool sfxr::SaveSettingsShort(std::ostream& stream) const
{
unsigned char version = fileVersion;
stream.write(reinterpret_cast<const char*>(&version), sizeof(version));
#define PROCESS_VAR(var)\
{\
char c = clampToChar(var*128);\
stream.write(reinterpret_cast<const char*>(&c), sizeof(char));\
}
#define PROCESS_VAR_UNNORM(var)\
{\
char c = clampToChar(var);\
stream.write(reinterpret_cast<const char*>(&c), sizeof(char));\
}
#define PROCESS_VAR_NORMWITH(var,norm)\
{\
char c = clampToChar((var)*(norm));\
stream.write(reinterpret_cast<const char*>(&c), sizeof(char));\
}
//stream.write(reinterpret_cast<const char*>(&wave_type), sizeof(wave_type));
PROCESS_VAR_UNNORM(wave_type)
//stream.write(reinterpret_cast<const char*>(&sound_vol), sizeof(sound_vol));
PROCESS_VAR(sound_vol)
PROCESS_VAR(GetStartFrequency()); //PROCESS_VAR(p_base_freq)
PROCESS_VAR(GetMinimumFrequency()); //PROCESS_VAR(p_freq_limit)
PROCESS_VAR(GetSlide()); //PROCESS_VAR(p_freq_ramp)
PROCESS_VAR(GetDeltaSlide()); //PROCESS_VAR(p_freq_dramp)
PROCESS_VAR(GetSquareDuty()); //PROCESS_VAR(p_duty)
PROCESS_VAR(GetDutySweep()); //PROCESS_VAR(p_duty_ramp)
PROCESS_VAR(GetVibratoDepth()); //PROCESS_VAR(p_vib_strength)
PROCESS_VAR(GetVibratoSpeed()); //PROCESS_VAR(p_vib_speed)
PROCESS_VAR(GetVibratoDelay());
//PROCESS_VAR_NORMWITH(GetAttackTime(),25); //PROCESS_VAR(p_env_attack)
//PROCESS_VAR_NORMWITH(GetSustainTime(),25); //PROCESS_VAR(p_env_sustain)
//PROCESS_VAR_NORMWITH(GetDecayTime(),25); //PROCESS_VAR(p_env_decay)
stream.write(reinterpret_cast<const char*>(&p_env_attack), sizeof(p_env_attack));
stream.write(reinterpret_cast<const char*>(&p_env_sustain), sizeof(p_env_sustain));
stream.write(reinterpret_cast<const char*>(&p_env_decay), sizeof(p_env_decay));
PROCESS_VAR(GetSustainPunch()); //PROCESS_VAR(p_env_punch)
PROCESS_VAR_UNNORM(filter_on)
PROCESS_VAR(GetLowPassFilterResonance()); //PROCESS_VAR(p_lpf_resonance)
PROCESS_VAR(GetLowPassFilterCutoff()); //PROCESS_VAR(p_lpf_freq)
PROCESS_VAR(GetLowPassFilterCutoffSweep()); //PROCESS_VAR(p_lpf_ramp)
PROCESS_VAR(GetHighPassFilterCutoff()); //PROCESS_VAR(p_hpf_freq)
PROCESS_VAR(GetHighPassFilterCutoffSweep()); //PROCESS_VAR(p_hpf_ramp)
PROCESS_VAR(GetPhaserOffset()); //PROCESS_VAR(p_pha_offset)
PROCESS_VAR(GetPhaserSweep()); //PROCESS_VAR(p_pha_ramp)
PROCESS_VAR(GetRepeatSpeed()); //PROCESS_VAR(p_repeat_speed)
PROCESS_VAR(GetChangeSpeed()); //PROCESS_VAR(p_arp_speed)
PROCESS_VAR(GetChangeAmount())
#undef PROCESS_VAR_UNNORM
#undef PROCESS_VAR
#undef PROCESS_VAR_NORMWITH
return stream.good();
}
bool sfxr::LoadSettings(const char* filename)
{
FILE* file=fopen(filename, "rb");
if(!file)
return false;
int version=0;
fread(&version, 1, sizeof(int), file);
if(version!=100 && version!=101 && version!=102)
return false;
fread(&wave_type, 1, sizeof(int), file);
sound_vol=0.5f;
if(version==102)
fread(&sound_vol, 1, sizeof(float), file);
fread(&p_base_freq, 1, sizeof(float), file);
fread(&p_freq_limit, 1, sizeof(float), file);
fread(&p_freq_ramp, 1, sizeof(float), file);
if(version>=101)
fread(&p_freq_dramp, 1, sizeof(float), file);
fread(&p_duty, 1, sizeof(float), file);
fread(&p_duty_ramp, 1, sizeof(float), file);
fread(&p_vib_strength, 1, sizeof(float), file);
fread(&p_vib_speed, 1, sizeof(float), file);
fread(&p_vib_delay, 1, sizeof(float), file);
fread(&p_env_attack, 1, sizeof(float), file);
fread(&p_env_sustain, 1, sizeof(float), file);
fread(&p_env_decay, 1, sizeof(float), file);
fread(&p_env_punch, 1, sizeof(float), file);
fread(&filter_on, 1, sizeof(bool), file);
fread(&p_lpf_resonance, 1, sizeof(float), file);
fread(&p_lpf_freq, 1, sizeof(float), file);
fread(&p_lpf_ramp, 1, sizeof(float), file);
fread(&p_hpf_freq, 1, sizeof(float), file);
fread(&p_hpf_ramp, 1, sizeof(float), file);
fread(&p_pha_offset, 1, sizeof(float), file);
fread(&p_pha_ramp, 1, sizeof(float), file);
fread(&p_repeat_speed, 1, sizeof(float), file);
if(version>=101)
{
fread(&p_arp_speed, 1, sizeof(float), file);
fread(&p_arp_mod, 1, sizeof(float), file);
}
fclose(file);
return true;
}
bool sfxr::SaveSettings(const char* filename)
{
FILE* file=fopen(filename, "wb");
if(!file)
return false;
int version=102;
fwrite(&version, 1, sizeof(int), file);
fwrite(&wave_type, 1, sizeof(int), file);
fwrite(&sound_vol, 1, sizeof(float), file);
fwrite(&p_base_freq, 1, sizeof(float), file);
fwrite(&p_freq_limit, 1, sizeof(float), file);
fwrite(&p_freq_ramp, 1, sizeof(float), file);
fwrite(&p_freq_dramp, 1, sizeof(float), file);
fwrite(&p_duty, 1, sizeof(float), file);
fwrite(&p_duty_ramp, 1, sizeof(float), file);
fwrite(&p_vib_strength, 1, sizeof(float), file);
fwrite(&p_vib_speed, 1, sizeof(float), file);
fwrite(&p_vib_delay, 1, sizeof(float), file);
fwrite(&p_env_attack, 1, sizeof(float), file);
fwrite(&p_env_sustain, 1, sizeof(float), file);
fwrite(&p_env_decay, 1, sizeof(float), file);
fwrite(&p_env_punch, 1, sizeof(float), file);
fwrite(&filter_on, 1, sizeof(bool), file);
fwrite(&p_lpf_resonance, 1, sizeof(float), file);
fwrite(&p_lpf_freq, 1, sizeof(float), file);
fwrite(&p_lpf_ramp, 1, sizeof(float), file);
fwrite(&p_hpf_freq, 1, sizeof(float), file);
fwrite(&p_hpf_ramp, 1, sizeof(float), file);
fwrite(&p_pha_offset, 1, sizeof(float), file);
fwrite(&p_pha_ramp, 1, sizeof(float), file);
fwrite(&p_repeat_speed, 1, sizeof(float), file);
fwrite(&p_arp_speed, 1, sizeof(float), file);
fwrite(&p_arp_mod, 1, sizeof(float), file);
fclose(file);
return true;
}
bool sfxr::ExportWAV(const char* filename)
{
FILE* foutput=fopen(filename, "wb");
if(!foutput)
return false;
// write wav header
unsigned int dword=0;
unsigned short word=0;
fwrite("RIFF", 4, 1, foutput); // "RIFF"
dword=0;
fwrite(&dword, 1, 4, foutput); // remaining file size
fwrite("WAVE", 4, 1, foutput); // "WAVE"
fwrite("fmt ", 4, 1, foutput); // "fmt "
dword=16;
fwrite(&dword, 1, 4, foutput); // chunk size
word=1;
fwrite(&word, 1, 2, foutput); // compression code
word=1;
fwrite(&word, 1, 2, foutput); // channels
dword=wav_freq;
fwrite(&dword, 1, 4, foutput); // sample rate
dword=wav_freq*wav_bits/8;
fwrite(&dword, 1, 4, foutput); // bytes/sec
word=wav_bits/8;
fwrite(&word, 1, 2, foutput); // block align
word=wav_bits;
fwrite(&word, 1, 2, foutput); // bits per sample
fwrite("data", 4, 1, foutput); // "data"
dword=0;
int foutstream_datasize=ftell(foutput);
fwrite(&dword, 1, 4, foutput); // chunk size
// write sample data
mute_stream=true;
file_sampleswritten=0;
filesample=0.0f;
fileacc=0;
PlaySample();
while(playing_sample)
SynthSample(256, NULL, foutput);
mute_stream=false;
// seek back to header and write size info
fseek(foutput, 4, SEEK_SET);
dword=0;
dword=foutstream_datasize-4+file_sampleswritten*wav_bits/8;
fwrite(&dword, 1, 4, foutput); // remaining file size
fseek(foutput, foutstream_datasize, SEEK_SET);
dword=file_sampleswritten*wav_bits/8;
fwrite(&dword, 1, 4, foutput); // chunk size (data)
fclose(foutput);
return true;
}
void sfxr::ResetParams()
{
wave_type=0;
p_base_freq=0.3f;
p_freq_limit=0.0f;
p_freq_ramp=0.0f;
p_freq_dramp=0.0f;
p_duty=0.0f;
p_duty_ramp=0.0f;
p_vib_strength=0.0f;
p_vib_speed=0.0f;
p_vib_delay=0.0f;
p_env_attack=0.0f;
p_env_sustain=0.3f;
p_env_decay=0.4f;
p_env_punch=0.0f;
filter_on=false;
p_lpf_resonance=0.0f;
p_lpf_freq=1.0f;
p_lpf_ramp=0.0f;
p_hpf_freq=0.0f;
p_hpf_ramp=0.0f;
p_pha_offset=0.0f;
p_pha_ramp=0.0f;
p_repeat_speed=0.0f;
p_arp_speed=0.0f;
p_arp_mod=0.0f;
sound_vol = 0.5f;
}
void sfxr::ResetSample(bool restart)
{
if(!restart)
phase=0;
fperiod=100.0/(p_base_freq*p_base_freq+0.001);
period=(int)fperiod;
fmaxperiod=100.0/(p_freq_limit*p_freq_limit+0.001);
fslide=1.0-pow((double)p_freq_ramp, 3.0)*0.01;
fdslide=-pow((double)p_freq_dramp, 3.0)*0.000001;
square_duty=0.5f-p_duty*0.5f;
square_slide=-p_duty_ramp*0.00005f;
if(p_arp_mod>=0.0f)
arp_mod=1.0-pow((double)p_arp_mod, 2.0)*0.9;
else
arp_mod=1.0+pow((double)p_arp_mod, 2.0)*10.0;
arp_time=0;
arp_limit=(int)(pow(1.0f-p_arp_speed, 2.0f)*20000+32);
if(p_arp_speed==1.0f)
arp_limit=0;
if(!restart)
{
// reset filter
fltp=0.0f;
fltdp=0.0f;
fltw=pow(p_lpf_freq, 3.0f)*0.1f;
fltw_d=1.0f+p_lpf_ramp*0.0001f;
fltdmp=5.0f/(1.0f+pow(p_lpf_resonance, 2.0f)*20.0f)*(0.01f+fltw);
if(fltdmp>0.8f) fltdmp=0.8f;
fltphp=0.0f;
flthp=pow(p_hpf_freq, 2.0f)*0.1f;
flthp_d=1.0+p_hpf_ramp*0.0003f;
// reset vibrato
vib_phase=0.0f;
vib_speed=pow(p_vib_speed, 2.0f)*0.01f;
vib_amp=p_vib_strength*0.5f;
// reset envelope
env_vol=0.0f;
env_stage=0;
env_time=0;
env_length[0]=(int)(p_env_attack*p_env_attack*100000.0f);
env_length[1]=(int)(p_env_sustain*p_env_sustain*100000.0f);
env_length[2]=(int)(p_env_decay*p_env_decay*100000.0f);
fphase=pow(p_pha_offset, 2.0f)*1020.0f;
if(p_pha_offset<0.0f) fphase=-fphase;
fdphase=pow(p_pha_ramp, 2.0f)*1.0f;
if(p_pha_ramp<0.0f) fdphase=-fdphase;
iphase=abs((int)fphase);
ipp=0;
for(int i=0;i<1024;i++)
phaser_buffer[i]=0.0f;
for(int i=0;i<32;i++)
noise_buffer[i] = frnd(2.0f) - 1.0f;
rep_time=0;
rep_limit=(int)(pow(1.0f-p_repeat_speed, 2.0f)*20000+32);
if(p_repeat_speed==0.0f)
rep_limit=0;
}
}
void sfxr::PlaySample()
{
ResetSample(false);
playing_sample=true;
}
void sfxr::SetSeed(unsigned seed)
{
srand(seed);
}
int sfxr::SynthSample(int length, float* buffer, FILE* file)
{
int numFloatsWritten = 0;
for(int i=0;i<length;i++)
{
if(!playing_sample)
break;
rep_time++;
if(rep_limit!=0 && rep_time>=rep_limit)
{
rep_time=0;
ResetSample(true);
}
// frequency envelopes/arpeggios
arp_time++;
if(arp_limit!=0 && arp_time>=arp_limit)
{
arp_limit=0;
fperiod*=arp_mod;
}
fslide+=fdslide;
fperiod*=fslide;
if(fperiod>fmaxperiod)
{
fperiod=fmaxperiod;
if(p_freq_limit>0.0f)
playing_sample=false;
}
float rfperiod=fperiod;
if(vib_amp>0.0f)
{
vib_phase+=vib_speed;
rfperiod=fperiod*(1.0+sin(vib_phase)*vib_amp);
}
period=(int)rfperiod;
if(period<8) period=8;
square_duty+=square_slide;
if(square_duty<0.0f) square_duty=0.0f;
if(square_duty>0.5f) square_duty=0.5f;
// volume envelope
env_time++;
if(env_time>env_length[env_stage])
{
env_time=0;
env_stage++;
if(env_stage==3)
playing_sample=false;
}
if(env_stage==0)
env_vol=(float)env_time/env_length[0];
if(env_stage==1)
env_vol=1.0f+pow(1.0f-(float)env_time/env_length[1], 1.0f)*2.0f*p_env_punch;
if(env_stage==2)
env_vol=1.0f-(float)env_time/env_length[2];
// phaser step
fphase+=fdphase;
iphase=abs((int)fphase);
if(iphase>1023) iphase=1023;
if(flthp_d!=0.0f)
{
flthp*=flthp_d;
if(flthp<0.00001f) flthp=0.00001f;
if(flthp>0.1f) flthp=0.1f;
}
float ssample=0.0f;
for(int si=0;si<8;si++) // 8x supersampling
{
float sample=0.0f;
phase++;
if(phase>=period)
{
// phase=0;
phase%=period;
if(wave_type==3)
for(int i=0;i<32;i++)
noise_buffer[i]=flfsr(); // NOTE: The original sfxr used: frnd(2.0f)-1.0f
// as the noise function. The iPhone CPU wasn't
// fast enough to keep up with the audio output.
}
// base waveform
float fp=(float)phase/period;
switch(wave_type)
{
case 0: // square
if(fp<square_duty)
sample=0.5f;
else
sample=-0.5f;
break;
case 1: // sawtooth
sample=1.0f-fp*2;
break;
case 2: // sine
sample=(float)sin(fp*2*PI);
break;
case 3: // noise
sample=noise_buffer[phase*32/period];
break;
}
// lp filter
float pp=fltp;
fltw*=fltw_d;
if(fltw<0.0f) fltw=0.0f;
if(fltw>0.1f) fltw=0.1f;
if(p_lpf_freq!=1.0f)
{
fltdp+=(sample-fltp)*fltw;
fltdp-=fltdp*fltdmp;
}
else
{
fltp=sample;
fltdp=0.0f;
}
fltp+=fltdp;
// hp filter
fltphp+=fltp-pp;
fltphp-=fltphp*flthp;
sample=fltphp;
// phaser
phaser_buffer[ipp&1023]=sample;
sample+=phaser_buffer[(ipp-iphase+1024)&1023];
ipp=(ipp+1)&1023;
// final accumulation and envelope application
ssample+=sample*env_vol;
}
ssample=ssample/8*master_vol;
ssample*=2.0f*sound_vol;
numFloatsWritten++;
if(buffer!=NULL)
{
if(ssample>1.0f) ssample=1.0f;
if(ssample<-1.0f) ssample=-1.0f;
*buffer++=ssample;
}
if(file!=NULL)
{
// quantize depending on format
// accumulate/count to accomodate variable sample rate?
ssample*=4.0f; // arbitrary gain to get reasonable output volume...
if(ssample>1.0f) ssample=1.0f;
if(ssample<-1.0f) ssample=-1.0f;
filesample+=ssample;
fileacc++;
if(wav_freq==44100 || fileacc==2)
{
filesample/=fileacc;
fileacc=0;
if(wav_bits==16)
{
short isample=(short)(filesample*32000);
fwrite(&isample, 1, 2, file);
}
else
{
unsigned char isample=(unsigned char)(filesample*127+128);
fwrite(&isample, 1, 1, file);
}
filesample=0.0f;
}
file_sampleswritten++;
}
}
return numFloatsWritten;
}
float sfxr::GetSoundVolume() const
{
SFXR_LOG(sound_vol);
return sound_vol;
}
void sfxr::SetSoundVolume(const float value)
{
sound_vol = value;
}
WaveformGenerator sfxr::GetWaveform() const
{
SFXR_LOG(wave_type);
switch (wave_type) {
case 0:
return SquareWave;
case 1:
return Sawtooth;
case 2:
return SineWave;
case 3:
return Noise;
default:
abort();
}
}
void sfxr::SetWaveform(const WaveformGenerator waveform)
{
SFXR_LOG(waveform);
switch (waveform) {
case SquareWave:
wave_type = 0;
break;
case Sawtooth:
wave_type = 1;
break;
case SineWave:
wave_type = 2;
break;
case Noise:
wave_type = 3;
break;
default:
abort();
}
}
float sfxr::GetAttackTime() const
{
SFXR_LOG(p_env_attack);
return p_env_attack;//(p_env_attack+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetAttackTime(const float value)
{
p_env_attack = value;//value * 2.0f - 1.0f;
}
float sfxr::GetSustainTime() const
{
SFXR_LOG(p_env_sustain);
return p_env_sustain;//(p_env_sustain+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetSustainTime(const float value)
{
p_env_sustain = value;// * 2.0f - 1.0f;
}
float sfxr::GetSustainPunch() const
{
SFXR_LOG((p_env_punch+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_env_punch+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetSustainPunch(const float value)
{
p_env_punch = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetDecayTime() const
{
SFXR_LOG(p_env_decay);
return p_env_decay;//(p_env_decay+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetDecayTime(const float value)
{
p_env_decay = value;// * 2.0f - 1.0f;
}
float sfxr::GetStartFrequency() const
{
SFXR_LOG(p_base_freq);
return p_base_freq;
}
void sfxr::SetStartFrequency(const float value)
{
p_base_freq = value;
}
float sfxr::GetMinimumFrequency() const
{
SFXR_LOG(p_freq_limit);
return p_freq_limit;
}
void sfxr::SetMinimumFrequency(const float value)
{
p_freq_limit = value;
}
float sfxr::GetSlide() const
{
SFXR_LOG((p_freq_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_freq_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetSlide(const float value)
{
p_freq_ramp = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetDeltaSlide() const
{
SFXR_LOG((p_freq_dramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_freq_dramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetDeltaSlide(const float value)
{
p_freq_dramp = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetVibratoDepth() const
{
SFXR_LOG((p_vib_strength+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_vib_strength+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetVibratoDepth(const float value)
{
p_vib_strength = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetVibratoSpeed() const
{
SFXR_LOG((p_vib_speed+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_vib_speed+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetVibratoSpeed(const float value)
{
p_vib_speed = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetVibratoDelay() const
{
SFXR_LOG((p_vib_delay+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_vib_delay+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetVibratoDelay(const float value)
{
p_vib_delay = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetChangeAmount() const
{
SFXR_LOG((p_arp_mod+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_arp_mod+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetChangeAmount(const float value)
{
p_arp_mod = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetChangeSpeed() const
{
SFXR_LOG((p_arp_speed+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_arp_speed+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetChangeSpeed(const float value)
{
p_arp_speed = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetSquareDuty() const
{
SFXR_LOG((p_duty+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_duty+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetSquareDuty(const float value)
{
p_duty = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetDutySweep() const
{
SFXR_LOG((p_duty_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_duty_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetDutySweep(const float value)
{
p_duty_ramp = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetRepeatSpeed() const
{
SFXR_LOG((p_repeat_speed+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_repeat_speed+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetRepeatSpeed(const float value)
{
p_repeat_speed = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetPhaserOffset() const
{
SFXR_LOG((p_pha_offset+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_pha_offset+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetPhaserOffset(const float value)
{
p_pha_offset = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetPhaserSweep() const
{
SFXR_LOG((p_pha_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_pha_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetPhaserSweep(const float value)
{
p_pha_ramp = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetLowPassFilterCutoff() const
{
SFXR_LOG((p_lpf_freq+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_lpf_freq+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetLowPassFilterCutoff(const float value)
{
p_lpf_freq = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetLowPassFilterCutoffSweep() const
{
SFXR_LOG((p_lpf_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_lpf_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetLowPassFilterCutoffSweep(const float value)
{
p_lpf_ramp = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetLowPassFilterResonance() const
{
SFXR_LOG((p_lpf_resonance+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_lpf_resonance+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetLowPassFilterResonance(const float value)
{
p_lpf_resonance = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetHighPassFilterCutoff() const
{
SFXR_LOG((p_hpf_freq+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_hpf_freq+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetHighPassFilterCutoff(const float value)
{
p_hpf_freq = value * PARAM_SCALE + PARAM_OFFSET;
}
float sfxr::GetHighPassFilterCutoffSweep() const
{
SFXR_LOG((p_hpf_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET);
return (p_hpf_ramp+ PARAM_OFFSET_GET)*PARAM_SCALE_GET;
}
void sfxr::SetHighPassFilterCutoffSweep(const float value)
{
p_hpf_ramp = value * PARAM_SCALE + PARAM_OFFSET;
}
void sfxr::PickupCoinButtonPressed()
{
ResetParams();
p_base_freq=0.4f+frnd(0.5f);
p_env_attack=0.0f;
p_env_sustain=frnd(0.1f);
p_env_decay=0.1f+frnd(0.4f);
p_env_punch=0.3f+frnd(0.3f);
if(rnd(1))
{
p_arp_speed=0.5f+frnd(0.2f);
p_arp_mod=0.2f+frnd(0.4f);
}
PlaySample();
}
void sfxr::LaserShootButtonPressed()
{
ResetParams();
wave_type=rnd(2);
if(wave_type==2 && rnd(1))
wave_type=rnd(1);
p_base_freq=0.5f+frnd(0.5f);
p_freq_limit=p_base_freq-0.2f-frnd(0.6f);
if(p_freq_limit<0.2f) p_freq_limit=0.2f;
p_freq_ramp=-0.15f-frnd(0.2f);
if(rnd(2)==0)
{
p_base_freq=0.3f+frnd(0.6f);
p_freq_limit=frnd(0.1f);
p_freq_ramp=-0.35f-frnd(0.3f);
}
if(rnd(1))
{
p_duty=frnd(0.5f);
p_duty_ramp=frnd(0.2f);
}
else
{
p_duty=0.4f+frnd(0.5f);
p_duty_ramp=-frnd(0.7f);
}
p_env_attack=0.0f;
p_env_sustain=0.1f+frnd(0.2f);
p_env_decay=frnd(0.4f);
if(rnd(1))
p_env_punch=frnd(0.3f);
if(rnd(2)==0)
{
p_pha_offset=frnd(0.2f);
p_pha_ramp=-frnd(0.2f);
}
if(rnd(1))
p_hpf_freq=frnd(0.3f);
PlaySample();
}
void sfxr::ExplosionButtonPressed()
{
ResetParams();
wave_type=3;
if(rnd(1))
{
p_base_freq=0.1f+frnd(0.4f);
p_freq_ramp=-0.1f+frnd(0.4f);
}
else
{
p_base_freq=0.2f+frnd(0.7f);
p_freq_ramp=-0.2f-frnd(0.2f);
}
p_base_freq*=p_base_freq;
if(rnd(4)==0)
p_freq_ramp=0.0f;
if(rnd(2)==0)
p_repeat_speed=0.3f+frnd(0.5f);
p_env_attack=0.0f;
p_env_sustain=0.1f+frnd(0.3f);
p_env_decay=frnd(0.5f);
if(rnd(1)==0)
{
p_pha_offset=-0.3f+frnd(0.9f);
p_pha_ramp=-frnd(0.3f);
}
p_env_punch=0.2f+frnd(0.6f);
if(rnd(1))
{
p_vib_strength=frnd(0.7f);
p_vib_speed=frnd(0.6f);
}
if(rnd(2)==0)
{
p_arp_speed=0.6f+frnd(0.3f);
p_arp_mod=0.8f-frnd(1.6f);
}
PlaySample();
}
void sfxr::PowerupButtonPressed()
{
ResetParams();
if(rnd(1))
wave_type=1;
else
p_duty=frnd(0.6f);
if(rnd(1))
{
p_base_freq=0.2f+frnd(0.3f);
p_freq_ramp=0.1f+frnd(0.4f);
p_repeat_speed=0.4f+frnd(0.4f);
}
else
{
p_base_freq=0.2f+frnd(0.3f);
p_freq_ramp=0.05f+frnd(0.2f);
if(rnd(1))
{
p_vib_strength=frnd(0.7f);
p_vib_speed=frnd(0.6f);
}
}
p_env_attack=0.0f;
p_env_sustain=frnd(0.4f);
p_env_decay=0.1f+frnd(0.4f);
PlaySample();
}
void sfxr::HitHurtButtonPressed()
{
ResetParams();
wave_type=rnd(2);
if(wave_type==2)
wave_type=3;
if(wave_type==0)
p_duty=frnd(0.6f);
p_base_freq=0.2f+frnd(0.6f);
p_freq_ramp=-0.3f-frnd(0.4f);
p_env_attack=0.0f;
p_env_sustain=frnd(0.1f);
p_env_decay=0.1f+frnd(0.2f);
if(rnd(1))
p_hpf_freq=frnd(0.3f);
PlaySample();
}
void sfxr::JumpButtonPressed()
{
ResetParams();
wave_type=0;
p_duty=frnd(0.6f);
p_base_freq=0.3f+frnd(0.3f);
p_freq_ramp=0.1f+frnd(0.2f);
p_env_attack=0.0f;
p_env_sustain=0.1f+frnd(0.3f);
p_env_decay=0.1f+frnd(0.2f);
if(rnd(1))
p_hpf_freq=frnd(0.3f);
if(rnd(1))
p_lpf_freq=1.0f-frnd(0.6f);
PlaySample();
}
void sfxr::BlitSelectButtonPressed()
{
ResetParams();
wave_type=rnd(1);
if(wave_type==0)
p_duty=frnd(0.6f);
p_base_freq=0.2f+frnd(0.4f);
p_env_attack=0.0f;
p_env_sustain=0.1f+frnd(0.1f);
p_env_decay=frnd(0.2f);
p_hpf_freq=0.1f;
PlaySample();
}
void sfxr::MutateButtonPressed()
{
if(rnd(1)) p_base_freq+=frnd(0.1f)-0.05f;
//if(rnd(1)) p_freq_limit+=frnd(0.1f)-0.05f;
if(rnd(1)) p_freq_ramp+=frnd(0.1f)-0.05f;
if(rnd(1)) p_freq_dramp+=frnd(0.1f)-0.05f;
if(rnd(1)) p_duty+=frnd(0.1f)-0.05f;
if(rnd(1)) p_duty_ramp+=frnd(0.1f)-0.05f;
if(rnd(1)) p_vib_strength+=frnd(0.1f)-0.05f;
if(rnd(1)) p_vib_speed+=frnd(0.1f)-0.05f;
if(rnd(1)) p_vib_delay+=frnd(0.1f)-0.05f;
if(rnd(1)) p_env_attack+=frnd(0.1f)-0.05f;
if(rnd(1)) p_env_sustain+=frnd(0.1f)-0.05f;
if(rnd(1)) p_env_decay+=frnd(0.1f)-0.05f;
if(rnd(1)) p_env_punch+=frnd(0.1f)-0.05f;
if(rnd(1)) p_lpf_resonance+=frnd(0.1f)-0.05f;
if(rnd(1)) p_lpf_freq+=frnd(0.1f)-0.05f;
if(rnd(1)) p_lpf_ramp+=frnd(0.1f)-0.05f;
if(rnd(1)) p_hpf_freq+=frnd(0.1f)-0.05f;
if(rnd(1)) p_hpf_ramp+=frnd(0.1f)-0.05f;
if(rnd(1)) p_pha_offset+=frnd(0.1f)-0.05f;
if(rnd(1)) p_pha_ramp+=frnd(0.1f)-0.05f;
if(rnd(1)) p_repeat_speed+=frnd(0.1f)-0.05f;
if(rnd(1)) p_arp_speed+=frnd(0.1f)-0.05f;
if(rnd(1)) p_arp_mod+=frnd(0.1f)-0.05f;
PlaySample();
}
void sfxr::RandomizeButtonPressed()
{
p_base_freq=pow(frnd(2.0f)-1.0f, 2.0f);
if(rnd(1))
p_base_freq=pow(frnd(2.0f)-1.0f, 3.0f)+0.5f;
p_freq_limit=0.0f;
p_freq_ramp=pow(frnd(2.0f)-1.0f, 5.0f);
if(p_base_freq>0.7f && p_freq_ramp>0.2f)
p_freq_ramp=-p_freq_ramp;
if(p_base_freq<0.2f && p_freq_ramp<-0.05f)
p_freq_ramp=-p_freq_ramp;
p_freq_dramp=pow(frnd(2.0f)-1.0f, 3.0f);
p_duty=frnd(2.0f)-1.0f;
p_duty_ramp=pow(frnd(2.0f)-1.0f, 3.0f);
p_vib_strength=pow(frnd(2.0f)-1.0f, 3.0f);
p_vib_speed=frnd(2.0f)-1.0f;
p_vib_delay=frnd(2.0f)-1.0f;
p_env_attack=pow(frnd(2.0f)-1.0f, 3.0f);
p_env_sustain=pow(frnd(2.0f)-1.0f, 2.0f);
p_env_decay=frnd(2.0f)-1.0f;
p_env_punch=pow(frnd(0.8f), 2.0f);
if(p_env_attack+p_env_sustain+p_env_decay<0.2f)
{
p_env_sustain+=0.2f+frnd(0.3f);
p_env_decay+=0.2f+frnd(0.3f);
}
p_lpf_resonance=frnd(2.0f)-1.0f;
p_lpf_freq=1.0f-pow(frnd(1.0f), 3.0f);
p_lpf_ramp=pow(frnd(2.0f)-1.0f, 3.0f);
if(p_lpf_freq<0.1f && p_lpf_ramp<-0.05f)
p_lpf_ramp=-p_lpf_ramp;
p_hpf_freq=pow(frnd(1.0f), 5.0f);
p_hpf_ramp=pow(frnd(2.0f)-1.0f, 5.0f);
p_pha_offset=pow(frnd(2.0f)-1.0f, 3.0f);
p_pha_ramp=pow(frnd(2.0f)-1.0f, 3.0f);
p_repeat_speed=frnd(2.0f)-1.0f;
p_arp_speed=frnd(2.0f)-1.0f;
p_arp_mod=frnd(2.0f)-1.0f;
PlaySample();
}
| [
"[email protected]"
] | |
ea87403d4752aa1d798d0c6f5b35cf8516d7c878 | af9095a0c6e2cfc0bcc7facaa7fd9f0fc28f97cb | /rosplan_knowledge_base/include/rosplan_knowledge_base/PDDLKnowledgeBase.h | 63396d7854bdf446b84e8bb1dda940bfc3c3d051 | [
"BSD-2-Clause"
] | permissive | Wonseok-Oh/rosplan | f597bed066a776429ddf8e21e638a905ca61a4dd | c6d83a0b2da034d310497d73fadb0bfe6abff812 | refs/heads/main | 2023-06-23T10:10:06.251316 | 2021-07-12T08:12:09 | 2021-07-12T08:12:09 | 376,003,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,547 | h | #ifndef KCL_PDDL_Knowledgebase
#define KCL_PDDL_Knowledgebase
#include <ros/ros.h>
#include <vector>
#include <iostream>
#include <fstream>
#include "std_srvs/Empty.h"
#include "rosplan_knowledge_msgs/KnowledgeUpdateService.h"
#include "rosplan_knowledge_msgs/KnowledgeUpdateServiceArray.h"
#include "rosplan_knowledge_msgs/KnowledgeQueryService.h"
#include "rosplan_knowledge_msgs/processReset.h"
#include "rosplan_knowledge_msgs/GetDomainNameService.h"
#include "rosplan_knowledge_msgs/GetDomainTypeService.h"
#include "rosplan_knowledge_msgs/GetDomainAttributeService.h"
#include "rosplan_knowledge_msgs/GetDomainOperatorService.h"
#include "rosplan_knowledge_msgs/GetDomainOperatorDetailsService.h"
#include "rosplan_knowledge_msgs/GetDomainPredicateDetailsService.h"
#include "rosplan_knowledge_msgs/DomainFormula.h"
#include "rosplan_knowledge_msgs/GetAttributeService.h"
#include "rosplan_knowledge_msgs/GetInstanceService.h"
#include "rosplan_knowledge_msgs/GetMetricService.h"
#include "rosplan_knowledge_msgs/KnowledgeItem.h"
#include "KnowledgeBase.h"
#include "KnowledgeComparitor.h"
#include "PDDLDomainParser.h"
#include "PDDLProblemParser.h"
#include "VALVisitorOperator.h"
#include "VALVisitorPredicate.h"
#include "VALVisitorProblem.h"
namespace KCL_rosplan {
class PDDLKnowledgeBase : public KnowledgeBase {
private:
/* parsing domain using VAL */
PDDLDomainParser domain_parser;
/* initial state from problem file using VAL */
PDDLProblemParser problem_parser;
// process reset signal for HiP-RL (Wonseok added)
ros::Subscriber m_reset_processor; // getInstances
public:
PDDLKnowledgeBase(ros::NodeHandle& n, int process_num = 0) : KnowledgeBase(n) {
m_reset_processor = _nh.subscribe<rosplan_knowledge_msgs::processReset>("reset", 1, &PDDLKnowledgeBase::processReset, this);
};
~PDDLKnowledgeBase() = default;
/* clear all the knowledge and re-initialize from domain and problem file */
void processReset(const rosplan_knowledge_msgs::processReset::ConstPtr &msg);
/* parse domain and probelm files */
void parseDomain(const std::string& domain_file_path, const std::string& problem_file_path) override;
/* add the initial state to the knowledge base */
void addInitialState() override;
void addConstants() override;
/* service methods for fetching the domain details */
bool getDomainName(rosplan_knowledge_msgs::GetDomainNameService::Request &req, rosplan_knowledge_msgs::GetDomainNameService::Response &res) override;
bool getTypes(rosplan_knowledge_msgs::GetDomainTypeService::Request &req, rosplan_knowledge_msgs::GetDomainTypeService::Response &res) override;
bool getPredicates(rosplan_knowledge_msgs::GetDomainAttributeService::Request &req, rosplan_knowledge_msgs::GetDomainAttributeService::Response &res) override;
bool getFunctionPredicates(rosplan_knowledge_msgs::GetDomainAttributeService::Request &req, rosplan_knowledge_msgs::GetDomainAttributeService::Response &res) override;
bool getOperators(rosplan_knowledge_msgs::GetDomainOperatorService::Request &req, rosplan_knowledge_msgs::GetDomainOperatorService::Response &res) override;
bool getOperatorDetails(rosplan_knowledge_msgs::GetDomainOperatorDetailsService::Request &req, rosplan_knowledge_msgs::GetDomainOperatorDetailsService::Response &res) override;
bool getPredicateDetails(rosplan_knowledge_msgs::GetDomainPredicateDetailsService::Request &req, rosplan_knowledge_msgs::GetDomainPredicateDetailsService::Response &res) override;
};
}
#endif
| [
"[email protected]"
] | |
0ea2d999306dcedb1d63508bc50a379347a84848 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_repos_function_2827_last_repos.cpp | abdde2024839142e840f4c43e90fc7dd245f0b36 | [] | 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 | 4,352 | cpp | static apr_status_t h2_session_start(h2_session *session, int *rv)
{
apr_status_t status = APR_SUCCESS;
nghttp2_settings_entry settings[3];
size_t slen;
int win_size;
ap_assert(session);
/* Start the conversation by submitting our SETTINGS frame */
*rv = 0;
if (session->r) {
const char *s, *cs;
apr_size_t dlen;
h2_stream * stream;
/* 'h2c' mode: we should have a 'HTTP2-Settings' header with
* base64 encoded client settings. */
s = apr_table_get(session->r->headers_in, "HTTP2-Settings");
if (!s) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EINVAL, session->r,
APLOGNO(02931)
"HTTP2-Settings header missing in request");
return APR_EINVAL;
}
cs = NULL;
dlen = h2_util_base64url_decode(&cs, s, session->pool);
if (APLOGrdebug(session->r)) {
char buffer[128];
h2_util_hex_dump(buffer, 128, (char*)cs, dlen);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, session->r, APLOGNO(03070)
"upgrading h2c session with HTTP2-Settings: %s -> %s (%d)",
s, buffer, (int)dlen);
}
*rv = nghttp2_session_upgrade(session->ngh2, (uint8_t*)cs, dlen, NULL);
if (*rv != 0) {
status = APR_EINVAL;
ap_log_rerror(APLOG_MARK, APLOG_ERR, status, session->r,
APLOGNO(02932) "nghttp2_session_upgrade: %s",
nghttp2_strerror(*rv));
return status;
}
/* Now we need to auto-open stream 1 for the request we got. */
stream = h2_session_open_stream(session, 1, 0);
if (!stream) {
status = APR_EGENERAL;
ap_log_rerror(APLOG_MARK, APLOG_ERR, status, session->r,
APLOGNO(02933) "open stream 1: %s",
nghttp2_strerror(*rv));
return status;
}
status = h2_stream_set_request_rec(stream, session->r, 1);
if (status != APR_SUCCESS) {
return status;
}
}
slen = 0;
settings[slen].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
settings[slen].value = (uint32_t)session->max_stream_count;
++slen;
win_size = h2_config_geti(session->config, H2_CONF_WIN_SIZE);
if (win_size != H2_INITIAL_WINDOW_SIZE) {
settings[slen].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
settings[slen].value = win_size;
++slen;
}
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, session->c,
H2_SSSN_LOG(APLOGNO(03201), session,
"start, INITIAL_WINDOW_SIZE=%ld, MAX_CONCURRENT_STREAMS=%d"),
(long)win_size, (int)session->max_stream_count);
*rv = nghttp2_submit_settings(session->ngh2, NGHTTP2_FLAG_NONE,
settings, slen);
if (*rv != 0) {
status = APR_EGENERAL;
ap_log_cerror(APLOG_MARK, APLOG_ERR, status, session->c,
H2_SSSN_LOG(APLOGNO(02935), session,
"nghttp2_submit_settings: %s"), nghttp2_strerror(*rv));
}
else {
/* use maximum possible value for connection window size. We are only
* interested in per stream flow control. which have the initial window
* size configured above.
* Therefore, for our use, the connection window can only get in the
* way. Example: if we allow 100 streams with a 32KB window each, we
* buffer up to 3.2 MB of data. Unless we do separate connection window
* interim updates, any smaller connection window will lead to blocking
* in DATA flow.
*/
*rv = nghttp2_submit_window_update(session->ngh2, NGHTTP2_FLAG_NONE,
0, NGHTTP2_MAX_WINDOW_SIZE - win_size);
if (*rv != 0) {
status = APR_EGENERAL;
ap_log_cerror(APLOG_MARK, APLOG_ERR, status, session->c,
H2_SSSN_LOG(APLOGNO(02970), session,
"nghttp2_submit_window_update: %s"),
nghttp2_strerror(*rv));
}
}
return status;
} | [
"[email protected]"
] | |
9bb9ce70b53da99c5f414fce1583324e77e9da1b | a4e12f7b14bf563b8c6b473268c8087c51c0cc12 | /src/labs/vector_add_lab_xilinx/Emulation-HW/binary_container_1.build/link/vivado/vpl/prj/prj.srcs/sources_1/bd/pfm_dynamic/ip/pfm_dynamic_dpa_hub_0/sim/pfm_dynamic_dpa_hub_0.h | 1d9fcfc8dff11f822019ebec0bf05d342645daea | [] | no_license | BabarZKhan/xilinx_ETH_training_winterschool_2021 | 49054f85dfab1b4b75e3f4f85244bb8428cdf983 | bd2f2f1fc9cf524bee432970d9b10d21c013dda1 | refs/heads/main | 2023-09-02T07:24:15.182179 | 2021-11-22T09:09:28 | 2021-11-22T09:09:28 | 329,877,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,013 | h | #ifndef IP_PFM_DYNAMIC_DPA_HUB_0_H_
#define IP_PFM_DYNAMIC_DPA_HUB_0_H_
// (c) Copyright 1995-2021 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
#ifndef XTLM
#include "xtlm.h"
#endif
#ifndef SYSTEMC_INCLUDED
#include <systemc>
#endif
#if defined(_MSC_VER)
#define DllExport __declspec(dllexport)
#elif defined(__GNUC__)
#define DllExport __attribute__ ((visibility("default")))
#else
#define DllExport
#endif
#include "pfm_dynamic_dpa_hub_0_sc.h"
#ifdef XILINX_SIMULATOR
class DllExport pfm_dynamic_dpa_hub_0 : public pfm_dynamic_dpa_hub_0_sc
{
public:
pfm_dynamic_dpa_hub_0(const sc_core::sc_module_name& nm);
virtual ~pfm_dynamic_dpa_hub_0();
// module pin-to-pin RTL interface
sc_core::sc_in< bool > s_aximm_clk;
sc_core::sc_in< bool > s_aximm_aresetn;
sc_core::sc_in< bool > trace_clk;
sc_core::sc_in< bool > trace_aresetn;
sc_core::sc_in< bool > axilite_clk;
sc_core::sc_in< bool > axilite_aresetn;
sc_core::sc_out< bool > trace_tready0;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata0;
sc_core::sc_in< bool > trace_tlast0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest0;
sc_core::sc_in< bool > trace_tvalid0;
sc_core::sc_out< bool > trace_tready1;
sc_core::sc_out< sc_dt::sc_bv<64> > trace_tdata1;
sc_core::sc_in< bool > trace_tlast1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest1;
sc_core::sc_in< bool > trace_tvalid1;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata2;
sc_core::sc_out< bool > trace_tready2;
sc_core::sc_in< bool > trace_tlast2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest2;
sc_core::sc_in< bool > trace_tvalid2;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awaddr;
sc_core::sc_in< bool > s_axi_awvalid;
sc_core::sc_out< bool > s_axi_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb;
sc_core::sc_in< bool > s_axi_wvalid;
sc_core::sc_out< bool > s_axi_wready;
sc_core::sc_out< bool > s_axi_bvalid;
sc_core::sc_in< bool > s_axi_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_araddr;
sc_core::sc_in< bool > s_axi_arvalid;
sc_core::sc_out< bool > s_axi_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp;
sc_core::sc_out< bool > s_axi_rvalid;
sc_core::sc_in< bool > s_axi_rready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_awaddr;
sc_core::sc_in< bool > s_axihub_awvalid;
sc_core::sc_out< bool > s_axihub_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axihub_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axihub_wstrb;
sc_core::sc_in< bool > s_axihub_wvalid;
sc_core::sc_out< bool > s_axihub_wready;
sc_core::sc_out< bool > s_axihub_bvalid;
sc_core::sc_in< bool > s_axihub_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_araddr;
sc_core::sc_in< bool > s_axihub_arvalid;
sc_core::sc_out< bool > s_axihub_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axihub_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_rresp;
sc_core::sc_out< bool > s_axihub_rvalid;
sc_core::sc_in< bool > s_axihub_rready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_awaddr;
sc_core::sc_in< bool > s_aximm_awvalid;
sc_core::sc_out< bool > s_aximm_awready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_awlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_awsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_awburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_awid;
sc_core::sc_in< sc_dt::sc_bv<64> > s_aximm_wdata;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_wstrb;
sc_core::sc_in< bool > s_aximm_wvalid;
sc_core::sc_out< bool > s_aximm_wready;
sc_core::sc_out< bool > s_aximm_bvalid;
sc_core::sc_in< bool > s_aximm_bready;
sc_core::sc_in< bool > s_aximm_wlast;
sc_core::sc_out< bool > s_aximm_rlast;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_bresp;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_bid;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_araddr;
sc_core::sc_in< bool > s_aximm_arvalid;
sc_core::sc_out< bool > s_aximm_arready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_arlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_arsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_arburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_arid;
sc_core::sc_out< sc_dt::sc_bv<64> > s_aximm_rdata;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_rid;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_rresp;
sc_core::sc_out< bool > s_aximm_rvalid;
sc_core::sc_in< bool > s_aximm_rready;
protected:
virtual void before_end_of_elaboration();
private:
xtlm::xaximm_pin2xtlm_t<64,32,1,1,1,1,1,1>* mp_S_AXIMM_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIFIFO_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIHUB_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_0_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_1_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_2_transactor;
};
#endif // XILINX_SIMULATOR
#ifdef XM_SYSTEMC
class DllExport pfm_dynamic_dpa_hub_0 : public pfm_dynamic_dpa_hub_0_sc
{
public:
pfm_dynamic_dpa_hub_0(const sc_core::sc_module_name& nm);
virtual ~pfm_dynamic_dpa_hub_0();
// module pin-to-pin RTL interface
sc_core::sc_in< bool > s_aximm_clk;
sc_core::sc_in< bool > s_aximm_aresetn;
sc_core::sc_in< bool > trace_clk;
sc_core::sc_in< bool > trace_aresetn;
sc_core::sc_in< bool > axilite_clk;
sc_core::sc_in< bool > axilite_aresetn;
sc_core::sc_out< bool > trace_tready0;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata0;
sc_core::sc_in< bool > trace_tlast0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest0;
sc_core::sc_in< bool > trace_tvalid0;
sc_core::sc_out< bool > trace_tready1;
sc_core::sc_out< sc_dt::sc_bv<64> > trace_tdata1;
sc_core::sc_in< bool > trace_tlast1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest1;
sc_core::sc_in< bool > trace_tvalid1;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata2;
sc_core::sc_out< bool > trace_tready2;
sc_core::sc_in< bool > trace_tlast2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest2;
sc_core::sc_in< bool > trace_tvalid2;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awaddr;
sc_core::sc_in< bool > s_axi_awvalid;
sc_core::sc_out< bool > s_axi_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb;
sc_core::sc_in< bool > s_axi_wvalid;
sc_core::sc_out< bool > s_axi_wready;
sc_core::sc_out< bool > s_axi_bvalid;
sc_core::sc_in< bool > s_axi_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_araddr;
sc_core::sc_in< bool > s_axi_arvalid;
sc_core::sc_out< bool > s_axi_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp;
sc_core::sc_out< bool > s_axi_rvalid;
sc_core::sc_in< bool > s_axi_rready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_awaddr;
sc_core::sc_in< bool > s_axihub_awvalid;
sc_core::sc_out< bool > s_axihub_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axihub_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axihub_wstrb;
sc_core::sc_in< bool > s_axihub_wvalid;
sc_core::sc_out< bool > s_axihub_wready;
sc_core::sc_out< bool > s_axihub_bvalid;
sc_core::sc_in< bool > s_axihub_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_araddr;
sc_core::sc_in< bool > s_axihub_arvalid;
sc_core::sc_out< bool > s_axihub_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axihub_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_rresp;
sc_core::sc_out< bool > s_axihub_rvalid;
sc_core::sc_in< bool > s_axihub_rready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_awaddr;
sc_core::sc_in< bool > s_aximm_awvalid;
sc_core::sc_out< bool > s_aximm_awready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_awlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_awsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_awburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_awid;
sc_core::sc_in< sc_dt::sc_bv<64> > s_aximm_wdata;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_wstrb;
sc_core::sc_in< bool > s_aximm_wvalid;
sc_core::sc_out< bool > s_aximm_wready;
sc_core::sc_out< bool > s_aximm_bvalid;
sc_core::sc_in< bool > s_aximm_bready;
sc_core::sc_in< bool > s_aximm_wlast;
sc_core::sc_out< bool > s_aximm_rlast;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_bresp;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_bid;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_araddr;
sc_core::sc_in< bool > s_aximm_arvalid;
sc_core::sc_out< bool > s_aximm_arready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_arlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_arsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_arburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_arid;
sc_core::sc_out< sc_dt::sc_bv<64> > s_aximm_rdata;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_rid;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_rresp;
sc_core::sc_out< bool > s_aximm_rvalid;
sc_core::sc_in< bool > s_aximm_rready;
protected:
virtual void before_end_of_elaboration();
private:
xtlm::xaximm_pin2xtlm_t<64,32,1,1,1,1,1,1>* mp_S_AXIMM_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIFIFO_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIHUB_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_0_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_1_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_2_transactor;
};
#endif // XM_SYSTEMC
#ifdef RIVIERA
class DllExport pfm_dynamic_dpa_hub_0 : public pfm_dynamic_dpa_hub_0_sc
{
public:
pfm_dynamic_dpa_hub_0(const sc_core::sc_module_name& nm);
virtual ~pfm_dynamic_dpa_hub_0();
// module pin-to-pin RTL interface
sc_core::sc_in< bool > s_aximm_clk;
sc_core::sc_in< bool > s_aximm_aresetn;
sc_core::sc_in< bool > trace_clk;
sc_core::sc_in< bool > trace_aresetn;
sc_core::sc_in< bool > axilite_clk;
sc_core::sc_in< bool > axilite_aresetn;
sc_core::sc_out< bool > trace_tready0;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata0;
sc_core::sc_in< bool > trace_tlast0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest0;
sc_core::sc_in< bool > trace_tvalid0;
sc_core::sc_out< bool > trace_tready1;
sc_core::sc_out< sc_dt::sc_bv<64> > trace_tdata1;
sc_core::sc_in< bool > trace_tlast1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest1;
sc_core::sc_in< bool > trace_tvalid1;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata2;
sc_core::sc_out< bool > trace_tready2;
sc_core::sc_in< bool > trace_tlast2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest2;
sc_core::sc_in< bool > trace_tvalid2;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awaddr;
sc_core::sc_in< bool > s_axi_awvalid;
sc_core::sc_out< bool > s_axi_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb;
sc_core::sc_in< bool > s_axi_wvalid;
sc_core::sc_out< bool > s_axi_wready;
sc_core::sc_out< bool > s_axi_bvalid;
sc_core::sc_in< bool > s_axi_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_araddr;
sc_core::sc_in< bool > s_axi_arvalid;
sc_core::sc_out< bool > s_axi_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp;
sc_core::sc_out< bool > s_axi_rvalid;
sc_core::sc_in< bool > s_axi_rready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_awaddr;
sc_core::sc_in< bool > s_axihub_awvalid;
sc_core::sc_out< bool > s_axihub_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axihub_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axihub_wstrb;
sc_core::sc_in< bool > s_axihub_wvalid;
sc_core::sc_out< bool > s_axihub_wready;
sc_core::sc_out< bool > s_axihub_bvalid;
sc_core::sc_in< bool > s_axihub_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_araddr;
sc_core::sc_in< bool > s_axihub_arvalid;
sc_core::sc_out< bool > s_axihub_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axihub_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_rresp;
sc_core::sc_out< bool > s_axihub_rvalid;
sc_core::sc_in< bool > s_axihub_rready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_awaddr;
sc_core::sc_in< bool > s_aximm_awvalid;
sc_core::sc_out< bool > s_aximm_awready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_awlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_awsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_awburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_awid;
sc_core::sc_in< sc_dt::sc_bv<64> > s_aximm_wdata;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_wstrb;
sc_core::sc_in< bool > s_aximm_wvalid;
sc_core::sc_out< bool > s_aximm_wready;
sc_core::sc_out< bool > s_aximm_bvalid;
sc_core::sc_in< bool > s_aximm_bready;
sc_core::sc_in< bool > s_aximm_wlast;
sc_core::sc_out< bool > s_aximm_rlast;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_bresp;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_bid;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_araddr;
sc_core::sc_in< bool > s_aximm_arvalid;
sc_core::sc_out< bool > s_aximm_arready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_arlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_arsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_arburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_arid;
sc_core::sc_out< sc_dt::sc_bv<64> > s_aximm_rdata;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_rid;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_rresp;
sc_core::sc_out< bool > s_aximm_rvalid;
sc_core::sc_in< bool > s_aximm_rready;
protected:
virtual void before_end_of_elaboration();
private:
xtlm::xaximm_pin2xtlm_t<64,32,1,1,1,1,1,1>* mp_S_AXIMM_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIFIFO_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIHUB_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_0_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_1_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_2_transactor;
};
#endif // RIVIERA
#ifdef VCSSYSTEMC
#include "utils/xtlm_aximm_target_stub.h"
#include "utils/xtlm_axis_target_stub.h"
class DllExport pfm_dynamic_dpa_hub_0 : public pfm_dynamic_dpa_hub_0_sc
{
public:
pfm_dynamic_dpa_hub_0(const sc_core::sc_module_name& nm);
virtual ~pfm_dynamic_dpa_hub_0();
// module pin-to-pin RTL interface
sc_core::sc_in< bool > s_aximm_clk;
sc_core::sc_in< bool > s_aximm_aresetn;
sc_core::sc_in< bool > trace_clk;
sc_core::sc_in< bool > trace_aresetn;
sc_core::sc_in< bool > axilite_clk;
sc_core::sc_in< bool > axilite_aresetn;
sc_core::sc_out< bool > trace_tready0;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata0;
sc_core::sc_in< bool > trace_tlast0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest0;
sc_core::sc_in< bool > trace_tvalid0;
sc_core::sc_out< bool > trace_tready1;
sc_core::sc_out< sc_dt::sc_bv<64> > trace_tdata1;
sc_core::sc_in< bool > trace_tlast1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest1;
sc_core::sc_in< bool > trace_tvalid1;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata2;
sc_core::sc_out< bool > trace_tready2;
sc_core::sc_in< bool > trace_tlast2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest2;
sc_core::sc_in< bool > trace_tvalid2;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awaddr;
sc_core::sc_in< bool > s_axi_awvalid;
sc_core::sc_out< bool > s_axi_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb;
sc_core::sc_in< bool > s_axi_wvalid;
sc_core::sc_out< bool > s_axi_wready;
sc_core::sc_out< bool > s_axi_bvalid;
sc_core::sc_in< bool > s_axi_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_araddr;
sc_core::sc_in< bool > s_axi_arvalid;
sc_core::sc_out< bool > s_axi_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp;
sc_core::sc_out< bool > s_axi_rvalid;
sc_core::sc_in< bool > s_axi_rready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_awaddr;
sc_core::sc_in< bool > s_axihub_awvalid;
sc_core::sc_out< bool > s_axihub_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axihub_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axihub_wstrb;
sc_core::sc_in< bool > s_axihub_wvalid;
sc_core::sc_out< bool > s_axihub_wready;
sc_core::sc_out< bool > s_axihub_bvalid;
sc_core::sc_in< bool > s_axihub_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_araddr;
sc_core::sc_in< bool > s_axihub_arvalid;
sc_core::sc_out< bool > s_axihub_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axihub_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_rresp;
sc_core::sc_out< bool > s_axihub_rvalid;
sc_core::sc_in< bool > s_axihub_rready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_awaddr;
sc_core::sc_in< bool > s_aximm_awvalid;
sc_core::sc_out< bool > s_aximm_awready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_awlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_awsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_awburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_awid;
sc_core::sc_in< sc_dt::sc_bv<64> > s_aximm_wdata;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_wstrb;
sc_core::sc_in< bool > s_aximm_wvalid;
sc_core::sc_out< bool > s_aximm_wready;
sc_core::sc_out< bool > s_aximm_bvalid;
sc_core::sc_in< bool > s_aximm_bready;
sc_core::sc_in< bool > s_aximm_wlast;
sc_core::sc_out< bool > s_aximm_rlast;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_bresp;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_bid;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_araddr;
sc_core::sc_in< bool > s_aximm_arvalid;
sc_core::sc_out< bool > s_aximm_arready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_arlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_arsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_arburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_arid;
sc_core::sc_out< sc_dt::sc_bv<64> > s_aximm_rdata;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_rid;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_rresp;
sc_core::sc_out< bool > s_aximm_rvalid;
sc_core::sc_in< bool > s_aximm_rready;
protected:
virtual void before_end_of_elaboration();
private:
xtlm::xaximm_pin2xtlm_t<64,32,1,1,1,1,1,1>* mp_S_AXIMM_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIFIFO_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIHUB_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_0_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_1_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_2_transactor;
// Transactor stubs
xtlm::xtlm_aximm_target_stub * S_AXIFIFO_transactor_target_rd_socket_stub;
xtlm::xtlm_aximm_target_stub * S_AXIFIFO_transactor_target_wr_socket_stub;
xtlm::xtlm_aximm_target_stub * S_AXIHUB_transactor_target_rd_socket_stub;
xtlm::xtlm_aximm_target_stub * S_AXIHUB_transactor_target_wr_socket_stub;
xtlm::xtlm_aximm_target_stub * S_AXIMM_transactor_target_rd_socket_stub;
xtlm::xtlm_aximm_target_stub * S_AXIMM_transactor_target_wr_socket_stub;
xtlm::xtlm_axis_target_stub * TRACE_IN_0_transactor_target_socket_stub;
xtlm::xtlm_axis_target_stub * TRACE_IN_1_transactor_target_socket_stub;
xtlm::xtlm_axis_target_stub * TRACE_IN_2_transactor_target_socket_stub;
// Socket stubs
};
#endif // VCSSYSTEMC
#ifdef MTI_SYSTEMC
class DllExport pfm_dynamic_dpa_hub_0 : public pfm_dynamic_dpa_hub_0_sc
{
public:
pfm_dynamic_dpa_hub_0(const sc_core::sc_module_name& nm);
virtual ~pfm_dynamic_dpa_hub_0();
// module pin-to-pin RTL interface
sc_core::sc_in< bool > s_aximm_clk;
sc_core::sc_in< bool > s_aximm_aresetn;
sc_core::sc_in< bool > trace_clk;
sc_core::sc_in< bool > trace_aresetn;
sc_core::sc_in< bool > axilite_clk;
sc_core::sc_in< bool > axilite_aresetn;
sc_core::sc_out< bool > trace_tready0;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata0;
sc_core::sc_in< bool > trace_tlast0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid0;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest0;
sc_core::sc_in< bool > trace_tvalid0;
sc_core::sc_out< bool > trace_tready1;
sc_core::sc_out< sc_dt::sc_bv<64> > trace_tdata1;
sc_core::sc_in< bool > trace_tlast1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid1;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest1;
sc_core::sc_in< bool > trace_tvalid1;
sc_core::sc_in< sc_dt::sc_bv<64> > trace_tdata2;
sc_core::sc_out< bool > trace_tready2;
sc_core::sc_in< bool > trace_tlast2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tid2;
sc_core::sc_in< sc_dt::sc_bv<8> > trace_tdest2;
sc_core::sc_in< bool > trace_tvalid2;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awaddr;
sc_core::sc_in< bool > s_axi_awvalid;
sc_core::sc_out< bool > s_axi_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb;
sc_core::sc_in< bool > s_axi_wvalid;
sc_core::sc_out< bool > s_axi_wready;
sc_core::sc_out< bool > s_axi_bvalid;
sc_core::sc_in< bool > s_axi_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_araddr;
sc_core::sc_in< bool > s_axi_arvalid;
sc_core::sc_out< bool > s_axi_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp;
sc_core::sc_out< bool > s_axi_rvalid;
sc_core::sc_in< bool > s_axi_rready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_awaddr;
sc_core::sc_in< bool > s_axihub_awvalid;
sc_core::sc_out< bool > s_axihub_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axihub_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axihub_wstrb;
sc_core::sc_in< bool > s_axihub_wvalid;
sc_core::sc_out< bool > s_axihub_wready;
sc_core::sc_out< bool > s_axihub_bvalid;
sc_core::sc_in< bool > s_axihub_bready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_bresp;
sc_core::sc_in< sc_dt::sc_bv<8> > s_axihub_araddr;
sc_core::sc_in< bool > s_axihub_arvalid;
sc_core::sc_out< bool > s_axihub_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axihub_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axihub_rresp;
sc_core::sc_out< bool > s_axihub_rvalid;
sc_core::sc_in< bool > s_axihub_rready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_awaddr;
sc_core::sc_in< bool > s_aximm_awvalid;
sc_core::sc_out< bool > s_aximm_awready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_awlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_awsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_awburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_awid;
sc_core::sc_in< sc_dt::sc_bv<64> > s_aximm_wdata;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_wstrb;
sc_core::sc_in< bool > s_aximm_wvalid;
sc_core::sc_out< bool > s_aximm_wready;
sc_core::sc_out< bool > s_aximm_bvalid;
sc_core::sc_in< bool > s_aximm_bready;
sc_core::sc_in< bool > s_aximm_wlast;
sc_core::sc_out< bool > s_aximm_rlast;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_bresp;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_bid;
sc_core::sc_in< sc_dt::sc_bv<32> > s_aximm_araddr;
sc_core::sc_in< bool > s_aximm_arvalid;
sc_core::sc_out< bool > s_aximm_arready;
sc_core::sc_in< sc_dt::sc_bv<8> > s_aximm_arlen;
sc_core::sc_in< sc_dt::sc_bv<3> > s_aximm_arsize;
sc_core::sc_in< sc_dt::sc_bv<2> > s_aximm_arburst;
sc_core::sc_in< sc_dt::sc_bv<1> > s_aximm_arid;
sc_core::sc_out< sc_dt::sc_bv<64> > s_aximm_rdata;
sc_core::sc_out< sc_dt::sc_bv<1> > s_aximm_rid;
sc_core::sc_out< sc_dt::sc_bv<2> > s_aximm_rresp;
sc_core::sc_out< bool > s_aximm_rvalid;
sc_core::sc_in< bool > s_aximm_rready;
protected:
virtual void before_end_of_elaboration();
private:
xtlm::xaximm_pin2xtlm_t<64,32,1,1,1,1,1,1>* mp_S_AXIMM_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIFIFO_transactor;
xtlm::xaximm_pin2xtlm_t<32,8,1,1,1,1,1,1>* mp_S_AXIHUB_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_0_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_1_transactor;
xtlm::xaxis_pin2xtlm_t<8,1,8,8,1,1>* mp_TRACE_IN_2_transactor;
};
#endif // MTI_SYSTEMC
#endif // IP_PFM_DYNAMIC_DPA_HUB_0_H_
| [
"[email protected]"
] | |
a18771888be22ca00b09b939bededafd9607380f | feb0734de5a56dc19eb45bd91dbf44483f679cd5 | /Tools/src/plotter2D.cc | 7f419661cb596802bb3b2c523d7054661d6c7329 | [] | no_license | harbali/TtZAnalysis | 9782d79a2bab214b6dac797b026cbd3ef1c1031a | df918707fec73bed3c3deb886538a98571bfaf2c | refs/heads/master | 2020-05-29T11:52:02.670015 | 2014-11-04T09:59:31 | 2014-11-04T09:59:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,446 | cc | /*
* plotter2D.cc
*
* Created on: Oct 27, 2014
* Author: kiesej
*/
#include "../interface/plotter2D.h"
#include "TColor.h"
namespace ztop{
plotter2D::plotter2D(): plotterBase(),dividebybinarea_(false){
}
plotter2D::~plotter2D(){}
void plotter2D::setPlot(const container2D* c, bool dividebybinarea){
plot_=*c;
if(dividebybinarea)
dividebybinarea_=true;
else
dividebybinarea_=false;
}
void plotter2D::preparePad(){
TVirtualPad* c=getPad();
c->Clear();
c->SetLogy(0);
c->SetBottomMargin(0.15);
c->SetLeftMargin(0.15);
c->SetRightMargin(0.2);
}
void plotter2D::drawPlots(){
const Int_t NRGBs = 5;
const Int_t NCont = 255;
Double_t stops[NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
Double_t red[NRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 };
Double_t green[NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
Double_t blue[NRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 };
TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont);
gStyle->SetNumberContours(NCont);
//applt style
// STC!!!
TH2D* h=addObject(plot_.getTH2D(plot_.getName(),dividebybinarea_,false));
h->GetZaxis()->SetTitleSize(0.06);
h->GetZaxis()->SetLabelSize(0.05);
h->GetYaxis()->SetTitleSize(0.06);
h->GetYaxis()->SetLabelSize(0.05);
h->GetXaxis()->SetTitleSize(0.06);
h->GetXaxis()->SetLabelSize(0.05);
h->GetZaxis()->SetRangeUser(-1,1);
h->Draw("colz");
}
// void drawTextBoxes();
void plotter2D::drawLegends(){
}
}
| [
"[email protected]"
] | |
b0079fa52e79f9dc6a7b89f02628afd29be2c4c0 | c08ef583d7700f734502aa624276046a0f55e63b | /Ficheros/Messages.h | 724980a26fb0c2db1aaaeecf3b3184d1cd967273 | [] | no_license | jorgerodrigar/Asteroids | 9c86577f6a0e6acacf4c314669d37c71699ce7cc | 85c6d15a5c59961be896e57fde314c58098df983 | refs/heads/master | 2021-01-25T11:48:18.492270 | 2018-04-17T11:05:19 | 2018-04-17T11:05:19 | 123,428,212 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 1,731 | h | #ifndef MESSAGES_H_
#define MESSAGES_H_
#include "Asteroid.h"
#include "Bullet.h"
#include "checkML.h"
class Fighter;
enum MessageId {
BULLET_ASTROID_COLLISION,
BULLET_FIGHTER_COLLISION,
ASTROID_FIGHTER_COLLISION,
FIGHTER_SHOOT,
GAME_OVER,
ROUND_START,
ROUND_OVER,
BULLET_CREATED,
NO_MORE_ATROIDS,
//BADGES
BADGE_ON,//9, a partir de aqui comienzan los mensajes de badges (GameManager.h)
BADGE_OFF,//al aņadir mas badges, poner sus mensajes debajo de estos de la misma manera (On, Off, On, Off, ...)
SUPER_ON,//y actualizar NUMBADGES de GameManader.h
SUPER_OFF,
MULTI_ON,
MULTI_OFF
};
struct Message {
Message(MessageId id) :
id_(id) {
}
MessageId id_;
};
struct BulletAstroidCollision: Message {
BulletAstroidCollision(Bullet* bullet, Asteroid* astroid) :
Message(BULLET_ASTROID_COLLISION), bullet_(bullet), astroid_(
astroid) {
}
Bullet* bullet_;
Asteroid* astroid_;
};
struct BulletFighterCollision: Message {
BulletFighterCollision(Bullet* bullet, Fighter* fighter) :
Message(BULLET_FIGHTER_COLLISION), bullet_(bullet), fighter_(
fighter) {
}
Bullet* bullet_;
Fighter* fighter_;
};
struct AstroidFighterCollision: Message {
AstroidFighterCollision(Asteroid* astroid, Fighter* fighter) :
Message(ASTROID_FIGHTER_COLLISION), astroid_(astroid), fighter_(
fighter) {
}
Asteroid* astroid_;
Fighter* fighter_;
};
struct FighterIsShooting: Message {
FighterIsShooting(Fighter* fighter, Vector2D bulletPosition,
Vector2D bulletVelocity) :
Message(FIGHTER_SHOOT), fighter_(fighter), bulletPosition_(
bulletPosition), bulletVelocity_(bulletVelocity) {
}
Fighter* fighter_;
Vector2D bulletPosition_;
Vector2D bulletVelocity_;
};
#endif /* MESSAGES_H_ */
| [
"[email protected]"
] | |
1b8153725f5e99fbe966777155f6f5c74b491b68 | 879fb3581f03b5c17dd90c68b45751712fbcd671 | /lib/c_cpp/c_palette.cpp | 0a5e1ad0f45772ed9c9b6c8421d3ce1d061db888 | [] | no_license | ivilab/kjb | 9f970e1ce16188f72f0edb34394e474ca83a9f2b | 238be8bc3c9018d4365741e56310067a52b715f9 | refs/heads/master | 2020-06-14T07:33:17.166805 | 2019-07-30T16:47:29 | 2019-07-30T16:47:29 | 194,946,614 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,240 | cpp | /**
* @file
* @brief Implementation for class Palette, giving you random colors.
* @author Andrew Predoehl
*/
/*
* $Id: c_palette.cpp 19803 2015-09-20 04:05:01Z predoehl $
*/
#include <l/l_def.h>
#include <l_cpp/l_exception.h>
#include <i_cpp/i_hsv.h>
#include <m_cpp/m_vector.h>
#include <c_cpp/c_palette.h>
/**
* Set this to 1 or 0 to to turn on or off the behavior of generating extra
* colors, then throwing away (one of) too-close color pairs, until we've
* thinned out the herd enough.
*
* Advice: leave it zero, which runs faster and produces better results IMO.
*/
#define GEN_EXTRA_THEN_CULL 0
#if GEN_EXTRA_THEN_CULL
/*
* which space to use to determine color similarity?
* My opinion: they work about equally well and HSY is faster.
*/
#define HSY_SPACE 1 /**< flag: 1=use Hue, Sat., Luma space for distance */
#define LAB_SPACE 0 /**< flag: 0=do not use LAB* space for color distance*/
#endif
#if LAB_SPACE
#include <c/c_colour_space.h>
#endif
#include <gsl_cpp/gsl_qrng.h>
#include <vector>
#include <ostream>
namespace
{
/**
* @brief makes distinct 24-bit colors
*
* The colors are only a little bit random -- actually the goal is to make
* them all as distinguishable as possible from one another. So, there should
* not be two very similar greens, or purply-blues, or anything. All should
* be as distinct as we can make them. If you randomly choose RGB, the
* result will NOT have this property for, say, 100 colors. In fact it is very
* difficult to make 100 pairwise-distinctive colors (495 comparisons).
*
* The original motivation was to serve as "colorist" for a visualization of
* superpixel segmentation, where each superpixel gets painted a different
* color. We want always to see clearly the boundary between superpixels.
* The color value itself tells us nothing, we only care that it is distinct
* from its neighbors.
*
* This class is lazy. Color 0 is 100% transparent (alpha==0) when the class
* has (lazily) not built itself yet. After that it goes opaque (alpha==255).
*/
class ColorPick
{
std::vector< kjb::PixelRGBA > colors;
void build(); // complicated overkill method, but it makes good colors.
bool is_not_yet_built() const
{
return 0 == colors[ 0 ].extra.alpha; // check for the sentinel value
}
public:
ColorPick( size_t num_colors )
: colors( num_colors )
{
if ( 0 == num_colors )
{
KJB_THROW_2(kjb::Illegal_argument,"Palette size must be positive");
}
colors[ 0 ].extra.alpha = 0; // sentinel: class hasn't built itself
}
void swap( ColorPick& other )
{
colors.swap( other.colors );
}
kjb::PixelRGBA operator[]( size_t index )
{
if ( is_not_yet_built() ) build();
return colors.at( index );
}
size_t size() const
{
return colors.size();
}
void debug_print( std::ostream& os ) const;
};
#if LAB_SPACE
void convert_to_lab( const kjb::PixelRGBA cc, kjb_c::Vector** lab )
{
kjb::Vector vv( 3 );
vv.at( 0 ) = cc.r;
vv.at( 1 ) = cc.g;
vv.at( 2 ) = cc.b;
ETX( kjb_c::convert_vector_rgb_to_lab( lab, vv.get_c_vector(), 00 ) );
}
double lab_dist2( const kjb::PixelRGBA& c1, const kjb::PixelRGBA& c2 )
{
kjb_c::Vector *v1 = 00, *v2 = 00;
convert_to_lab( c1, &v1 );
convert_to_lab( c2, &v2 );
kjb::Vector w1( v1 ), w2( v2 );
w1 -= w2;
return w1.magnitude_squared();
}
#endif
void ColorPick::build()
{
// If already built, return. Now say that with a double negative:
if ( ! is_not_yet_built() ) return;
#if GEN_EXTRA_THEN_CULL
const float EXTRA_FACTOR = 1.5; // you can twiddle this ad libidum
#else
const size_t EXTRA_FACTOR = 1;
#endif
const size_t K_CLUST = colors.size(),
EXTRA_CLUST = K_CLUST * EXTRA_FACTOR;
std::vector< kjb::PixelRGBA > precolors;
precolors.reserve( EXTRA_CLUST );
//////// THIS ONE WORKS PRETTY WELL, even if EXTRA_FACTOR is 1.
const double ISOSCALE = 2.0, Y_TOO_DARK = 0.15;
kjb::Vector v( 3 );
for ( kjb::Gsl_Qrng_Sobol qq( 3 ); precolors.size() < EXTRA_CLUST; )
{
v = qq.read(); // elements 0,1,2 correspond to H,S,Y.
/*
* Sadly (I guess) the Y value, luminance, must lie in range [0,1] and
* the isotropic scaling below is going to blow a lot of them out of
* range. We humanely reject them now to save them from future
* suffering, and also to skip an unnecessary for loop.
* Also we reject values that are too dark, i.e., luminance below 0.15.
*/
if ( v[ 2 ] < Y_TOO_DARK / ISOSCALE || 1.0 / ISOSCALE < v[ 2 ] )
{
continue; // reject: Y component is too dark or too bright
}
/*
* QRNG values are not random; there's something "funny" about their
* spacing; so to preserve their "funny" distances we must scale them
* by the same factor in each dimension.
* We have to scale up by 2 because H values and S values range from -1
* to +1.
*/
v *= ISOSCALE;
// Translate the H and S components from range [0,2] to [-1,1].
v[ 0 ] -= 1; // H component
v[ 1 ] -= 1; // S component
/*
* Test whether that point lies within the HSY polyhedron; the
* polyhedron is not a cuboid, so not every point in
* [-1,1] x [-1,1] x [0,1] is a valid HSY value. So there is more
* rejection going on at this step. The function's return value tells
* you whether v is valid, and if so, the RGB values are to be found in
* Pixel p.
*/
kjb_c::Pixel p;
p.extra.alpha = 255; // doesn't get set by function, Valgrind is sad.
int rc = get_pixel_from_hsluma_space( v, &p );
if ( EXIT_SUCCESS == rc )
{
precolors.push_back( p );
}
}
#if GEN_EXTRA_THEN_CULL
// HEURISTIC FIXUP: First thin it out. Then look for splitups.
std::vector< double > dist2;
std::vector< size_t > winner;
kjb::Vector vk;
/* This loop could be "while(true)" since the break below will exit us.
* However, I am afraid of putting an infinite loop in the code for real.
*/
for ( int irrelevant = 0; irrelevant < 9999; ++irrelevant )
{
using kjb_c::kjb_rand;
// compute nearest color to each color
dist2.assign( precolors.size(), DBL_MAX );
winner.assign( precolors.size(), precolors.size() );
for ( size_t kix = 0; kix < precolors.size(); ++kix )
{
vk = hsluma_space( precolors[ kix ] );
for ( size_t jix = 0; jix < precolors.size(); ++jix )
{
if ( kix == jix ) continue;
#if HSY_SPACE
// Compute spacing using HSY
double d2 = ( vk
- hsluma_space( precolors[ jix ] ) ).magnitude_squared();
#endif
#if LAB_SPACE
// Compute spacing using L*a*b
double d2 = lab_dist2( precolors[ kix ], precolors[ jix ] );
#endif
if ( d2 < dist2[ kix ] )
{
dist2[ kix ] = d2;
winner[ kix ] = jix;
}
}
KJB(ASSERT( winner[ kix ] < precolors.size() ));
}
// find which 2 colors are most cramped, least cramped
size_t mcix = 0, lcix = 0;
for ( size_t kix = 0; kix < precolors.size(); ++kix )
{
if ( dist2[ kix ] < dist2[ mcix ] )
{
mcix = kix;
}
if ( dist2[ kix ] > dist2[ lcix ] )
{
lcix = kix;
}
}
KJB(ASSERT( dist2.at( mcix ) < dist2.at( lcix ) || mcix == lcix ));
KJB(ASSERT( dist2[ mcix ] == dist2[ winner[ mcix ] ] ));
// Cut one of the two most cramped colors if we have surplus colors
if ( K_CLUST < precolors.size() )
{
size_t cutix = kjb_rand() < 0.5 ? mcix : winner[ mcix ];
precolors[ cutix ] = precolors.back();
precolors.pop_back();
}
// No more cuts, but can one of the cramped pair move in with you guys?
else if ( dist2[ mcix ] * 4 < dist2[ lcix ] )
{
size_t shiftix = kjb_rand() < 0.5 ? mcix : winner[ mcix ];
precolors[ shiftix ] =
precolors[ lcix ] + precolors[ winner[ lcix ] ];
precolors[ shiftix ] *= 0.5;
}
else
{
break; // <--- the usual exit condition
}
}
#endif
KJB(ASSERT( K_CLUST == precolors.size() ));
std::copy( precolors.begin(), precolors.end(), colors.begin() );
}
void ColorPick::debug_print( std::ostream& os ) const
{
if ( is_not_yet_built() )
{
os << "Palette is lazy, and has not computed itself yet.\n";
}
else
{
for ( size_t kix = 0; kix < colors.size(); ++kix )
{
int rrr = static_cast< int >( colors[ kix ].r ),
ggg = static_cast< int >( colors[ kix ].g ),
bbb = static_cast< int >( colors[ kix ].b );
os << rrr << ' ' << ggg << ' ' << bbb << '\n';
}
}
}
} // anonymous namespace
namespace kjb {
Palette::Palette( size_t size )
{
my_pal.reserve( size );
if ( 2 == size )
{
// Severe black and white for a two-color palette
my_pal.push_back( kjb::PixelRGBA( 0, 0, 0 ) );
my_pal.push_back( kjb::PixelRGBA( 250, 250, 250 ) );
}
else
{
// Random colors for a multicolor palette -- this works nicely
ColorPick cp( size );
for ( size_t kix = 0; kix < size; ++kix )
{
my_pal.push_back( cp[ kix ] );
}
}
}
/**
* @brief compute a new color mixed from old.
* @return a color mixed from the palette components
* @param weights_d vector of weights, sum of 1, big means more of that color.
* @throws Illegal_argument if 'weights' is the wrong length.
* @throws Illegal_argument if 'weights' does not sum to unity.
*
* Less cryptically: the input vector of doubles must be the same size as
* the palette size(), and the values in the vector are treated as weights;
* they must be normalized to sum to unity (or pretty close). The output
* pixel is a weighted sum of the palette colors, using these weights.
*/
kjb::PixelRGBA Palette::weighted_sum( const kjb::Vector& weights_d ) const
{
if (weights_d.get_length() != (int)size() ) KJB_THROW(Illegal_argument);
float sum = 0;
for ( int iii = 0; iii < weights_d.get_length(); ++iii )
{
sum += weights_d( iii );
}
const float EPS = 1.0E-4f;
if (fabs( sum - 1.0f ) > EPS ) KJB_THROW(Illegal_argument);
kjb::PixelRGBA weighted_sum( 0, 0, 0 );
std::vector< kjb::PixelRGBA >::const_iterator ppal = my_pal.begin();
for ( int iii = 0; iii < weights_d.get_length(); ++iii )
{
weighted_sum += *ppal++ * weights_d( iii );
}
return weighted_sum.ow_clamp(); // alpha channel surely needs clamping
}
} // namespace kjb
| [
"[email protected]"
] | |
1f91407e3d189b425db3c2a98aa44460605c2835 | 7857e0bdefe000612519e8ff3670dd07c7b00184 | /pointers/bubbel_sort_func_ptr.cpp | f1358a977a104421b238acd014d363d596b7bb60 | [] | no_license | sleebapaul/udacity-cpp | 8c13f69e0e3be7f30f7afbb9d93f30607257422c | ff1648e2cbcf07d80fa94868c4fdded4a3d87f32 | refs/heads/master | 2021-05-12T09:30:52.758287 | 2018-04-15T12:42:47 | 2018-04-15T12:42:47 | 117,320,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | cpp | #include <iostream>
using namespace std;
// What if we need to change the sorting order at times?
// We will need to modify the swap operation accordingly
// We can use a callback for this.
// Callback function should compare two integers, should return 1
// if the first element has higher rank, 0 if elements are equal,
// and -1 if second element has higher rank
// Callback function
int compare(int a, int b)
{
if (a > b)
{
return 1;
}
else
{
return 0;
}
}
// We can write multiple callbacks for our needs
void bubbleSort(int *A, int n, int (*compare)(int, int))
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - 1; j++)
{
if (compare(A[j], A[j + 1]) > 0) // Swap operation
{
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
}
int main()
{
int i, A[] = {3, 2, 1, 5, 6, 4};
bubbleSort(A, 6, compare);
for (int i = 0; i < 6; i++)
{
cout << A[i] << "\n";
}
} | [
"[email protected]"
] | |
4868106c2e87c051311e5308b6fc3514dbb7abb3 | a53f8d2859477f837c81f943c81ceed56cf37238 | /RTL/Component/Include/IFXBitStreamCompressedX.h | 163904ace14532b73dfce5070a13257356913c76 | [
"Apache-2.0"
] | permissive | ClinicalGraphics/u3d | ffd062630cde8c27a0792370c158966d51182d4d | a2dc4bf9ead5400939f698d5834b7c5d43dbf42a | refs/heads/master | 2023-04-13T17:25:55.126360 | 2023-03-30T07:34:12 | 2023-03-31T18:20:43 | 61,121,064 | 11 | 5 | Apache-2.0 | 2023-09-01T04:23:31 | 2016-06-14T12:29:13 | C++ | UTF-8 | C++ | false | false | 2,106 | h | //***************************************************************************
//
// Copyright (c) 2000 - 2006 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//***************************************************************************
/**
@file IFXBitStreamCompressedX.h
Declaration of IFXBitStreamCompressedX exception-based interface.
*/
#ifndef IFXBITSTREAMCOMPRESSEDX_H__
#define IFXBITSTREAMCOMPRESSEDX_H__
#include "IFXBitStreamX.h"
// {8F594846-C215-48d5-A28C-D1CE3B8F0A48}
IFXDEFINE_GUID(IID_IFXBitStreamCompressedX,
0x8f594846, 0xc215, 0x48d5, 0xa2, 0x8c, 0xd1, 0xce, 0x3b, 0x8f, 0xa, 0x48);
/**
Declaration of IFXBitStreamCompressedX exception-based interface.
*/
class IFXBitStreamCompressedX : public IFXBitStreamX
{
public:
/** Bit writing method. */
virtual void IFXAPI WriteCompressedU32X(U32 Context, U32 Value) = 0;
/** Bit writing method. */
virtual void IFXAPI WriteCompressedU16X(U32 Context, U16 Value) = 0;
/** Bit writing method. */
virtual void IFXAPI WriteCompressedU8X(U32 Context, U8 Value) = 0;
/** Bit reading method. */
virtual void IFXAPI ReadCompressedU32X(U32 Context, U32& rValue) = 0;
/** Bit reading method. */
virtual void IFXAPI ReadCompressedU16X(U32 Context, U16& rValue) = 0;
/** Bit reading method. */
virtual void IFXAPI ReadCompressedU8X(U32 Context, U8& rValue) = 0;
/** Set no compression mode. */
virtual void IFXAPI SetNoCompressionMode(BOOL isNoCompression) = 0;
/** Compression context management method. */
virtual void IFXAPI SetElephantX(U32 uElephant) = 0;
};
#endif
| [
"[email protected]"
] | |
b3d8c3d5ede46a20f43926ae34149c12db23f92c | c867c92d512a468e65d416b9185c01a5d48bf4f8 | /Unit 2/2.7.5.cpp | 40f171bec48ab924b7521b50d7363540d0041980 | [] | no_license | fredgnr/C-Primer-Plus | 8209f3dacd7697d7296fff12070ce3f362f47358 | 72bf4c0a596adf4d744404f1111e29de9535ee03 | refs/heads/master | 2021-04-28T04:41:58.767180 | 2018-08-01T02:15:41 | 2018-08-01T02:15:41 | 122,166,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | cpp | #include<iostream>
using namespace std;
double convert(double);
int main()
{
double degree;
cout << "Please enter a Celsius degree :";
cin >> degree;
cout << degree << " degrees Celsius is " << convert(degree) << " degrees Fahrenheit" << endl;
return 0;
}
double convert(double degrees)
{
return 1.8*degrees + 32;
} | [
"[email protected]"
] | |
fa0caded6794fde27240a530e7bcf932fc66e225 | 5d6b55bc07c39e110bcdae3081ef8555c3b323a6 | /Проект18/VptrMap.cpp | c3c1bc1842b064e0db7694dee52c480c815798e6 | [] | no_license | SergioKogut/Projects | 8cbe46937362ac0d838e8a1a08ac9d6372b77c9f | 5f2c274aa94498efddf2fafc00df938ce803875a | refs/heads/master | 2020-03-13T05:17:53.411627 | 2018-04-27T07:54:50 | 2018-04-27T07:54:50 | 130,980,668 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,954 | cpp | #include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
int Add(int, int);
int Sub(int, int);
int Div(int, int);
int Mult(int, int);
class menu
{
public:
menu();// по замовчуванню
menu(map<string, int(*)(int, int)>MapPtrFunc2);// параметризований
menu(pair<string, int(*)(int, int)>);// параметризований
~menu();
void Show();
private:
map<string, int(*)(int, int)>MapPtrFunc1;
int a = 4;
int b = 3;
};
void menu::Show()
{
for (auto it = MapPtrFunc1.begin(); it != MapPtrFunc1.end(); ++it)
{
cout << it->first << ": " << it->second(a, b) << endl;
}
}
menu::menu()
{
MapPtrFunc1 = { { "Add", Add }, { "Sub", Sub }, { "Mult", Mult }, { "Div", Div } };
}
menu::menu(map<string, int(*)(int, int)>MapPtrFunc2)
{
MapPtrFunc1 = MapPtrFunc2;
}
menu::menu(pair<string, int(*)(int, int)>a)
{
MapPtrFunc1.insert(a);
}
menu::~menu()
{
}
class Game
{
public:
void Run();
int Add1(int, int);
Game();
~Game();
private:
// pair<string, int(*)(int, int)> para = {"Add",Add1 };
menu Menu1({ "Add1",Add1 });
};
int Game::Add1(int, int)
{
return 5;
}
void Game::Run()
{
}
Game::Game()
{
}
Game::~Game()
{
}
double area(double R)
{
const double PI = 3.1415;
return PI * R * R;
}
int Add(int a,int b)
{
return a + b;
}
int Mult(int a, int b)
{
return a * b;
}
int Div(int a, int b)
{
return a / b;
}
int Sub(int a, int b)
{
return a - b;
}
void one()
{
cout << "Funk one" << endl;
}
void two()
{
cout << "Funk two" << endl;
}
int main()
{
void(*FunkPtr)();
FunkPtr = &two;
FunkPtr();
FunkPtr = &one;
FunkPtr();
//---------------------------------------------------------------------------------
double(*pfunc)(double); // переменная указатель на функцию
pfunc = area;
double r = 1.0;
cout << "for circle radius " << r << " Area = "
<< (*pfunc)(r) << endl;
int(*CalcPtr)(int, int);
int a;
int b;
cout << "Enter a:";
cin >> a;
cout << "Enter b:";
cin >> b;
CalcPtr=Mult;
cout << a << "*" << b << " = " << CalcPtr(a, b) << endl;
//------------------------vector-----------------------------------------------------
vector<int(*)(int, int)> VPtrFunc;
VPtrFunc.push_back(Add);
VPtrFunc.push_back(Sub);
VPtrFunc.push_back(Mult);
VPtrFunc.push_back(Div);
cout << a << "*" << b << " = " << VPtrFunc[2](a, b) << endl;
//------------------------------map---------------------------------------------------
map<string, int(*)(int, int)>MapPtrFunc = { { "Add", Add },{ "Sub", Sub },{ "Mult", Mult},{ "Div", Div } };
for (auto it = MapPtrFunc.begin(); it != MapPtrFunc.end(); ++it)
{
cout << it->first << ": " << it->second(a, b) << endl;
}
//--------------------class-----------------------------------------------------
cout << "Menu:" << endl;
//menu Menu1;
//menu Menu1(MapPtrFunc);
menu Menu1( {"Add", Add });
Menu1.Show();
return 0;
} | [
"[email protected]"
] | |
46f7bd667aebe277d8260aba0388cf220f895c24 | a9f678119a8ed6b852f30aa4c35ee8d75ee55c10 | /plusOne.cpp | 615571e63ec1b63518c447a57e5bbdf200a2d4d8 | [] | no_license | gaolu/Leetcode | 0ae73c04be1f1cb75b499d957ed24fde78684074 | 10d1091c20b1692d9a9fa91b41d23a1f8ba9424a | refs/heads/master | 2021-01-13T02:06:45.626985 | 2014-03-18T04:26:39 | 2014-03-18T04:26:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int carry = 0;
vector<int> afterPlus (digits.size() + 1, 0);
if(digits.size() == 0)
return afterPlus;
reverse(digits.begin(), digits.end());
int length = digits.size();
int i = 1;
int firstSum = digits[0] + 1 + carry;
carry = firstSum / 10;
int firstDigit = firstSum % 10;
afterPlus[0] = firstDigit;
while(i < length){
int localSum = digits[i] + carry;
carry = localSum / 10;
int localDigit = localSum % 10;
afterPlus[i] = localDigit;
i++;
}
if(carry > 0)
afterPlus[afterPlus.size() - 1] = carry;
if(afterPlus[afterPlus.size() - 1] == 0)
afterPlus.resize(afterPlus.size() - 1);
reverse(afterPlus.begin(), afterPlus.end());
return afterPlus;
}
};
| [
"[email protected]"
] | |
0a98661075d71c0a7a8ed900c0f8b199b40e77bb | 0dc0142475fe40a67750bf878f51c86e9ccb0bf6 | /server_game/Peer.hpp | 56d984ce55c65794d3c302c9a12a506347273aba | [] | no_license | denghe/xxlib_cpp | 780bad8d7972ecda6c0f8dd097828dc5a52e0bca | 14ca77f06a18893148b213239f804aaf855afc1d | refs/heads/master | 2020-04-02T02:23:11.104266 | 2020-01-03T08:53:22 | 2020-01-03T08:53:22 | 153,906,209 | 6 | 4 | null | 2019-05-23T14:21:15 | 2018-10-20T13:03:46 | C | GB18030 | C++ | false | false | 4,807 | hpp | inline int Peer::ReceiveRequest(int const& serial, xx::Object_s&& msg) noexcept {
switch (msg->GetTypeId()) {
case xx::TypeId_v<PKG::Generic::Ping>: {
// 重置超时
if (auto && p = player_w.lock()) {
p->ResetTimeoutFrameNumber();
}
else {
ResetTimeoutMS(10000);
}
// 携带收到的数据回发
pkgPong->ticks = xx::As<PKG::Generic::Ping>(msg)->ticks;
auto r = SendResponse(serial, pkgPong);
Flush();
return r;
}
default:
xx::CoutTN("recv unhandled request: ", msg);
return -1;
}
}
inline int Peer::ReceivePush(xx::Object_s&& msg) noexcept {
// 有玩家 bind
if (auto && player = player_w.lock()) {
// 已绑定连接
// 将初步判定合法的消息放入容器, 待到适当时机读出使用, 模拟输入
auto&& typeId = msg->GetTypeId();
if (typeId != xx::TypeId_v<PKG::Client_CatchFish::Bet>
&& typeId != xx::TypeId_v<PKG::Client_CatchFish::Fire>
&& typeId != xx::TypeId_v<PKG::Client_CatchFish::Hit>) {
xx::CoutTN("binded recv unhandled push: ", msg);
return -1;
}
player->recvs.push_back(msg);
return 0;
}
// 没玩家 bind
else {
if (!isFirstPackage) return -1;
isFirstPackage = false;
// 匿名连接. 只接受 Enter
switch (msg->GetTypeId()) {
case xx::TypeId_v<PKG::Client_CatchFish::Enter>: {
auto&& o = xx::As<PKG::Client_CatchFish::Enter>(msg);
// 引用到公共配置方便使用
auto&& cfg = *catchFish->cfg;
// 判断要进入哪个 scene (当前就一个, 略 )
auto&& scene = *catchFish->scene;
// 如果有传入玩家 id, 就试着定位, 走断线重连逻辑
while (o->token) {
// 用 token 查找玩家
for(auto&& p : catchFish->players) {
if (p->token == *o->token) {
assert(p->peer != shared_from_this());
// 踢掉原有连接( 可能性: 客户端很久没收到推送, 自己 redial, 而 server 并没发现断线 )
p->Kick(GetIP(), " reconnect");
// 玩家与连接绑定
player_w = p;
p->peer = xx::As<Peer>(shared_from_this());
// 放入本帧进入游戏的列表, 以便下发完整同步
scene.frameEnters.Add(&*p);
// 设置超时
p->ResetTimeoutFrameNumber();
// 返回成功
return 0;
}
}
break;
}
// 看看有没有位置. 如果没有就直接断开
PKG::CatchFish::Sits sit;
if (!scene.freeSits->TryPop(sit)) {
xx::CoutTN("no more free sit: ", msg);
return -2;
}
// 构建玩家上下文( 模拟已从db读到了数据 )
auto&& player = xx::Make<PKG::CatchFish::Player>();
xx::MakeTo(player->cannons);
player->scene = &scene;
player->id = ++::service->playerAutoId;
xx::Append(player->token, xx::Guid(true));
player->sit = sit;
player->pos = scene.cfg->sitPositons->At((int)sit);
player->coin = 100000;
xx::MakeTo(player->nickname, "player_" + std::to_string(player->id));
player->autoFire = false;
player->autoIncId = 0;
player->autoLock = false;
player->avatar_id = 0;
player->noMoney = false;
xx::MakeTo(player->weapons);
// 构建初始炮台
auto&& cannonCfgId = 0;
switch (cannonCfgId) {
case 0: {
auto&& cannonCfg = cfg.cannons->At(cannonCfgId);
auto&& cannon = xx::Make<PKG::CatchFish::Cannon>();
cannon->angle = float(cannonCfg->angle);
xx::MakeTo(cannon->bullets);
cannon->cfg = &*cannonCfg;
cannon->cfgId = cannonCfgId;
cannon->coin = 1;
cannon->id = (int)player->cannons->len;
cannon->player = &*player;
cannon->pos = cfg.sitPositons->At((int)sit);
cannon->quantity = cannonCfg->quantity;
cannon->scene = &scene;
cannon->fireCD = 0;
player->cannons->Add(cannon);
break;
}
// todo: more cannon types here
default:
xx::CoutTN("unbind recv unhandled cannon cfg id: ", msg);
return -3;
}
// 将玩家放入相应容器
catchFish->players.Add(player);
scene.players->Add(player);
scene.frameEnters.Add(&*player);
// 玩家与连接绑定
player_w = player;
player->peer = xx::As<Peer>(shared_from_this());
// 构建玩家进入通知并放入帧同步下发事件集合待发
{
auto&& enter = xx::Make<PKG::CatchFish::Events::Enter>();
enter->avatar_id = player->avatar_id;
enter->cannonCfgId = player->cannons->At(0)->cfgId;
enter->cannonCoin = player->cannons->At(0)->coin;
enter->coin = player->coin;
enter->nickname = player->nickname;
enter->noMoney = player->noMoney;
enter->playerId = player->id;
enter->sit = player->sit;
scene.frameEvents->events->Add(enter);
}
// 设置超时
player->ResetTimeoutFrameNumber();
// 成功退出
xx::CoutTN(GetIP(), " player enter. ", player);
break;
}
default:
xx::CoutTN("unbind recv unhandled push: ", msg);
return -4;
}
}
return 0;
}
| [
"[email protected]"
] | |
6ed28d778ada41181f04188563b6aa961d89fad1 | 41bcb9b91a7607c795a6b6946c753968c8aa506e | /Tunneling.cpp | 55aa5f1a3009168f60d43d2a0f49c632fa185513 | [] | no_license | WhoiisThisGuy/Pacman | 92645d33e1140cfd6c0224d7de425d20c0750176 | 7b61e918c7e55bb9ff42771a7f8bc083c6a60d59 | refs/heads/master | 2023-03-04T02:12:46.912587 | 2021-02-09T18:11:44 | 2021-02-09T18:11:44 | 232,933,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | cpp | #include "Tunneling.h"
#include "Chase.h"
#include "GhostGameOver.h"
#include "Map.h"
#include "Frighten.h"
Tunneling::Tunneling(Ghost* ghostToHandle) {
ghost = ghostToHandle;
ghost->currentState = eFrighten;
Init();
}
void Tunneling::Update(const float& dt)
{
float stateTime = stateClock.getElapsedTime().asSeconds();
if (Game_Over || Game_Win) {
Exit(eGameOver);
return;
}
if (paused)
return;
//if eaten exit here
if (ghost->collideWithPacman()) {
Game_Over = true;
paused = true;
Exit(eGameOver);
return;
}
ghost->animation.Update(dt, ghost->ANIMATIONSWITCHTIME);
ghost->UpdateTexture();
(this->*fToUpdate)(dt); //Function pointers FIGHTIN'!
return; //Return immediatley
}
void Tunneling::TunnelingIn(const float& dt)
{
if (ghost->tunnelTeleport()) {
fToUpdate = &Tunneling::TunnelingOut;
}
ghost->moveOn(dt);
}
void Tunneling::TunnelingOut(const float& dt)
{
if (ghost->turningPointReached())
{
Exit(eChase);
return;
}
ghost->moveOn(dt);
}
void Tunneling::Init()
{
fToUpdate = &Tunneling::TunnelingIn;
stateClock.restart().asSeconds();
ghost->speed = levelValues[LEVELNUMBER][5];
ghost->currentState = eTunneling;
ghost->animation.firstImage = ghost->getDirectionForAnimation();
ghost->animation.imageToSet.x = ghost->animation.firstImage;
ghost->animation.imageToSet.y = ghost->rowForAnimation;
ghost->animation.lastImage = ghost->animation.firstImage+1;
}
void Tunneling::Exit(const GhostState& state)
{
ghost->inTunnel = false;
switch (state) {
case eChase:
ghost->setState(new Chase(ghost));
break;
case eGameOver:
ghost->setState(new GhostGameOver(ghost));
break;
}
} | [
"[email protected]"
] | |
ff546321c0fdad85c1b8b6f7572efb3ad906d58b | bd9b79f6abab92782c003373f066eb12ed551a64 | /Source/TopDown/StrategySpectatorPawn.h | 9b5c6fb76ad86216db546243bcffcb47102a2681 | [] | no_license | nessessary/ue4_rts_demo | 85476466f83584a7a5434fd11fe05e06e94d34bd | d352dc49520298fabadbbe6925a9a3a0d6ff4e74 | refs/heads/master | 2021-01-21T06:39:03.817020 | 2017-04-20T01:54:10 | 2017-04-20T01:54:10 | 82,869,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,269 | h | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
//#include "StrategyTypes.h"
#include "GameFramework/SpectatorPawn.h"
#include "StrategySpectatorPawn.generated.h"
//@TODO: Write a comment here
UCLASS(Blueprintable, BlueprintType)
class AStrategySpectatorPawn : public ASpectatorPawn
{
GENERATED_UCLASS_BODY()
// Begin ADefaultPawn interface
/** event call on move forward input */
virtual void MoveForward(float Val) override;
/** event call on strafe right input */
virtual void MoveRight(float Val) override;
/** Add custom key bindings */
virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override;
// End ADefaultPawn interface
// The camera component for this camera
private:
UPROPERTY(Category = CameraActor, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
class UStrategyCameraComponent* StrategyCameraComponent;
UPROPERTY(EditAnywhere)
USpringArmComponent* OurCameraSpringArm;
public:
/** Handles the mouse scrolling down. */
void OnMouseScrollUp();
/** Handles the mouse scrolling up. */
void OnMouseScrollDown();
/* Returns a pointer to the strategy camera component the pawn has. */
UStrategyCameraComponent* GetStrategyCameraComponent();
};
| [
"[email protected]"
] | |
446c872e4512579f1184b2dae1de88a5733d2ac2 | b385c1b2cce4c295172a6e3eebbeb2ffa83791ce | /client/GameLogger/gameloggerui.cpp | d2ed49e51c215830b4a14b62daefb0eecf7bff33 | [
"MIT"
] | permissive | shanhija/game-logger | ff583d72d451d6b999ed1d84d028f4447d23d576 | 7638c084c531483d8cca203954c279770cb2ecc8 | refs/heads/master | 2021-05-27T14:10:16.960345 | 2014-06-29T17:49:16 | 2014-06-29T17:49:16 | 18,464,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,341 | cpp | #include "gameloggerui.h"
#include "ui_gameloggerui.h"
#include <QMessageBox>
#include <QDialog>
#include <QAction>
#include <QMenu>
#include <QCloseEvent>
#include "common.h"
#include "settings.h"
GameLoggerUI::GameLoggerUI(QWidget *parent) :
QDialog(parent),
ui(new Ui::GameLoggerUI)
{
ui->setupUi(this);
createTrayIcon();
}
void GameLoggerUI::setup(QString serverUrl, QString player) {
QDEBUG("[GameLoggerUI::setup()] called with url %s and player %s", qPrintable(serverUrl), qPrintable(player));
gameLogger = new GameLogger(serverUrl, player);
connect(gameLogger, SIGNAL(error(QString)), this, SLOT(exitError(QString)));
connect(gameLogger, SIGNAL(settingsReady(Settings*)), this, SLOT(settingsReady(Settings*)));
connect(gameLogger, SIGNAL(updated(int,Session*)), this, SLOT(logsUpdated(int,Session*)));
}
GameLoggerUI::~GameLoggerUI()
{
delete quitter;
delete gameLogger;
delete ui;
}
void GameLoggerUI::startQuitting()
{
// Send close information to gameLogger
gameLogger->notifyClose();
quitter = new QTimer(this);
quitter->setSingleShot(true);
quitter->setInterval(1000);
quitter->start();
connect(quitter, SIGNAL(timeout()), qApp, SLOT(quit()));
}
void GameLoggerUI::settingsReady(Settings *settings)
{
// Show game data
for (QHash<QString, GameInfo*>::iterator iter = settings->games.begin(); iter != settings->games.end(); ++iter) {
QStringList lst;
lst.append(iter.key());
lst.append(((GameInfo *)iter.value())->completeName);
ui->gameTree->addTopLevelItem(new QTreeWidgetItem(lst));
}
// Show general settings
ui->serverURLLabel->setText(settings->serverUrl);
ui->userLabel->setText(settings->player);
ui->suppressLabel->setText((settings->supressUpdates)?"true":"false");
}
void GameLoggerUI::logsUpdated(int apm, Session *session)
{
ui->apmLabel->setText(QString::number(apm));
if (session) {
ui->gameNameLabel->setText(session->gameName);
ui->durationLabel->setText("Started at " + session->begun.toString("d.M.yyyy h:mm:ss") + ", played for " + QTime(0,0).addSecs(session->begun.secsTo(session->updated)).toString("h:mm:ss"));
} else {
ui->gameNameLabel->setText("<no active game>");
ui->durationLabel->setText("");
}
}
void GameLoggerUI::createTrayIcon() {
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(QIcon(":/images/thumbs_up_48.png"));
trayIcon->show();
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayClicked(QSystemTrayIcon::ActivationReason)));
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), this, SLOT(startQuitting()));
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(quitAction);
trayIcon->setContextMenu(trayIconMenu);
}
void GameLoggerUI::trayClicked(QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger) {
showNormal();
}
}
void GameLoggerUI::closeEvent(QCloseEvent *event)
{
hide();
event->ignore();
}
void GameLoggerUI::exitError(QString error)
{
QDEBUG("[GameLoggerUI::exitError()] called with error %s", qPrintable(error));
/* QMessageBox msg;
msg.setText(error);
msg.exec();
qApp->quit();*/
}
| [
"[email protected]"
] | |
156d0a5bc74bdec7600a059887630ad76cb5035c | 6f100f69232c6597c3f9564acde9c303b2adf47d | /UVa Online Judge/12049 - Just Prune The List/main.cpp | f771f8b0530f51f12b16c684921dc0b3cda663f5 | [] | no_license | douglasbravimbraga/programming-contests | 43e1b6aaa5a3ef51f5815fed8cb9a607f4f334cc | 75e444977cc3ff701b7390b8de70c88f6b40c52f | refs/heads/master | 2023-07-20T07:58:53.145049 | 2021-08-01T12:48:23 | 2021-08-01T12:48:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
std::ios_base::sync_with_stdio(false);
int test_cases;
cin >> test_cases;
while (test_cases--) {
int n, m;
unordered_map<int, int> m1, m2;
unordered_set<int> s;
int temp;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> temp;
m1[temp]++;
s.insert(temp);
}
for (int i = 0; i < m; i++) {
cin >> temp;
m2[temp]++;
s.insert(temp);
}
int count = 0;
for (auto i : s) {
count += abs(m1[i] - m2[i]);
}
cout << count << endl;
}
return 0;
} | [
"[email protected]"
] | |
3c0ccf541ef9dcf471a1d582ac49cba3b5277650 | cf1a6032a8494c1416c88b8aec1f20bed9e8b9b6 | /Game Engine/ext/box2d/include/Common/b2StackAllocator.h | c88dbddb96994c3e6598e561ba3e1ef8324ef220 | [] | no_license | Wedeueis/Projetos | fd95b846188fc7a9638d1a488cd4b808dcd2ddce | e871eb59fc2a86f67e60d445055eceb93d1e155b | refs/heads/master | 2020-05-06T15:43:32.621065 | 2019-04-08T18:10:01 | 2019-04-08T18:10:01 | 180,205,398 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,729 | h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_STACK_ALLOCATOR_H
#define B2_STACK_ALLOCATOR_H
#include "../Common/b2Settings.h"
const int32 b2_stackSize = 100 * 1024; // 100k
const int32 b2_maxStackEntries = 32;
struct b2StackEntry
{
char* data;
int32 size;
bool usedMalloc;
};
// This is a stack allocator used for fast per step allocations.
// You must nest allocate/free pairs. The code will assert
// if you try to interleave multiple allocate/free pairs.
class b2StackAllocator
{
public:
b2StackAllocator();
~b2StackAllocator();
void* Allocate(int32 size);
void Free(void* p);
int32 GetMaxAllocation() const;
private:
char m_data[b2_stackSize];
int32 m_index;
int32 m_allocation;
int32 m_maxAllocation;
b2StackEntry m_entries[b2_maxStackEntries];
int32 m_entryCount;
};
#endif
| [
"[email protected]"
] | |
eafaa742b2ddceecd575dcd6fc22822f4ef468de | 954d216e92924a84fbd64452680bc58517ae53e8 | /source/apps/demos/nckDemo_Texture2D.h | 8c46a4d2c8296fc240681eec5b2f174aaa77cf14 | [
"MIT"
] | permissive | nczeroshift/nctoolkit | e18948691844a8657f8937d2d490eba1b522d548 | c9f0be533843d52036ec45200512ac54c1faeb11 | refs/heads/master | 2021-01-17T07:25:02.626447 | 2020-06-10T14:07:03 | 2020-06-10T14:07:03 | 47,587,062 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 869 | h |
/**
* NCtoolKit © 2007-2017 Luís F.Loureiro, under zlib software license.
* https://github.com/nczeroshift/nctoolkit
*/
#ifndef _NCK_DEMO_TEXTURE_2D_H_
#define _NCK_DEMO_TEXTURE_2D_H_
#include "../nckDemo.h"
class Demo_Texture2D : public Demo{
public:
Demo_Texture2D(Core::Window * wnd, Graph::Device * dev);
~Demo_Texture2D();
void Load();
void Render(float dt);
void UpdateWndEvents();
std::vector<std::string> GetKeywords();
std::string GetDescription();
private:
Graph::Texture2D * m_R16Tex;
Graph::Texture2D * m_R32Tex;
Graph::Texture2D * m_RGBA16Tex;
Graph::Texture2D * m_RGBA32Tex;
Graph::Texture2D * m_RGBTex;
Graph::Texture2D * m_RGBATex;
Graph::Texture * m_TextureJpg;
Graph::Texture * m_TexturePng;
float time;
};
Demo * CreateDemo_Texture2D(Core::Window * wnd, Graph::Device * dev);
#endif
| [
"[email protected]"
] | |
e1a7e648e8e23ba718f4ccbb8c3fd14e909e71d3 | e44987791f76a56730c0c94b88d4bc09f18cd716 | /Dynamic Programming/LengthofLongestSubsequence.cpp | 3525bb29020c93ce0d967d274d7e466d783cecac | [] | no_license | segsev/Interviewbit | 11b77c5a707726b029a8badd772cbc4a7b7671d8 | c6f9d071284b7d73803fa1085278abdef5c05dec | refs/heads/master | 2020-07-09T04:31:45.553344 | 2019-09-23T07:41:26 | 2019-09-23T07:41:26 | 203,877,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | cpp | int Solution::longestSubsequenceLength(const vector<int> &A) {
int n = A.size();
if(n == 0) {
return 0;
}
vector<int> dpLeft(n,1);
vector<int> dpRight(n,1);
for(int i = 1; i < n; i++) {
for(int j = 0; j < i; j++) {
if(A[j] < A[i]) {
dpLeft[i] = max(dpLeft[i], 1+dpLeft[j]);
}
}
}
for(int i = n-2; i>= 0; i--) {
for(int j = n-1; j>i; j--) {
if(A[j] < A[i]) {
dpRight[i] = max(dpRight[i], 1+dpRight[j]);
}
}
}
int ans = INT_MIN;
for(int i = 0; i < n; i++) {
ans = max(ans, dpLeft[i] + dpRight[i]);
}
return ans-1;
}
| [
"[email protected]"
] | |
5d63804a18152970c51d8eed1a86bfc56840d344 | 9688ca06ad7d3207156054e8e38776b733ce33a4 | /test_17_08_18/p0008.cpp | 11587754cfc6765a07f1a56540ec4cc0dcb52214 | [] | no_license | swekiiz/Programming.in.th | b2ee9a781f1efe4280306ceacc5889c800617922 | 52568ad8bd971310e6abd695d9962aa9c5986d66 | refs/heads/master | 2022-12-06T19:07:40.101453 | 2020-08-31T20:14:08 | 2020-08-31T20:14:08 | 189,581,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 81 | cpp | #include<cstdio>
main(){
int a,b;
scanf("%d %d",&a,&b);
printf("%d",2*b-a);
}
| [
"[email protected]"
] | |
a480faef1acef7f046c2cb9ff165067fee20b848 | 98f10c77b9932915eb9f37d9cf79a83094342444 | /URI/1445.cpp | fda6f9b9babf792268e30ecd7480a90b6ecc5848 | [] | no_license | lucianovr/competitive-programming | b5ba55a5055e486862c0c8b62e61c86e41b8f2b8 | bd95492bb8a14563603a5a2d74e3c1676a4a61e6 | refs/heads/master | 2022-09-10T04:54:07.417831 | 2020-05-28T00:33:36 | 2020-05-28T00:33:36 | 267,455,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | cpp | #include <map>
#include <stdio.h>
using namespace std;
struct CONVIDADOS {
int a, b;
} C[1002];
int main() {
map<int, int> M;
map<int, int>::iterator it;
int N, cont, i;
char lixo;
bool B;
while (scanf("%d", &N) && N) {
M.clear();
for (i = 0; i < N; i++) {
scanf("\n");
scanf("%c%d%c%d%c", &lixo, &C[i].a, &lixo, &C[i].b, &lixo);
M[C[i].a] = M[C[i].b] = false;
}
B = M[1] = true;
cont = 0;
while (B) {
B = false;
for (i = 0; i < N; i++) {
if (M[C[i].a] ^ M[C[i].b]) {
B = M[C[i].a] = M[C[i].b] = true;
cont++;
}
}
}
printf("%d\n", cont + 1);
}
return 0;
}
| [
"[email protected]"
] | |
c47ef43e72e7cf61eaf9eb2432bcdb817623d45c | 9cb3e1ca3586cee2523c528c8f8bb5f24a7926f1 | /user.h | 6f9867a11528673ff0eb8a0881dcc2c004a0385e | [] | no_license | sussanstha/LibraryMS | bc709028294d5b421ad4a898d0ec27018b1001d6 | 5282edb94af82fd404d6b2dfa280b7afb042a830 | refs/heads/main | 2023-04-02T03:47:54.382325 | 2020-12-18T06:11:39 | 2020-12-18T06:11:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | h | #ifndef USER_H
#define USER_H
#include<QString>
class user{
protected:
QString _id;
QString _name;
QString _password;
public:
QString id(){
return _id;
}
void new_id(QString new_id){
_id=new_id;
}
QString name(){
return _name;
}
void new_name(QString new_name){
_name=new_name;
}
QString password(){
return _password;
}
void new_password(QString new_password){
_password=new_password;
}
};
#endif // USER_H
| [
"[email protected]"
] | |
4380f0c1e910c5c090599950f255b26c55fbe9d7 | 1efccc5f7a3b725395c7c9fc3f63b64b4b99b546 | /MonsterChase/Engine/Src/Maths/Point3D.h | 271a57f8b92855fc9229d240548347b1dc15d490 | [] | no_license | Rud156/Hailey | 4ea4b0a1eef5e556a893610ee67eb5ed35bb910c | 1ffb92933ff68b822cb15c4a14e0e2f47a601a74 | refs/heads/master | 2023-05-03T08:50:17.271610 | 2021-05-26T19:37:39 | 2021-05-26T19:37:39 | 214,330,307 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,551 | h | #pragma once
#include <ostream>
namespace Math
{
class Point2D;
class Point3D
{
private:
float _x;
float _y;
float _z;
public:
// Constructor
Point3D();
Point3D(float i_x, float i_y, float i_z);
Point3D(const Point3D& i_point3d);
Point3D(const Point2D& i_point2d, float i_z);
// Destructor
~Point3D();
// Getters
[[nodiscard]] inline float X() const;
[[nodiscard]] inline float Y() const;
[[nodiscard]] inline float Z() const;
// Static Operations
inline friend Point3D operator+(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline friend Point3D operator-(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline friend Point3D operator*(const Point3D& i_point3d, const float i_operation);
inline friend Point3D operator/(const Point3D& i_point3d, const float i_operation);
inline friend bool operator==(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline friend bool operator!=(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline friend Point3D operator-(const Point3D& i_point3d);
// Modifier Operations
Point3D operator+=(const Point3D& i_point3d);
Point3D operator-=(const Point3D& i_point3d);
Point3D operator*=(const float i_operation);
Point3D operator/=(const float i_operation);
inline friend std::ostream& operator<<(std::ostream& i_stream, const Point3D& i_point3d);
// Utility Methods
void set(const Point3D& i_point3d);
void set(float i_x, float i_y, float i_z);
void set(int i_x, int i_y, int i_z);
void setX(float i_x);
void setX(int i_x);
void setY(float i_y);
void setY(int i_y);
void setZ(float i_z);
void setZ(int i_z);
[[nodiscard]] inline bool isZero() const;
[[nodiscard]] inline float length() const;
[[nodiscard]] inline float lengthSq() const;
[[nodiscard]] inline Point3D copy() const;
inline Point3D normalize();
inline static Point3D normalize(const Point3D& i_point3d);
inline static Point3D Zero();
inline static float dot(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline static Point3D cross(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline static float angle(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline static float distance(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline static float distanceSq(const Point3D& i_point3d_1, const Point3D& i_point3d_2);
inline static Point3D lerp(const Point3D& i_point3d_1, const Point3D& i_point3d_2, float i_progress);
};
}
#include "Point3D_Inl.h"
| [
"[email protected]"
] | |
f7157d5902b4a5043290b4d29f2457bff7b41cce | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/skia/include/core/SkDocument.h | 7f293f149defab11696fe373715827d4a8d6c2cf | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 7,481 | h | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkDocument_DEFINED
#define SkDocument_DEFINED
#include "SkBitmap.h"
#include "SkPicture.h"
#include "SkRect.h"
#include "SkRefCnt.h"
#include "SkString.h"
#include "SkTime.h"
class SkCanvas;
class SkWStream;
#ifdef SK_BUILD_FOR_WIN
struct IXpsOMObjectFactory;
#endif
/** SK_ScalarDefaultDPI is 72 DPI.
*/
#define SK_ScalarDefaultRasterDPI 72.0f
/**
* High-level API for creating a document-based canvas. To use..
*
* 1. Create a document, specifying a stream to store the output.
* 2. For each "page" of content:
* a. canvas = doc->beginPage(...)
* b. draw_my_content(canvas);
* c. doc->endPage();
* 3. Close the document with doc->close().
*/
class SK_API SkDocument : public SkRefCnt {
public:
struct OptionalTimestamp {
SkTime::DateTime fDateTime;
bool fEnabled;
OptionalTimestamp() : fEnabled(false) {}
};
/**
* Optional metadata to be passed into the PDF factory function.
*/
struct PDFMetadata {
/**
* The document's title.
*/
SkString fTitle;
/**
* The name of the person who created the document.
*/
SkString fAuthor;
/**
* The subject of the document.
*/
SkString fSubject;
/**
* Keywords associated with the document. Commas may be used
* to delineate keywords within the string.
*/
SkString fKeywords;
/**
* If the document was converted to PDF from another format,
* the name of the conforming product that created the
* original document from which it was converted.
*/
SkString fCreator;
/**
* The product that is converting this document to PDF.
*
* Leave fProducer empty to get the default, correct value.
*/
SkString fProducer;
/**
* The date and time the document was created.
*/
OptionalTimestamp fCreation;
/**
* The date and time the document was most recently modified.
*/
OptionalTimestamp fModified;
/** The DPI (pixels-per-inch) at which features without
* native PDF support will be rasterized (e.g. draw image
* with perspective, draw text with perspective, ...) A
* larger DPI would create a PDF that reflects the
* original intent with better fidelity, but it can make
* for larger PDF files too, which would use more memory
* while rendering, and it would be slower to be processed
* or sent online or to printer.
*/
SkScalar fRasterDPI = SK_ScalarDefaultRasterDPI;
/** If true, include XMP metadata, a document UUID, and sRGB output intent information.
* This adds length to the document and makes it non-reproducable, but are necessary
* features for PDF/A-2b conformance
*/
bool fPDFA = false;
/**
* Encoding quality controls the trade-off between size and quality. By default this is
* set to 101 percent, which corresponds to lossless encoding. If this value is set to
* a value <= 100, and the image is opaque, it will be encoded (using JPEG) with that
* quality setting.
*/
int fEncodingQuality = 101;
};
/**
* Create a PDF-backed document, writing the results into a
* SkWStream.
*
* PDF pages are sized in point units. 1 pt == 1/72 inch == 127/360 mm.
*
* @param stream A PDF document will be written to this stream. The document may write
* to the stream at anytime during its lifetime, until either close() is
* called or the document is deleted.
* @param metadata a PDFmetadata object. Any fields may be left empty.
*
* @returns NULL if there is an error, otherwise a newly created PDF-backed SkDocument.
*/
static sk_sp<SkDocument> MakePDF(SkWStream* stream, const PDFMetadata& metadata);
static sk_sp<SkDocument> MakePDF(SkWStream* stream);
#ifdef SK_BUILD_FOR_WIN
/**
* Create a XPS-backed document, writing the results into the stream.
*
* @param stream A XPS document will be written to this stream. The
* document may write to the stream at anytime during its
* lifetime, until either close() or abort() are called or
* the document is deleted.
* @param xpsFactory A pointer to a COM XPS factory. Must be non-null.
* The document will take a ref to the factory. See
* dm/DMSrcSink.cpp for an example.
* @param dpi The DPI (pixels-per-inch) at which features without
* native XPS support will be rasterized (e.g. draw image
* with perspective, draw text with perspective, ...) A
* larger DPI would create a XPS that reflects the
* original intent with better fidelity, but it can make
* for larger XPS files too, which would use more memory
* while rendering, and it would be slower to be processed
* or sent online or to printer.
*
* @returns nullptr if XPS is not supported.
*/
static sk_sp<SkDocument> MakeXPS(SkWStream* stream,
IXpsOMObjectFactory* xpsFactory,
SkScalar dpi = SK_ScalarDefaultRasterDPI);
#endif
/**
* Begin a new page for the document, returning the canvas that will draw
* into the page. The document owns this canvas, and it will go out of
* scope when endPage() or close() is called, or the document is deleted.
*/
SkCanvas* beginPage(SkScalar width, SkScalar height, const SkRect* content = nullptr);
/**
* Call endPage() when the content for the current page has been drawn
* (into the canvas returned by beginPage()). After this call the canvas
* returned by beginPage() will be out-of-scope.
*/
void endPage();
/**
* Call close() when all pages have been drawn. This will close the file
* or stream holding the document's contents. After close() the document
* can no longer add new pages. Deleting the document will automatically
* call close() if need be.
*/
void close();
/**
* Call abort() to stop producing the document immediately.
* The stream output must be ignored, and should not be trusted.
*/
void abort();
protected:
SkDocument(SkWStream*);
// note: subclasses must call close() in their destructor, as the base class
// cannot do this for them.
virtual ~SkDocument();
virtual SkCanvas* onBeginPage(SkScalar width, SkScalar height) = 0;
virtual void onEndPage() = 0;
virtual void onClose(SkWStream*) = 0;
virtual void onAbort() = 0;
// Allows subclasses to write to the stream as pages are written.
SkWStream* getStream() { return fStream; }
enum State {
kBetweenPages_State,
kInPage_State,
kClosed_State
};
State getState() const { return fState; }
private:
SkWStream* fStream;
State fState;
typedef SkRefCnt INHERITED;
};
#endif
| [
"[email protected]"
] | |
f0054d195e4b6ee762f563a76884404865a9c564 | 10ecd7454a082e341eb60817341efa91d0c7fd0b | /SDK/BP_DecalGlow_Reverse_functions.cpp | 3a52c06a968245f04a0be9c72a5c6b325402e9d0 | [] | no_license | Blackstate/Sot-SDK | 1dba56354524572894f09ed27d653ae5f367d95b | cd73724ce9b46e3eb5b075c468427aa5040daf45 | refs/heads/main | 2023-04-10T07:26:10.255489 | 2021-04-23T01:39:08 | 2021-04-23T01:39:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,230 | cpp | // Name: SoT, Version: 2.1.0.1
#include "../SDK.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.StartGlowEffect
// (Public, BlueprintCallable, BlueprintEvent)
void ABP_DecalGlow_Reverse_C::StartGlowEffect()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.StartGlowEffect");
ABP_DecalGlow_Reverse_C_StartGlowEffect_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.StartReaction
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
bool ABP_DecalGlow_Reverse_C::StartReaction()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.StartReaction");
ABP_DecalGlow_Reverse_C_StartReaction_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.StopReaction
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
bool ABP_DecalGlow_Reverse_C::StopReaction()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.StopReaction");
ABP_DecalGlow_Reverse_C_StopReaction_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.CollectDecalMaterials
// (Public, BlueprintCallable, BlueprintEvent)
void ABP_DecalGlow_Reverse_C::CollectDecalMaterials()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.CollectDecalMaterials");
ABP_DecalGlow_Reverse_C_CollectDecalMaterials_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_DecalGlow_Reverse_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.UserConstructionScript");
ABP_DecalGlow_Reverse_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.ReceiveBeginPlay
// (Event, Public, BlueprintEvent)
void ABP_DecalGlow_Reverse_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.ReceiveBeginPlay");
ABP_DecalGlow_Reverse_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.ExecuteUbergraph_BP_DecalGlow_Reverse
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_DecalGlow_Reverse_C::ExecuteUbergraph_BP_DecalGlow_Reverse(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_DecalGlow_Reverse.BP_DecalGlow_Reverse_C.ExecuteUbergraph_BP_DecalGlow_Reverse");
ABP_DecalGlow_Reverse_C_ExecuteUbergraph_BP_DecalGlow_Reverse_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
1066c2b84b4f0b2fa6c546168cf8928d0aaaecd6 | a02d4b3c879c047082ccc295607d6ec8d1130039 | /UE4-Plugins/Plugins/MiliBlueprintLibrary/Source/MiliBlueprintLibrary/Public/MiliBlueprintLibrary.h | 1908c00bae2c55e3e91d786850991cefdd458c5d | [
"Apache-2.0"
] | permissive | iceprincefounder/selected-sources | 4fa97e439248d1b4bd9e6e59d0f80a7c33752761 | b225c529e02009b5f44bfb2891ef8f039b9a6d80 | refs/heads/master | 2022-05-22T03:24:45.329292 | 2022-03-13T09:22:12 | 2022-03-13T09:22:12 | 149,724,714 | 17 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 298 | h | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "ModuleManager.h"
class FMiliBlueprintLibraryModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
}; | [
"[email protected]"
] | |
d3b7b7d486d16b186fec92aab8c7f394bf6106ff | ec68c973b7cd3821dd70ed6787497a0f808e18e1 | /Cpp/SDK/Widget_QuestNotification_classes.h | d27b19d8e14ac17ac60891c5470c9573a8e19269 | [] | no_license | Hengle/zRemnant-SDK | 05be5801567a8cf67e8b03c50010f590d4e2599d | be2d99fb54f44a09ca52abc5f898e665964a24cb | refs/heads/main | 2023-07-16T04:44:43.113226 | 2021-08-27T14:26:40 | 2021-08-27T14:26:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | h | #pragma once
// Name: Remnant, Version: 1.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass Widget_QuestNotification.Widget_QuestNotification_C
// 0x0000
class UWidget_QuestNotification_C : public UWidget_UserWidget_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass Widget_QuestNotification.Widget_QuestNotification_C");
return ptr;
}
void GetZoneQuest();
void UpdateQuestPinning();
void IsValidQuest();
void ObjectiveSuccess();
void InitQuests();
void QuestSuccess();
void QuestComplete();
void FindWidgetForQuest();
void UpdateQuest();
void Construct();
void OnQuestObjectivesUpdate();
void OnQuestCompleted();
void OnFinishTravel();
void OnBeginTravel();
void ExecuteUbergraph_Widget_QuestNotification();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
44cb6d12c956f047100f9eabec86e927a75b0637 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetsrv/iis/svcs/staxcore/mailmsg/lib/cmmrcpts.cpp | de4d7a95ef29056a09fc3e21a77c738927724fe4 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 57,841 | cpp | /*++
Copyright (c) 1998 Microsoft Corporation
Module Name:
cmmrcpts.cpp
Abstract:
This module contains the implementation of the recipient list class
Author:
Keith Lau ([email protected])
Revision History:
keithlau 03/10/98 created
--*/
#define WIN32_LEAN_AND_MEAN 1
#include "atq.h"
#include "stddef.h"
#include "dbgtrace.h"
#include "signatur.h"
#include "cmmtypes.h"
#include "cmailmsg.h"
// =================================================================
// Private Definitions
//
// Define a structure describing a domain in the stream
typedef struct _DOMAIN_TABLE_ENTRY
{
DWORD dwStartingIndex;
DWORD dwCount;
FLAT_ADDRESS faOffsetToName;
DWORD dwNameLength;
DWORD dwNextDomain;
} DOMAIN_TABLE_ENTRY, *LPDOMAIN_TABLE_ENTRY;
// Define an extended info structure
typedef struct _EXTENDED_INFO
{
DWORD dwDomainCount;
DWORD dwTotalSizeIncludingThisStruct;
} EXTENDED_INFO, *LPEXTENDED_INFO;
// The following is the list of default address types
PROP_ID rgDefaultAddressTypes[MAX_COLLISION_HASH_KEYS] =
{
IMMPID_RP_ADDRESS_SMTP, // The first address type will be used for domain grouping
IMMPID_RP_ADDRESS_X400,
IMMPID_RP_ADDRESS_X500,
IMMPID_RP_LEGACY_EX_DN,
IMMPID_RP_ADDRESS_OTHER
};
// =================================================================
// Static declarations
//
// Recipients table instance info for CMailMsgRecipientsAdd instantiation
const PROPERTY_TABLE_INSTANCE CMailMsgRecipientsAdd::s_DefaultInstance =
{
RECIPIENTS_PTABLE_INSTANCE_SIGNATURE_VALID,
INVALID_FLAT_ADDRESS,
RECIPIENTS_PROPERTY_TABLE_FRAGMENT_SIZE,
RECIPIENTS_PROPERTY_ITEM_BITS,
RECIPIENTS_PROPERTY_ITEM_SIZE,
RECIPIENTS_PROPERTY_ITEMS,
INVALID_FLAT_ADDRESS
};
//
// Well-known per-recipient properties
//
INTERNAL_PROPERTY_ITEM
*const CMailMsgRecipientsPropertyBase::s_pWellKnownProperties = NULL;
const DWORD CMailMsgRecipientsPropertyBase::s_dwWellKnownProperties = 0;
// =================================================================
// Compare function
//
HRESULT CMailMsgRecipientsPropertyBase::CompareProperty(
LPVOID pvPropKey,
LPPROPERTY_ITEM pItem
)
{
if (*(PROP_ID *)pvPropKey == ((LPRECIPIENT_PROPERTY_ITEM)pItem)->idProp)
return(S_OK);
return(STG_E_UNKNOWN);
}
// =================================================================
// Inline code for special properties
//
#include "accessor.inl"
// =================================================================
// Implementation of CMailMsgRecipientsPropertyBase
//
HRESULT CMailMsgRecipientsPropertyBase::PutProperty(
CBlockManager *pBlockManager,
LPRECIPIENTS_PROPERTY_ITEM pItem,
DWORD dwPropID,
DWORD cbLength,
LPBYTE pbValue
)
{
HRESULT hrRes = S_OK;
RECIPIENT_PROPERTY_ITEM piRcptItem;
if (!pBlockManager || !pItem || !pbValue) return E_POINTER;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsPropertyBase::PutProperty");
// Instantiate a property table for the recipient properties
CPropertyTable ptProperties(
PTT_PROPERTY_TABLE,
RECIPIENT_PTABLE_INSTANCE_SIGNATURE_VALID,
pBlockManager,
&(pItem->ptiInstanceInfo),
CMailMsgRecipientsPropertyBase::CompareProperty,
CMailMsgRecipientsPropertyBase::s_pWellKnownProperties,
CMailMsgRecipientsPropertyBase::s_dwWellKnownProperties
);
// Put the recipient property
piRcptItem.idProp = dwPropID;
hrRes = ptProperties.PutProperty(
(LPVOID)&dwPropID,
(LPPROPERTY_ITEM)&piRcptItem,
cbLength,
pbValue);
DebugTrace((LPARAM)this,
"PutProperty: Prop ID = %u, HRESULT = %08x",
dwPropID, hrRes);
TraceFunctLeave();
return(hrRes);
}
HRESULT CMailMsgRecipientsPropertyBase::GetProperty(
CBlockManager *pBlockManager,
LPRECIPIENTS_PROPERTY_ITEM pItem,
DWORD dwPropID,
DWORD cbLength,
DWORD *pcbLength,
LPBYTE pbValue
)
{
HRESULT hrRes = S_OK;
RECIPIENT_PROPERTY_ITEM piRcptItem;
if (!pBlockManager || !pItem || !pcbLength || !pbValue) return E_POINTER;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsPropertyBase::GetProperty");
// Instantiate a property table for the recipient properties
CPropertyTable ptProperties(
PTT_PROPERTY_TABLE,
RECIPIENT_PTABLE_INSTANCE_SIGNATURE_VALID,
pBlockManager,
&(pItem->ptiInstanceInfo),
CMailMsgRecipientsPropertyBase::CompareProperty,
CMailMsgRecipientsPropertyBase::s_pWellKnownProperties,
CMailMsgRecipientsPropertyBase::s_dwWellKnownProperties
);
// Get the recipient property using an atomic operation
hrRes = ptProperties.GetPropertyItemAndValue(
(LPVOID)&dwPropID,
(LPPROPERTY_ITEM)&piRcptItem,
cbLength,
pcbLength,
pbValue);
DebugTrace((LPARAM)this,
"GetPropertyItemAndValue: Prop ID = %u, HRESULT = %08x",
dwPropID, hrRes);
TraceFunctLeave();
return(hrRes);
}
// =================================================================
// Implementation of CMailMsgRecipients
//
CMailMsgRecipients::CMailMsgRecipients(
CBlockManager *pBlockManager,
LPPROPERTY_TABLE_INSTANCE pInstanceInfo
)
:
m_SpecialPropertyTable(&g_SpecialRecipientsPropertyTable)
{
_ASSERT(pBlockManager);
_ASSERT(pInstanceInfo);
m_pBlockManager = pBlockManager;
m_pInstanceInfo = pInstanceInfo;
m_ulRefCount = 0;
m_dwDomainCount = 0;
m_pStream = NULL;
m_fGlobalCommitDone = FALSE;
}
CMailMsgRecipients::~CMailMsgRecipients()
{
}
HRESULT CMailMsgRecipients::SetStream(
IMailMsgPropertyStream *pStream
)
{
// The stream can be NULL for all we know
m_pStream = pStream;
return(S_OK);
}
HRESULT CMailMsgRecipients::SetCommitState(
BOOL fGlobalCommitDone
)
{
m_fGlobalCommitDone = fGlobalCommitDone;
return(S_OK);
}
HRESULT CMailMsgRecipients::QueryInterface(
REFIID iid,
void **ppvObject
)
{
if (iid == IID_IUnknown)
{
// Return our identity
*ppvObject = (IUnknown *)(IMailMsgRecipients *)this;
AddRef();
}
else if (iid == IID_IMailMsgRecipients)
{
// Return the recipient list interface
*ppvObject = (IMailMsgRecipients *)this;
AddRef();
}
else if (iid == IID_IMailMsgRecipientsBase)
{
// Return the base recipients interface
*ppvObject = (IMailMsgRecipientsBase *)this;
AddRef();
}
else if (iid == IID_IMailMsgPropertyReplication)
{
// Return the base recipients interface
*ppvObject = (IMailMsgPropertyReplication *)this;
AddRef();
}
else
return(E_NOINTERFACE);
return(S_OK);
}
ULONG CMailMsgRecipients::AddRef()
{
return(InterlockedIncrement(&m_ulRefCount));
}
ULONG CMailMsgRecipients::Release()
{
LONG lRefCount = InterlockedDecrement(&m_ulRefCount);
if (lRefCount == 0)
{
delete this;
}
return(lRefCount);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::Commit(
DWORD dwIndex,
IMailMsgNotify *pNotify
)
{
HRESULT hrRes = S_OK;
RECIPIENTS_PROPERTY_ITEM piItem;
FLAT_ADDRESS faOffset;
DWORD cTotalBlocksToWrite = 0;
DWORD cTotalBytesToWrite = 0;
_ASSERT(m_pBlockManager);
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::Commit");
// Make sure we have a content handle
hrRes = RestoreResourcesIfNecessary(FALSE, TRUE);
if (!SUCCEEDED(hrRes))
return(hrRes);
_ASSERT(m_pStream);
if (!m_pStream)
return(STG_E_INVALIDPARAMETER);
// Now, see if a global commit call is called [recently enough].
if (!m_fGlobalCommitDone)
return(E_FAIL);
// Get the recipient item first
{
CPropertyTableItem ptiItem(m_pBlockManager, m_pInstanceInfo);
hrRes = ptiItem.GetItemAtIndex(
dwIndex,
(LPPROPERTY_ITEM)&piItem,
&faOffset
);
DebugTrace((LPARAM)this,
"GetItemAtIndex: index = %u, HRESULT = %08x",
dwIndex, hrRes);
}
for (int fComputeBlockSizes = 1;
SUCCEEDED(hrRes) && fComputeBlockSizes >= 0;
fComputeBlockSizes--)
{
LPPROPERTY_TABLE_INSTANCE pInstance = &(piItem.ptiInstanceInfo);
CPropertyTableItem ptiItem(m_pBlockManager, pInstance);
if (fComputeBlockSizes) {
m_pStream->StartWriteBlocks((IMailMsgProperties *) this,
cTotalBlocksToWrite,
cTotalBytesToWrite);
}
// Write out the recipient item, this includes the instance
// info for the recipient property table
hrRes = m_pBlockManager->CommitDirtyBlocks(
faOffset,
sizeof(RECIPIENTS_PROPERTY_ITEM),
0,
m_pStream,
FALSE,
fComputeBlockSizes,
&cTotalBlocksToWrite,
&cTotalBytesToWrite,
pNotify);
if (SUCCEEDED(hrRes))
{
DWORD dwLeft;
DWORD dwLeftInFragment;
DWORD dwSizeRead;
FLAT_ADDRESS faFragment;
LPRECIPIENT_PROPERTY_ITEM pItem;
CBlockContext bcContext;
RECIPIENT_PROPERTY_TABLE_FRAGMENT ptfFragment;
// Commit the special properties
for (DWORD i = 0; i < MAX_COLLISION_HASH_KEYS; i++)
if (piItem.faNameOffset[i] != INVALID_FLAT_ADDRESS)
{
hrRes = m_pBlockManager->CommitDirtyBlocks(
piItem.faNameOffset[i],
piItem.dwNameLength[i],
0,
m_pStream,
FALSE,
fComputeBlockSizes,
&cTotalBlocksToWrite,
&cTotalBytesToWrite,
pNotify);
if (!SUCCEEDED(hrRes))
goto Cleanup;
}
// OK, now commit each property
dwLeft = pInstance->dwProperties;
faFragment = pInstance->faFirstFragment;
// $REVIEW(dbraun)
// WORKAROUND FOR IA64 FRE COMPILER BUG
//while (faFragment != INVALID_FLAT_ADDRESS)
while (TRUE)
{
if (faFragment == INVALID_FLAT_ADDRESS)
break;
// END WORKAROUND
// Make sure there are items to commit
_ASSERT(dwLeft);
// Commit the fragment
hrRes = m_pBlockManager->CommitDirtyBlocks(
faFragment,
sizeof(RECIPIENT_PROPERTY_TABLE_FRAGMENT),
0,
m_pStream,
FALSE,
fComputeBlockSizes,
&cTotalBlocksToWrite,
&cTotalBytesToWrite,
pNotify);
if (!SUCCEEDED(hrRes))
goto Cleanup;
// Load the fragment info to find the next hop
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&ptfFragment,
faFragment,
sizeof(RECIPIENT_PROPERTY_TABLE_FRAGMENT),
&dwSizeRead,
&bcContext);
if (!SUCCEEDED(hrRes))
goto Cleanup;
// Commit each property in the fragment
dwLeftInFragment = RECIPIENT_PROPERTY_ITEMS;
pItem = ptfFragment.rgpiItems;
while (dwLeft && dwLeftInFragment)
{
hrRes = m_pBlockManager->CommitDirtyBlocks(
pItem->piItem.faOffset,
pItem->piItem.dwSize,
0,
m_pStream,
FALSE,
fComputeBlockSizes,
&cTotalBlocksToWrite,
&cTotalBytesToWrite,
pNotify);
if (!SUCCEEDED(hrRes))
goto Cleanup;
pItem++;
dwLeftInFragment--;
dwLeft--;
}
// Next
faFragment = ptfFragment.ptfFragment.faNextFragment;
}
// No more fragments, make sure no more properties as well
_ASSERT(!dwLeft);
}
if (fComputeBlockSizes) {
m_pStream->EndWriteBlocks((IMailMsgProperties *) this);
}
}
Cleanup:
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::DomainCount(
DWORD *pdwCount
)
{
HRESULT hrRes = S_OK;
EXTENDED_INFO eiInfo;
DWORD dwSize;
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::DomainCount");
if (!pdwCount)
return(E_POINTER);
// Load up the extended info
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&eiInfo,
m_pInstanceInfo->faExtendedInfo,
sizeof(EXTENDED_INFO),
&dwSize,
NULL);
if (SUCCEEDED(hrRes))
*pdwCount = eiInfo.dwDomainCount;
else
*pdwCount = 0;
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::DomainItem(
DWORD dwIndex,
DWORD cchLength,
LPSTR pszDomain,
DWORD *pdwRecipientIndex,
DWORD *pdwRecipientCount
)
{
return(DomainItemEx(
dwIndex,
cchLength,
pszDomain,
pdwRecipientIndex,
pdwRecipientCount,
NULL));
}
HRESULT CMailMsgRecipients::DomainItemEx(
DWORD dwIndex,
DWORD cchLength,
LPSTR pszDomain,
DWORD *pdwRecipientIndex,
DWORD *pdwRecipientCount,
DWORD *pdwNextDomainIndex
)
{
HRESULT hrRes = S_OK;
EXTENDED_INFO eiInfo;
DWORD dwSize;
CBlockContext cbContext;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::DomainItemEx");
if (pdwRecipientIndex) *pdwRecipientIndex = 0;
if (pdwRecipientCount) *pdwRecipientCount = 0;
if (pdwNextDomainIndex) *pdwNextDomainIndex = 0;
if (pszDomain) *pszDomain = 0;
// Load up the extended info
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&eiInfo,
m_pInstanceInfo->faExtendedInfo,
sizeof(EXTENDED_INFO),
&dwSize,
&cbContext);
if (SUCCEEDED(hrRes))
{
if (dwIndex >= eiInfo.dwDomainCount)
hrRes = E_INVALIDARG;
else
{
FLAT_ADDRESS faOffset;
DOMAIN_TABLE_ENTRY dteDomain;
// Locate the record to load
faOffset = dwIndex * sizeof(DOMAIN_TABLE_ENTRY);
faOffset += (m_pInstanceInfo->faExtendedInfo + sizeof(EXTENDED_INFO));
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&dteDomain,
faOffset,
sizeof(DOMAIN_TABLE_ENTRY),
&dwSize,
&cbContext);
if (SUCCEEDED(hrRes))
{
// Return the starting index and count regardless
if (pdwRecipientIndex)
*pdwRecipientIndex = dteDomain.dwStartingIndex;
if (pdwRecipientCount)
*pdwRecipientCount = dteDomain.dwCount;
if (pdwNextDomainIndex)
*pdwNextDomainIndex = dteDomain.dwNextDomain;
if (pszDomain)
{
// Check length
if (dteDomain.dwNameLength > cchLength)
hrRes = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
else
{
// Load up the domain name
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)pszDomain,
dteDomain.faOffsetToName,
dteDomain.dwNameLength,
&dwSize,
&cbContext);
}
}
}
}
}
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::SetNextDomain(
DWORD dwDomainIndex,
DWORD dwNextDomainIndex,
DWORD dwFlags
)
{
HRESULT hrRes = S_OK;
EXTENDED_INFO eiInfo;
DWORD dwSize;
DWORD dwNextDomainIndexValue = dwNextDomainIndex;
CBlockContext cbContext;
CBlockContext cbNextContext;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::SetNextDomain");
// Input flags check - mikeswa 7/3/98
if (FLAG_OVERWRITE_EXISTING_LINKS & dwFlags)
{
if ((FLAG_FAIL_IF_NEXT_DOMAIN_LINKED | FLAG_FAIL_IF_SOURCE_DOMAIN_LINKED) & dwFlags)
{
hrRes = E_INVALIDARG;
goto Cleanup;
}
}
if (FLAG_SET_FIRST_DOMAIN & dwFlags)
{
//if this flag is set, we will terminate with this domain
dwNextDomainIndexValue = INVALID_DOMAIN_INDEX;
}
// Load up the extended info
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&eiInfo,
m_pInstanceInfo->faExtendedInfo,
sizeof(EXTENDED_INFO),
&dwSize,
&cbContext);
if (SUCCEEDED(hrRes))
{
if ((dwDomainIndex >= eiInfo.dwDomainCount) ||
(!(FLAG_SET_FIRST_DOMAIN & dwFlags) && //we only care about 2nd domain if setting it
(dwNextDomainIndex >= eiInfo.dwDomainCount)))
hrRes = E_INVALIDARG;
else
{
FLAT_ADDRESS faOffset;
FLAT_ADDRESS faNextOffset;
DWORD dwOriginalLink;
DWORD dwNextLink;
// Locate the offset to write
faOffset = (m_pInstanceInfo->faExtendedInfo + sizeof(EXTENDED_INFO));
faOffset += offsetof(DOMAIN_TABLE_ENTRY, dwNextDomain);
faNextOffset = faOffset + (dwNextDomainIndex * sizeof(DOMAIN_TABLE_ENTRY));
faOffset += dwDomainIndex * sizeof(DOMAIN_TABLE_ENTRY);
//we only care about the original domain if we aren't overwriting it
if (!((FLAG_OVERWRITE_EXISTING_LINKS | FLAG_SET_FIRST_DOMAIN) & dwFlags))
{
// Read the original Link's next link
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&dwOriginalLink,
faOffset,
sizeof(DWORD),
&dwSize,
&cbContext);
if (!SUCCEEDED(hrRes))
goto Cleanup;
// Observe the flags
if ((dwOriginalLink != INVALID_DOMAIN_INDEX) &&
(dwFlags & FLAG_FAIL_IF_SOURCE_DOMAIN_LINKED))
{
hrRes = E_FAIL;
goto Cleanup;
}
// Read the target Link's next link
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&dwNextLink,
faNextOffset,
sizeof(DWORD),
&dwSize,
&cbNextContext);
if (!SUCCEEDED(hrRes))
goto Cleanup;
// Observe the flags
// Also, if both the original and target domains are linked, we
// have no way of fixing these links so we have to fail if
// FLAG_OVERWRITE_EXISTING_LINKS is not specified
if ((dwNextLink != INVALID_DOMAIN_INDEX) &&
(
(dwFlags & FLAG_FAIL_IF_NEXT_DOMAIN_LINKED) ||
(dwOriginalLink != INVALID_DOMAIN_INDEX)
))
{
hrRes = E_FAIL;
goto Cleanup;
}
}
else
{
//we are overwriting exiting link information
dwNextLink = INVALID_DOMAIN_INDEX;
dwOriginalLink = INVALID_DOMAIN_INDEX;
}
// Write the source's next link
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)&dwNextDomainIndexValue,
faOffset,
sizeof(DWORD),
&dwSize,
&cbContext);
if (!SUCCEEDED(hrRes))
goto Cleanup;
// Hook'em up! (if there is a next link)
if (!(FLAG_SET_FIRST_DOMAIN & dwFlags))
{
if (dwOriginalLink != INVALID_DOMAIN_INDEX)
dwNextLink = dwOriginalLink;
if ((dwNextLink != INVALID_DOMAIN_INDEX) ||
(FLAG_OVERWRITE_EXISTING_LINKS & dwFlags))
{
// Write the next link's next link
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)&dwNextLink,
faNextOffset,
sizeof(DWORD),
&dwSize,
&cbNextContext);
}
}
}
}
Cleanup:
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::InitializeRecipientFilterContext(
LPRECIPIENT_FILTER_CONTEXT pContext,
DWORD dwStartingDomain,
DWORD dwFilterFlags,
DWORD dwFilterMask
)
{
HRESULT hrRes = S_OK;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::InitializeRecipientFilterContext");
if (!pContext)
return(E_POINTER);
// First, get the domain item ...
hrRes = DomainItemEx(
dwStartingDomain,
0,
NULL,
&(pContext->dwCurrentRecipientIndex),
&(pContext->dwRecipientsLeftInDomain),
&(pContext->dwNextDomain));
if (SUCCEEDED(hrRes))
{
pContext->dwCurrentDomain = dwStartingDomain;
pContext->dwFilterFlags = dwFilterFlags;
pContext->dwFilterMask = dwFilterMask;
}
else
pContext->dwCurrentDomain = INVALID_DOMAIN_INDEX;
TraceFunctLeaveEx((LPARAM)this);
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::TerminateRecipientFilterContext(
LPRECIPIENT_FILTER_CONTEXT pContext
)
{
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::TerminateRecipientFilterContext");
if (!pContext)
return(E_POINTER);
pContext->dwCurrentDomain = INVALID_DOMAIN_INDEX;
TraceFunctLeaveEx((LPARAM)this);
return(S_OK);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::GetNextRecipient(
LPRECIPIENT_FILTER_CONTEXT pContext,
DWORD *pdwRecipientIndex
)
{
HRESULT hrRes = E_FAIL;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::GetNextRecipient");
if (!pContext || !pdwRecipientIndex)
return(E_POINTER);
if (INVALID_DOMAIN_INDEX == pContext->dwCurrentDomain)
return(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
// Fetch the next recipient that matches the criteria
do
{
if (pContext->dwRecipientsLeftInDomain)
{
// This is easy, just return the index index
*pdwRecipientIndex = (pContext->dwCurrentRecipientIndex)++;
(pContext->dwRecipientsLeftInDomain)--;
DebugTrace((LPARAM)this, "Returning next recipient, index %u",
*pdwRecipientIndex);
hrRes = S_OK;
}
else
{
DWORD dwNextDomain;
DWORD dwStartingIndex;
DWORD dwRecipientCount;
// See if we have a next domain, we are done if not
if (pContext->dwNextDomain == INVALID_DOMAIN_INDEX)
{
DebugTrace((LPARAM)this, "No more domains, we are done");
hrRes = HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS);
break;
}
// Go on to the next domain
DebugTrace((LPARAM)this, "Loading next domain, index %u",
pContext->dwNextDomain);
hrRes = DomainItemEx(
pContext->dwNextDomain,
0,
NULL,
&dwStartingIndex,
&dwRecipientCount,
&dwNextDomain);
if (SUCCEEDED(hrRes))
{
// A domain with zero recipients is by definition not allowed
_ASSERT(dwRecipientCount);
*pdwRecipientIndex = dwStartingIndex++;
DebugTrace((LPARAM)this, "Returning first recipient, index %u",
*pdwRecipientIndex);
pContext->dwCurrentDomain = pContext->dwNextDomain;
pContext->dwCurrentRecipientIndex = dwStartingIndex;
pContext->dwRecipientsLeftInDomain = --dwRecipientCount;
pContext->dwNextDomain = dwNextDomain;
}
else
pContext->dwCurrentDomain = INVALID_DOMAIN_INDEX;
}
// Now check if the recipient flags match the criteria
if (SUCCEEDED(hrRes))
{
FLAT_ADDRESS faOffset;
DWORD dwFlags, dwSize;
// See if this is the one we want ...
faOffset = m_pInstanceInfo->faFirstFragment;
if (faOffset == INVALID_FLAT_ADDRESS)
{
hrRes = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
break;
}
faOffset += (sizeof(PROPERTY_TABLE_FRAGMENT) +
offsetof(RECIPIENTS_PROPERTY_ITEM, dwFlags) +
(sizeof(RECIPIENTS_PROPERTY_ITEM) * *pdwRecipientIndex)
);
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)&dwFlags,
faOffset,
sizeof(DWORD),
&dwSize,
NULL);
if (!SUCCEEDED(hrRes))
break;
// Compare the flags : we mask out the bits that we are interested in,
// then we will make sure the interested bits are a perfect match.
dwFlags &= pContext->dwFilterMask;
if (dwFlags ^ pContext->dwFilterFlags)
hrRes = E_FAIL;
DebugTrace((LPARAM)this, "Masked recipient flags %08x, required flags: %08x, %smatched",
dwFlags, pContext->dwFilterFlags,
(dwFlags == pContext->dwFilterFlags)?"":"not ");
}
} while (!SUCCEEDED(hrRes));
// Invalidate the context if we are done or we hit an error
if (!SUCCEEDED(hrRes))
pContext->dwCurrentDomain = INVALID_DOMAIN_INDEX;
TraceFunctLeaveEx((LPARAM)this);
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::AllocNewList(
IMailMsgRecipientsAdd **ppNewList
)
{
HRESULT hrRes = S_OK;
CMailMsgRecipientsAdd *pNewList;
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::AllocNewList");
if (!ppNewList)
return(E_POINTER);
pNewList = new CMailMsgRecipientsAdd(m_pBlockManager);
if (!pNewList)
hrRes = E_OUTOFMEMORY;
if (SUCCEEDED(hrRes))
{
// Get the correct interface
hrRes = pNewList->QueryInterface(
IID_IMailMsgRecipientsAdd,
(LPVOID *)ppNewList);
if (!SUCCEEDED(hrRes))
pNewList->Release();
}
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::WriteList(
IMailMsgRecipientsAdd *pNewList
)
{
HRESULT hrRes = S_OK;
CRecipientsHash *pHash;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::WriteList");
if (!pNewList)
return(E_POINTER);
// Get the underlying implementation
pHash = ((CMailMsgRecipientsAdd *)pNewList)->GetHashTable();
do
{
DWORD dwDomainNameSize;
DWORD dwRecipientNameSize;
DWORD dwRecipientCount;
DWORD dwDomainCount;
DWORD dwTotalSize;
DWORD dwSize;
FLAT_ADDRESS faBuffer;
FLAT_ADDRESS faFirstFragment;
FLAT_ADDRESS faDomainList;
FLAT_ADDRESS faRecipient;
FLAT_ADDRESS faStringTable;
// Have different contexts for fastest access
CBlockContext bcDomain;
CBlockContext bcRecipient;
CBlockContext bcString;
// This is a lengthy process since CMailMsgRecipientAdd will actually
// go in and build the entire domain list
hrRes = pHash->BuildDomainListFromHash((CMailMsgRecipientsAdd *)pNewList);
if (!SUCCEEDED(hrRes))
break;
// OK, now we have a domain list, then collect the memory requirements
pHash->GetDomainCount(&dwDomainCount);
pHash->GetDomainNameSize(&dwDomainNameSize);
pHash->GetRecipientCount(&dwRecipientCount);
pHash->GetRecipientNameSize(&dwRecipientNameSize);
m_dwDomainCount = dwDomainCount;
//
// The data will be laid out as follows:
//
// An EXTENDED_INFO structure
// dwDomainCount entries of DOMAIN_TABLE_ENTRY
// A single fragment of RECIPIENT_PROPERTY_TABLE_FRAGMENT with:
// dwRecipientCount entries of RECIPIENTS_PROPERTY_ITEM
// A flat string table for all the domain and recipient name strings
//
// Calculate all the memory needed
dwTotalSize = sizeof(EXTENDED_INFO) +
(sizeof(DOMAIN_TABLE_ENTRY) * dwDomainCount) +
sizeof(PROPERTY_TABLE_FRAGMENT) +
(sizeof(RECIPIENTS_PROPERTY_ITEM) * dwRecipientCount) +
dwDomainNameSize +
dwRecipientNameSize;
DebugTrace((LPARAM)this, "%u bytes required to write recipient list",
dwTotalSize);
// Allocate the memory
hrRes = m_pBlockManager->AllocateMemory(
dwTotalSize,
&faBuffer,
&dwSize,
NULL);
DebugTrace((LPARAM)this, "AllocateMemory: HRESULT = %08x", hrRes);
if (!SUCCEEDED(hrRes))
break;
_ASSERT(dwSize >= dwTotalSize);
// Fill in the info ... try to use the stack so that we minimize
// other memory overhead
{
EXTENDED_INFO eiInfo;
eiInfo.dwDomainCount = dwDomainCount;
eiInfo.dwTotalSizeIncludingThisStruct = dwTotalSize;
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)&eiInfo,
faBuffer,
sizeof(EXTENDED_INFO),
&dwSize,
&bcDomain);
DebugTrace((LPARAM)this, "WriteMemory: HRESULT = %08x", hrRes);
if (!SUCCEEDED(hrRes))
break;
}
// Set up all the pointers
faDomainList = faBuffer + sizeof(EXTENDED_INFO);
faRecipient = faDomainList +
(sizeof(DOMAIN_TABLE_ENTRY) * dwDomainCount);
faStringTable = faRecipient +
sizeof(PROPERTY_TABLE_FRAGMENT) +
(sizeof(RECIPIENTS_PROPERTY_ITEM) * dwRecipientCount);
// Build and write out the recipient table fragment
{
PROPERTY_TABLE_FRAGMENT ptfFragment;
ptfFragment.dwSignature = PROPERTY_FRAGMENT_SIGNATURE_VALID;
ptfFragment.faNextFragment = INVALID_FLAT_ADDRESS;
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)&ptfFragment,
faRecipient,
sizeof(PROPERTY_TABLE_FRAGMENT),
&dwSize,
&bcRecipient);
if (!SUCCEEDED(hrRes))
break;
// Mark this for later
faFirstFragment = faRecipient;
faRecipient += sizeof(PROPERTY_TABLE_FRAGMENT);
}
// Build the domain table
{
DOMAIN_TABLE_ENTRY dteEntry;
DOMAIN_ITEM_CONTEXT dicContext;
LPRECIPIENTS_PROPERTY_ITEM_EX pItemEx;
LPRECIPIENTS_PROPERTY_ITEM pItem;
DWORD dwCurrentDomain = 0;
DWORD dwCurrentIndex = 0;
DWORD dwCount;
DWORD dwLength;
LPDOMAIN_LIST_ENTRY pDomainListEntry;
BOOL fGetFirstDomain = FALSE;
hrRes = pHash->GetFirstDomain(
&dicContext,
&pItemEx,
&pDomainListEntry);
DebugTrace((LPARAM)this, "GetFirstDomain: HRESULT = %08x", hrRes);
fGetFirstDomain = TRUE;
while (SUCCEEDED(hrRes))
{
dwCount = 0;
// OK, process the domain by walking it's members
while (pItemEx)
{
DWORD dwCurrentName;
DWORD_PTR faStack[MAX_COLLISION_HASH_KEYS];
// Obtain the record in stream form
pItem = &(pItemEx->rpiRecipient);
for (dwCurrentName = 0;
dwCurrentName < MAX_COLLISION_HASH_KEYS;
dwCurrentName++)
{
// Store the pointers ...
faStack[dwCurrentName] = pItem->faNameOffset[dwCurrentName];
// Write out valid names
if (faStack[dwCurrentName] != (FLAT_ADDRESS)NULL)
{
// Write out the first name
dwLength = pItem->dwNameLength[dwCurrentName];
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)faStack[dwCurrentName],
faStringTable,
dwLength,
&dwSize,
&bcString);
if (!SUCCEEDED(hrRes))
break;
// Convert the pointer to an offset and bump the ptr
pItem->faNameOffset[dwCurrentName] = faStringTable;
faStringTable += dwLength;
}
else
{
// Name is not valid, so set it to invalid
pItem->faNameOffset[dwCurrentName] = INVALID_FLAT_ADDRESS;
}
}
// Finally, write out the recipient record
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)pItem,
faRecipient,
sizeof(RECIPIENTS_PROPERTY_ITEM),
&dwSize,
&bcRecipient);
if (!SUCCEEDED(hrRes))
break;
for (dwCurrentName = 0;
dwCurrentName < MAX_COLLISION_HASH_KEYS;
dwCurrentName++)
{
// Restore the pointers ...
pItem->faNameOffset[dwCurrentName] = (FLAT_ADDRESS) faStack[dwCurrentName];
}
// Bump the ptr
faRecipient += sizeof(RECIPIENTS_PROPERTY_ITEM);
// Do next item
dwCount++;
pItemEx = pItemEx->pNextInDomain;
}
// Don't continue if failed!
if (!SUCCEEDED(hrRes))
break;
// Write out the domain record
dwLength = pDomainListEntry->dwDomainNameLength;
dteEntry.dwStartingIndex = dwCurrentIndex;
dteEntry.dwCount = dwCount;
dteEntry.faOffsetToName = faStringTable;
dteEntry.dwNameLength = dwLength;
dteEntry.dwNextDomain = INVALID_DOMAIN_INDEX;
dwCurrentIndex += dwCount;
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)&dteEntry,
faDomainList,
sizeof(DOMAIN_TABLE_ENTRY),
&dwSize,
&bcDomain);
if (!SUCCEEDED(hrRes))
break;
// Bump the ptr
faDomainList += sizeof(DOMAIN_TABLE_ENTRY);
// Write out the domain name
hrRes = m_pBlockManager->WriteMemory(
(LPBYTE)pDomainListEntry->szDomainName,
faStringTable,
dwLength,
&dwSize,
&bcString);
if (!SUCCEEDED(hrRes))
break;
// Bump the ptr
faStringTable += dwLength;
// OKay, up the count and get the next domain
dwCurrentDomain++;
hrRes = pHash->GetNextDomain(
&dicContext,
&pItemEx,
&pDomainListEntry);
DebugTrace((LPARAM)this, "GetNextDomain: HRESULT = %08x", hrRes);
}
// Now, if everything is in order, we should have a failed
// HRESULT of HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS).
if (hrRes != HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS))
{
if (fGetFirstDomain) {
HRESULT hr = pHash->CloseDomainContext(&dicContext);
_ASSERT(SUCCEEDED(hr));
}
ErrorTrace((LPARAM)this, "Expecting ERROR_NO_MORE_ITEMS, got = %08x", hrRes);
} else {
hrRes = S_OK;
}
}// Stack frame
// OKay, we've come this far, now all we are left to do is to
// update our instance info structure to link to this new list
// Note this will be flushed when the master header is committed
dwSize = sizeof(PROPERTY_TABLE_FRAGMENT) +
(sizeof(RECIPIENTS_PROPERTY_ITEM) * dwRecipientCount);
// Hook up first fragment
m_pInstanceInfo->faFirstFragment = faFirstFragment;
// Update the fragment size
m_pInstanceInfo->dwFragmentSize = dwSize;
// Force to evaluate only 1 fragment
m_pInstanceInfo->dwItemBits = 31;
// Should not change, but for good measure
m_pInstanceInfo->dwItemSize = sizeof(RECIPIENTS_PROPERTY_ITEM);
// Properties = number of recipient records
m_pInstanceInfo->dwProperties = dwRecipientCount;
// Hook up to the EXTENDED_INFO struct
m_pInstanceInfo->faExtendedInfo = faBuffer;
} while (0);
// Update the commit state
if (SUCCEEDED(hrRes))
m_fGlobalCommitDone = FALSE;
TraceFunctLeave();
return(hrRes);
}
/***************************************************************************/
//
// Implementation of CMailMsgRecipients::CMailMsgRecipientsPropertyBase
//
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::Count(
DWORD *pdwCount
)
{
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::Count");
if (!pdwCount)
return(E_POINTER);
*pdwCount = m_pInstanceInfo->dwProperties;
TraceFunctLeave();
return(S_OK);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::Item(
DWORD dwIndex,
DWORD dwWhichName,
DWORD cchLength,
LPSTR pszName
)
{
HRESULT hrRes = S_OK;
RECIPIENTS_PROPERTY_ITEM piItem;
_ASSERT(m_pBlockManager);
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::Item");
if (!pszName)
return(E_POINTER);
// We know where the name is immediately
if (dwWhichName >= MAX_COLLISION_HASH_KEYS)
return(E_INVALIDARG);
// Get the recipient item first
{
CPropertyTableItem ptiItem(m_pBlockManager, m_pInstanceInfo);
hrRes = ptiItem.GetItemAtIndex(
dwIndex,
(LPPROPERTY_ITEM)&piItem
);
DebugTrace((LPARAM)this,
"GetItemAtIndex: index = %u, HRESULT = %08x",
dwIndex, hrRes);
}
if (SUCCEEDED(hrRes))
{
DWORD dwSizeToRead;
DWORD dwSize;
FLAT_ADDRESS faOffset;
dwSizeToRead = piItem.dwNameLength[dwWhichName];
faOffset = piItem.faNameOffset[dwWhichName];
if (faOffset == INVALID_FLAT_ADDRESS)
return(STG_E_UNKNOWN);
// See if we have enough buffer
if (cchLength < dwSizeToRead)
return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
// Issue the read
hrRes = m_pBlockManager->ReadMemory(
(LPBYTE)pszName,
faOffset,
dwSizeToRead,
&dwSize,
NULL);
}
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::PutProperty(
DWORD dwIndex,
DWORD dwPropID,
DWORD cbLength,
LPBYTE pbValue
)
{
HRESULT hrRes = S_OK;
RECIPIENTS_PROPERTY_ITEM piItem;
FLAT_ADDRESS faOffset;
_ASSERT(m_pBlockManager);
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::PutProperty");
// Get the recipient item first
{
CPropertyTableItem ptiItem(m_pBlockManager, m_pInstanceInfo);
hrRes = ptiItem.GetItemAtIndex(
dwIndex,
(LPPROPERTY_ITEM)&piItem,
&faOffset
);
DebugTrace((LPARAM)this,
"GetItemAtIndex: index = %u, HRESULT = %08x",
dwIndex, hrRes);
}
if (SUCCEEDED(hrRes))
{
HRESULT myRes = S_OK;
// Handle special properties first
hrRes = m_SpecialPropertyTable.PutProperty(
(PROP_ID)dwPropID,
(LPVOID)&piItem,
(LPVOID)m_pBlockManager,
PT_NONE,
cbLength,
pbValue,
TRUE);
if (SUCCEEDED(hrRes) && (hrRes != S_OK))
{
// Call the derived generic method
hrRes = CMailMsgRecipientsPropertyBase::PutProperty(
m_pBlockManager,
&piItem,
dwPropID,
cbLength,
pbValue);
//
// There is a window here for concurrency problems: if two threads
// try to add properties to the same recipient using this method, then
// we will have a property ID step over, since we acquire and increment the
// property ID value in a non-atomic manner.
//
// Note that IMailMsgRecipientsAdd::PutProperty does not have this problem
//
if (SUCCEEDED(hrRes) &&
(hrRes == S_FALSE))
{
//mikeswa - changed 7/8/98 write entire item to memory
LPBYTE pbTemp = (LPBYTE)&piItem;
myRes = m_pBlockManager->WriteMemory(
pbTemp,
faOffset,
sizeof(RECIPIENTS_PROPERTY_ITEM),
&cbLength,
NULL);
}
}
else if (SUCCEEDED(hrRes))
{
LPBYTE pbTemp = (LPBYTE)&piItem;
myRes = m_pBlockManager->WriteMemory(
pbTemp,
faOffset,
sizeof(RECIPIENTS_PROPERTY_ITEM),
&cbLength,
NULL);
}
// Here, if any of the writes failed, we will return an error
// note, myRes being not S_OK implies hrRes being successful.
if (FAILED(myRes))
hrRes = myRes;
}
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::GetProperty(
DWORD dwIndex,
DWORD dwPropID,
DWORD cbLength,
DWORD *pcbLength,
LPBYTE pbValue
)
{
HRESULT hrRes = S_OK;
RECIPIENTS_PROPERTY_ITEM piItem;
_ASSERT(m_pBlockManager);
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::GetProperty");
if (!pcbLength || !pbValue)
return(E_POINTER);
*pcbLength = 0;
// Get the recipient item first
{
CPropertyTableItem ptiItem(m_pBlockManager, m_pInstanceInfo);
hrRes = ptiItem.GetItemAtIndex(
dwIndex,
(LPPROPERTY_ITEM)&piItem
);
DebugTrace((LPARAM)this,
"GetItemAtIndex: index = %u, HRESULT = %08x",
dwIndex, hrRes);
}
if (SUCCEEDED(hrRes))
{
// Special properties are optimized
// Handle special properties first
hrRes = m_SpecialPropertyTable.GetProperty(
(PROP_ID)dwPropID,
(LPVOID)&piItem,
(LPVOID)m_pBlockManager,
PT_NONE,
cbLength,
pcbLength,
pbValue,
TRUE);
if (SUCCEEDED(hrRes) && (hrRes != S_OK))
{
// Call the derived generic method
hrRes = CMailMsgRecipientsPropertyBase::GetProperty(
m_pBlockManager,
&piItem,
dwPropID,
cbLength,
pcbLength,
pbValue);
}
}
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipients::CopyTo(
DWORD dwSourceRecipientIndex,
IMailMsgRecipientsBase *pTargetRecipientList,
DWORD dwTargetRecipientIndex,
DWORD dwExemptCount,
DWORD *pdwExemptPropIdList
)
{
HRESULT hrRes = S_OK;
RECIPIENTS_PROPERTY_ITEM piItem;
LPRECIPIENTS_PROPERTY_ITEM pRcptItem;
RECIPIENT_PROPERTY_ITEM piRcptItem;
DWORD dwIndex;
DWORD dwExempt;
DWORD *pdwExemptId;
BOOL fExempt;
BYTE rgbCopyBuffer[4096];
DWORD dwBufferSize = sizeof(rgbCopyBuffer);
DWORD dwSizeRead;
LPBYTE pBuffer = rgbCopyBuffer;
if (!pTargetRecipientList)
return(E_POINTER);
if (dwExemptCount)
{
_ASSERT(pdwExemptPropIdList);
if (!pdwExemptPropIdList)
return(E_POINTER);
}
_ASSERT(m_pBlockManager);
_ASSERT(m_pInstanceInfo);
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipients::CopyTo");
// Get the recipient item first
{
CPropertyTableItem ptiItem(m_pBlockManager, m_pInstanceInfo);
hrRes = ptiItem.GetItemAtIndex(
dwSourceRecipientIndex,
(LPPROPERTY_ITEM)&piItem
);
DebugTrace((LPARAM)this,
"GetItemAtIndex: index = %u, HRESULT = %08x",
dwSourceRecipientIndex, hrRes);
}
if (SUCCEEDED(hrRes))
{
DWORD dwTempFlags;
pRcptItem = &piItem;
// Iteratively copy all properties from the source to the target, avoiding
// those in the exempt list note that special name properties are not copied.
// First, copy the recipient flags as a special property
dwTempFlags = piItem.dwFlags &
~(FLAG_RECIPIENT_DO_NOT_DELIVER | FLAG_RECIPIENT_NO_NAME_COLLISIONS);
DebugTrace((LPARAM)this, "Copying recipient flags (%08x)", dwTempFlags);
hrRes = pTargetRecipientList->PutProperty(
dwTargetRecipientIndex,
IMMPID_RP_RECIPIENT_FLAGS,
sizeof(DWORD),
(LPBYTE)&dwTempFlags);
if (FAILED(hrRes))
{
ErrorTrace((LPARAM)this, "Failed to copy recipient flags (%08x)", hrRes);
TraceFunctLeaveEx((LPARAM)this);
return(hrRes);
}
// Instantiate a property table for the recipient properties
LPPROPERTY_TABLE_INSTANCE pInstance =
&(pRcptItem->ptiInstanceInfo);
CPropertyTable ptProperties(
PTT_PROPERTY_TABLE,
RECIPIENT_PTABLE_INSTANCE_SIGNATURE_VALID,
m_pBlockManager,
pInstance,
CMailMsgRecipientsPropertyBase::CompareProperty,
CMailMsgRecipientsPropertyBase::s_pWellKnownProperties,
CMailMsgRecipientsPropertyBase::s_dwWellKnownProperties
);
dwIndex = 0;
do
{
// Get the recipient property using an atomic operation
hrRes = ptProperties.GetPropertyItemAndValueUsingIndex(
dwIndex,
(LPPROPERTY_ITEM)&piRcptItem,
dwBufferSize,
&dwSizeRead,
pBuffer);
if (hrRes == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
{
// Insufficient buffer, try a bigger buffer
do { dwBufferSize <<= 1; } while (dwBufferSize < piRcptItem.piItem.dwSize);
pBuffer = new BYTE [dwBufferSize];
if (!pBuffer)
{
hrRes = E_OUTOFMEMORY;
ErrorTrace((LPARAM)this,
"Unable to temporarily allocate %u bytes, HRESULT = %08x",
dwBufferSize, hrRes);
goto Cleanup;
}
// Read it with the proper buffer
hrRes = m_pBlockManager->ReadMemory(
pBuffer,
piRcptItem.piItem.faOffset,
piRcptItem.piItem.dwSize,
&dwSizeRead,
NULL);
}
DebugTrace((LPARAM)this,
"Read: [%u] PropID = %u, length = %u, HRESULT = %08x",
dwIndex,
piRcptItem.idProp,
piRcptItem.piItem.dwSize,
hrRes);
if (SUCCEEDED(hrRes))
{
// See if this is an exempt property
for (dwExempt = 0,
pdwExemptId = pdwExemptPropIdList,
fExempt = FALSE;
dwExempt < dwExemptCount;
dwExempt++,
pdwExemptId++)
if (piRcptItem.idProp == *pdwExemptId)
{
DebugTrace((LPARAM)this, "Property exempted");
fExempt = TRUE;
break;
}
if (!fExempt)
{
// Write it out the the target object
hrRes = pTargetRecipientList->PutProperty(
dwTargetRecipientIndex,
piRcptItem.idProp,
piRcptItem.piItem.dwSize,
pBuffer);
DebugTrace((LPARAM)this, "Write: HRESULT = %08x", hrRes);
}
// Next
dwIndex++;
}
} while (SUCCEEDED(hrRes));
// Correct the error code
if (hrRes == HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS))
hrRes = S_OK;
}
Cleanup:
if (pBuffer && pBuffer != rgbCopyBuffer)
delete [] pBuffer;
TraceFunctLeave();
return(hrRes);
}
// *************************************************************************************
// *************************************************************************************
// *************************************************************************************
// *************************************************************************************
// =================================================================
// Implementation of CMailMsgRecipientsAdd
//
#define ADD_DEFAULT_RECIPIENT_NAME_BUFFER_SIZE 2048
CMailMsgRecipientsAdd::CMailMsgRecipientsAdd(
CBlockManager *pBlockManager
)
:
m_SpecialPropertyTable(&g_SpecialRecipientsAddPropertyTable)
{
_ASSERT(pBlockManager);
// Initialize the refcount
m_ulRefCount = 0;
// Acquire the block manager
m_pBlockManager = pBlockManager;
// Initialize the internal property table instance
MoveMemory(
&m_InstanceInfo,
&s_DefaultInstance,
sizeof(PROPERTY_TABLE_INSTANCE));
}
CMailMsgRecipientsAdd::~CMailMsgRecipientsAdd()
{
}
HRESULT CMailMsgRecipientsAdd::QueryInterface(
REFIID iid,
void **ppvObject
)
{
if (iid == IID_IUnknown)
{
// Return our identity
*ppvObject = (IUnknown *)(IMailMsgRecipientsAdd *)this;
AddRef();
}
else if (iid == IID_IMailMsgRecipientsAdd)
{
// Return the add recipients interface
*ppvObject = (IMailMsgRecipientsAdd *)this;
AddRef();
}
else if (iid == IID_IMailMsgRecipientsBase)
{
// Return the base recipients interface
*ppvObject = (IMailMsgRecipientsBase *)this;
AddRef();
}
else if (iid == IID_IMailMsgPropertyReplication)
{
// Return the base recipients interface
*ppvObject = (IMailMsgPropertyReplication *)this;
AddRef();
}
else
return(E_NOINTERFACE);
return(S_OK);
}
ULONG CMailMsgRecipientsAdd::AddRef()
{
return(InterlockedIncrement(&m_ulRefCount));
}
ULONG CMailMsgRecipientsAdd::Release()
{
LONG lRefCount = InterlockedDecrement(&m_ulRefCount);
if (lRefCount == 0)
{
delete this;
}
return(lRefCount);
}
HRESULT CMailMsgRecipientsAdd::AddPrimaryOrSecondary(
DWORD dwCount,
LPCSTR *ppszNames,
DWORD *pdwPropIDs,
DWORD *pdwIndex,
IMailMsgRecipientsBase *pFrom,
DWORD dwFrom,
BOOL fPrimary
)
{
HRESULT hrRes = S_OK;
BOOL fLockTaken = FALSE;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::AddPrimaryOrSecondary");
if (dwCount)
{
if (!ppszNames || !pdwPropIDs || !pdwIndex)
return(E_POINTER);
}
// If we have a count of zero, by default, we will copy all the
// names of the source recipient to the new recipient. However,
// if a source recipient is not specified, then this is an error
if (dwCount || pFrom)
{
DWORD i;
BOOL rgfAllocated[MAX_COLLISION_HASH_KEYS];
DWORD rgPropIDs[MAX_COLLISION_HASH_KEYS];
LPBYTE rgszNames[MAX_COLLISION_HASH_KEYS];
for (i = 0; i < MAX_COLLISION_HASH_KEYS; i++)
rgfAllocated[i] = FALSE;
CMemoryAccess cmaAccess;
if (!dwCount)
{
DWORD dwPropID;
DWORD dwLength;
BYTE pBuffer[ADD_DEFAULT_RECIPIENT_NAME_BUFFER_SIZE];
LPBYTE pNameStart;
DWORD dwRemaining = ADD_DEFAULT_RECIPIENT_NAME_BUFFER_SIZE;
ppszNames = (LPCSTR*)rgszNames;
pdwPropIDs = rgPropIDs;
pNameStart = pBuffer;
// OK, copy the default names ...
for (i = 0; i < MAX_COLLISION_HASH_KEYS; i++)
{
rgfAllocated[i] = FALSE;
dwPropID = rgDefaultAddressTypes[i];
hrRes = pFrom->GetProperty(
dwFrom,
dwPropID,
dwRemaining,
&dwLength,
pNameStart);
if (hrRes == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
{
// Insufficient buffer, allocate and retry
hrRes = cmaAccess.AllocBlock(
(LPVOID *)&(rgszNames[dwCount]),
dwLength);
if (SUCCEEDED(hrRes))
{
hrRes = pFrom->GetProperty(
dwFrom,
dwPropID,
dwLength,
&dwLength,
rgszNames[dwCount]);
rgfAllocated[dwCount] = TRUE;
}
}
else if (SUCCEEDED(hrRes))
{
_ASSERT(dwRemaining >= dwLength);
rgszNames[dwCount] = pNameStart;
pNameStart += dwLength;
dwRemaining -= dwLength;
}
if (SUCCEEDED(hrRes))
{
// OK, got a name, now set the prop ID and
// bump the count
rgPropIDs[dwCount] = dwPropID;
dwCount++;
}
else if (hrRes == STG_E_UNKNOWN)
hrRes = S_OK;
else
{
ErrorTrace((LPARAM)this, "Error in GetProperty, hr=%08x", hrRes);
}
}
}
if (SUCCEEDED(hrRes))
{
if (dwCount)
{
_ASSERT(ppszNames);
_ASSERT(pdwPropIDs);
m_Hash.Lock();
fLockTaken = TRUE;
if (fPrimary)
{
hrRes = m_Hash.AddPrimary(
dwCount,
ppszNames,
pdwPropIDs,
pdwIndex);
}
else
{
hrRes = m_Hash.AddSecondary(
dwCount,
ppszNames,
pdwPropIDs,
pdwIndex);
}
}
else
{
ErrorTrace((LPARAM)this, "No recipient names specified or an error occurred");
hrRes = E_FAIL;
}
}
// Free any allocated memory
for (i = 0; i < MAX_COLLISION_HASH_KEYS; i++)
if (rgfAllocated[i])
{
HRESULT myRes;
myRes = cmaAccess.FreeBlock((LPVOID)rgszNames[i]);
_ASSERT(SUCCEEDED(myRes));
}
}
else
{
ErrorTrace((LPARAM)this, "No recipient names specified, and no source to copy from");
hrRes = E_INVALIDARG;
}
if (SUCCEEDED(hrRes) && pFrom)
{
HRESULT hrRep;
IMailMsgPropertyReplication *pReplication = NULL;
// Copy the properties over
hrRep = pFrom->QueryInterface(
IID_IMailMsgPropertyReplication,
(LPVOID *)&pReplication);
if (SUCCEEDED(hrRep))
{
// Copy all properties, be careful not to overwrite anything
// that we just set.
hrRep = pReplication->CopyTo(
dwFrom,
(IMailMsgRecipientsBase *)this,
*pdwIndex,
dwCount,
pdwPropIDs);
// Done with the replication interface
pReplication->Release();
}
// Remove the recipient if we fail here
if (FAILED(hrRep))
{
HRESULT myRes = m_Hash.RemoveRecipient(*pdwIndex);
_ASSERT(SUCCEEDED(myRes));
// Return this error instead
hrRes = hrRep;
}
}
if (fLockTaken)
m_Hash.Unlock();
TraceFunctLeave();
return(hrRes);
}
HRESULT CMailMsgRecipientsAdd::AddPrimary(
DWORD dwCount,
LPCSTR *ppszNames,
DWORD *pdwPropIDs,
DWORD *pdwIndex,
IMailMsgRecipientsBase *pFrom,
DWORD dwFrom
)
{
HRESULT hrRes = S_OK;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::AddPrimary");
hrRes = AddPrimaryOrSecondary(
dwCount,
ppszNames,
pdwPropIDs,
pdwIndex,
pFrom,
dwFrom,
TRUE);
TraceFunctLeave();
return(hrRes);
}
HRESULT CMailMsgRecipientsAdd::AddSecondary(
DWORD dwCount,
LPCSTR *ppszNames,
DWORD *pdwPropIDs,
DWORD *pdwIndex,
IMailMsgRecipientsBase *pFrom,
DWORD dwFrom
)
{
HRESULT hrRes = S_OK;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::AddSecondary");
hrRes = AddPrimaryOrSecondary(
dwCount,
ppszNames,
pdwPropIDs,
pdwIndex,
pFrom,
dwFrom,
FALSE);
TraceFunctLeave();
return(hrRes);
}
/***************************************************************************/
//
// Implementation of CMailMsgRecipientsAdd::CMailMsgRecipientsPropertyBase
//
HRESULT STDMETHODCALLTYPE CMailMsgRecipientsAdd::Count(
DWORD *pdwCount
)
{
HRESULT hrRes;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::Count");
if (!pdwCount)
return(E_POINTER);
hrRes = m_Hash.GetRecipientCount(pdwCount);
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipientsAdd::Item(
DWORD dwIndex,
DWORD dwWhichName,
DWORD cchLength,
LPSTR pszName
)
{
HRESULT hrRes = S_OK;
LPRECIPIENTS_PROPERTY_ITEM_EX pItem = NULL;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::Item");
// Get a pointer to the recipient from the index
hrRes = m_Hash.GetRecipient(dwIndex, &pItem);
if (FAILED(hrRes))
return(E_POINTER);
if (!pItem || !pszName)
return(E_POINTER);
if (pItem->dwSignature != RECIPIENTS_PROPERTY_ITEM_EX_SIG)
return E_POINTER;
if (dwWhichName >= MAX_COLLISION_HASH_KEYS)
return(E_INVALIDARG);
// Copy the name over
if (!pItem->rpiRecipient.faNameOffset[dwWhichName])
return(STG_E_UNKNOWN);
if (cchLength < pItem->rpiRecipient.dwNameLength[dwWhichName])
return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
MoveMemory(pszName,
(LPVOID)((pItem->rpiRecipient).faNameOffset[dwWhichName]),
pItem->rpiRecipient.dwNameLength[dwWhichName]);
TraceFunctLeave();
return(S_OK);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipientsAdd::PutProperty(
DWORD dwIndex,
DWORD dwPropID,
DWORD cbLength,
LPBYTE pbValue
)
{
HRESULT hrRes = S_OK;
LPRECIPIENTS_PROPERTY_ITEM_EX pItem = NULL;
LPRECIPIENTS_PROPERTY_ITEM pRcptItem;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::PutProperty");
// Get a pointer to the recipient from the index
hrRes = m_Hash.GetRecipient(dwIndex, &pItem);
if (FAILED(hrRes))
return(E_POINTER);
if (!pItem || !pbValue)
return(E_POINTER);
if (pItem->dwSignature != RECIPIENTS_PROPERTY_ITEM_EX_SIG)
return E_POINTER;
pRcptItem = &(pItem->rpiRecipient);
_ASSERT(pRcptItem);
// Handle special properties first
hrRes = m_SpecialPropertyTable.PutProperty(
(PROP_ID)dwPropID,
(LPVOID)pRcptItem,
NULL,
PT_NONE,
cbLength,
pbValue,
TRUE);
if (SUCCEEDED(hrRes) && (hrRes != S_OK))
{
// Call the derived generic method
hrRes = CMailMsgRecipientsPropertyBase::PutProperty(
m_pBlockManager,
pRcptItem,
dwPropID,
cbLength,
pbValue);
}
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipientsAdd::GetProperty(
DWORD dwIndex,
DWORD dwPropID,
DWORD cbLength,
DWORD *pcbLength,
LPBYTE pbValue
)
{
HRESULT hrRes = S_OK;
LPRECIPIENTS_PROPERTY_ITEM_EX pItem = NULL;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::GetProperty");
// Get a pointer to the recipient from the index
hrRes = m_Hash.GetRecipient(dwIndex, &pItem);
if (FAILED(hrRes))
return(E_POINTER);
hrRes = GetPropertyInternal(
pItem,
dwPropID,
cbLength,
pcbLength,
pbValue);
return hrRes;
}
HRESULT CMailMsgRecipientsAdd::GetPropertyInternal(
LPRECIPIENTS_PROPERTY_ITEM_EX pItem,
DWORD dwPropID,
DWORD cbLength,
DWORD *pcbLength,
LPBYTE pbValue
)
{
HRESULT hrRes = S_OK;
LPRECIPIENTS_PROPERTY_ITEM pRcptItem;
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::GetProperty");
if (!pItem || !pcbLength || !pbValue)
return(E_POINTER);
if (pItem->dwSignature != RECIPIENTS_PROPERTY_ITEM_EX_SIG)
return E_POINTER;
*pcbLength = 0;
pRcptItem = &(pItem->rpiRecipient);
_ASSERT(pRcptItem);
// Special properties are optimized
// Handle special properties first
hrRes = m_SpecialPropertyTable.GetProperty(
(PROP_ID)dwPropID,
(LPVOID)pRcptItem,
NULL,
PT_NONE,
cbLength,
pcbLength,
pbValue,
TRUE);
if (SUCCEEDED(hrRes) && (hrRes != S_OK))
{
// Call the derived generic method
hrRes = CMailMsgRecipientsPropertyBase::GetProperty(
m_pBlockManager,
pRcptItem,
dwPropID,
cbLength,
pcbLength,
pbValue);
}
TraceFunctLeave();
return(hrRes);
}
HRESULT STDMETHODCALLTYPE CMailMsgRecipientsAdd::CopyTo(
DWORD dwSourceRecipientIndex,
IMailMsgRecipientsBase *pTargetRecipientList,
DWORD dwTargetRecipientIndex,
DWORD dwExemptCount,
DWORD *pdwExemptPropIdList
)
{
HRESULT hrRes = S_OK;
LPRECIPIENTS_PROPERTY_ITEM_EX pItem = NULL;
LPRECIPIENTS_PROPERTY_ITEM pRcptItem;
RECIPIENT_PROPERTY_ITEM piRcptItem;
DWORD dwTempFlags;
DWORD dwIndex;
DWORD dwExempt;
DWORD *pdwExemptId;
BOOL fExempt;
BYTE rgbCopyBuffer[4096];
DWORD dwBufferSize = sizeof(rgbCopyBuffer);
DWORD dwSizeRead;
LPBYTE pBuffer = rgbCopyBuffer;
if (!pTargetRecipientList)
return(E_POINTER);
if (dwExemptCount)
{
if (!pdwExemptPropIdList)
return(E_POINTER);
}
TraceFunctEnterEx((LPARAM)this, "CMailMsgRecipientsAdd::CopyTo");
// Get a pointer to the recipient from the index
hrRes = m_Hash.GetRecipient(dwSourceRecipientIndex, &pItem);
if (FAILED(hrRes))
return(E_POINTER);
if (!pItem)
return E_POINTER;
if (pItem->dwSignature != RECIPIENTS_PROPERTY_ITEM_EX_SIG)
return E_POINTER;
pRcptItem = &(pItem->rpiRecipient);
// Iteratively copy all properties from the source to the target, avoiding
// those in the exempt list note that special name properties are not copied.
// First, copy the recipient flags as a special property
dwTempFlags = pRcptItem->dwFlags &
~(FLAG_RECIPIENT_DO_NOT_DELIVER | FLAG_RECIPIENT_NO_NAME_COLLISIONS);
DebugTrace((LPARAM)this, "Copying recipient flags (%08x)", dwTempFlags);
hrRes = pTargetRecipientList->PutProperty(
dwTargetRecipientIndex,
IMMPID_RP_RECIPIENT_FLAGS,
sizeof(DWORD),
(LPBYTE)&dwTempFlags);
if (FAILED(hrRes))
{
ErrorTrace((LPARAM)this, "Failed to copy recipient flags (%08x)", hrRes);
TraceFunctLeaveEx((LPARAM)this);
return(hrRes);
}
// Instantiate a property table for the recipient properties
LPPROPERTY_TABLE_INSTANCE pInstance =
&(pRcptItem->ptiInstanceInfo);
CPropertyTable ptProperties(
PTT_PROPERTY_TABLE,
RECIPIENT_PTABLE_INSTANCE_SIGNATURE_VALID,
m_pBlockManager,
pInstance,
CMailMsgRecipientsPropertyBase::CompareProperty,
CMailMsgRecipientsPropertyBase::s_pWellKnownProperties,
CMailMsgRecipientsPropertyBase::s_dwWellKnownProperties
);
dwIndex = 0;
do
{
// Get the recipient property using an atomic operation
hrRes = ptProperties.GetPropertyItemAndValueUsingIndex(
dwIndex,
(LPPROPERTY_ITEM)&piRcptItem,
dwBufferSize,
&dwSizeRead,
pBuffer);
if (hrRes == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
{
// Insufficient buffer, try a bigger buffer
do { dwBufferSize <<= 1; } while (dwBufferSize < piRcptItem.piItem.dwSize);
pBuffer = new BYTE [dwBufferSize];
if (!pBuffer)
{
hrRes = E_OUTOFMEMORY;
ErrorTrace((LPARAM)this,
"Unable to temporarily allocate %u bytes, HRESULT = %08x",
dwBufferSize, hrRes);
goto Cleanup;
}
// Read it with the proper buffer
hrRes = m_pBlockManager->ReadMemory(
pBuffer,
piRcptItem.piItem.faOffset,
piRcptItem.piItem.dwSize,
&dwSizeRead,
NULL);
}
DebugTrace((LPARAM)this,
"Read: [%u] PropID = %u, length = %u, HRESULT = %08x",
dwIndex,
piRcptItem.idProp,
piRcptItem.piItem.dwSize,
hrRes);
// See if this is an exempt property
for (dwExempt = 0,
pdwExemptId = pdwExemptPropIdList,
fExempt = FALSE;
dwExempt < dwExemptCount;
dwExempt++,
pdwExemptId++)
if (piRcptItem.idProp == *pdwExemptId)
{
DebugTrace((LPARAM)this, "Property exempted");
fExempt = TRUE;
break;
}
if (SUCCEEDED(hrRes) && !fExempt)
{
// Write it out the the target object
hrRes = pTargetRecipientList->PutProperty(
dwTargetRecipientIndex,
piRcptItem.idProp,
piRcptItem.piItem.dwSize,
pBuffer);
DebugTrace((LPARAM)this, "Write: HRESULT = %08x", hrRes);
}
// Next
dwIndex++;
} while (SUCCEEDED(hrRes));
// Correct the error code
if (hrRes == HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS))
hrRes = S_OK;
Cleanup:
if (pBuffer && pBuffer != rgbCopyBuffer)
delete [] pBuffer;
TraceFunctLeave();
return(hrRes);
}
| [
"[email protected]"
] | |
81377e83b654de92854938052e74a48cbecd64c3 | c837912162568c7d02d309aff70638c7582119be | /TowerDefense/TowerDefense/SFML-utils/cegui/GuiManager.hpp | 01604688e1b701eb02e7422e8d9426e3bee11482 | [] | no_license | iwilsonq/TowerDefense | c7985896df42c32b7785e28865aafcb619a0d6e1 | ad8bc5c6a1f5bf1e0d6a47dbac9cb5276d3ae3d6 | refs/heads/master | 2021-05-30T14:33:48.510176 | 2016-01-29T07:30:00 | 2016-01-29T07:30:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,249 | hpp | #ifndef SFUTILS_CEGUI_GUIMANAGER_HPP
#define SFUTILS_CEGUI_GUIMANAGER_HPP
#include <array>
#include <SFML/Graphics.hpp>
#include <CEGUI/CEGUI.h>
#include <CEGUI/RendererModules/OpenGL/GLRenderer.h>
namespace sfutils
{
namespace cegui
{
class GuiManager
{
public:
GuiManager(const GuiManager&) = delete;
GuiManager& operator=(const GuiManager&) = delete;
static void init(const std::string& mediDirectory,const std::string& defaultFont = "DejaVuSans-10");
static bool processEvent(const sf::Event& event); //< inject event to CEGUI::System::getSingleton().getDefaultGUIContext()
static bool processEvent(const sf::Event& event,CEGUI::GUIContext& context);
/**
* update BOTH of the system and the default GUIContext
*/
static void update(const sf::Time& deltaTime);
/**
* update ONLY the context.
* You have to update the system yourself
*/
static void update(const sf::Time& deltaTime,CEGUI::GUIContext& context);
/**
* Don't forget to [push/pop]GLStates
* render the default context
* */
static void render();
/**
* Don't forget to [push/pop]GLStates
* render the specified context
* */
static void render(CEGUI::GUIContext& context);
static CEGUI::OpenGLRenderer& getRenderer();
protected:
private:
GuiManager();
typedef std::array<CEGUI::Key::Scan,sf::Keyboard::Key::KeyCount> KeyMap;
typedef std::array<CEGUI::MouseButton,sf::Mouse::Button::ButtonCount> MouseButtonMap;
static KeyMap _keyMap;
static MouseButtonMap _mouseButtonMap;
static CEGUI::OpenGLRenderer* _renderer;
static void _initMaps();
static void _initRenderer();
static void _initResources(const std::string& rootDir);
};
}
}
#endif
| [
"[email protected]"
] | |
9cceac50edef24f841bfeb53b3d0c9447d990352 | e1880fcf16d89f092c9a98163bd4bb3d8ff05cec | /src/engine.cpp | 34b7f321807e3549d06e7619f008655ccd01d51a | [] | no_license | Twiebs/venom | 021dc7528543121d8fba70bed94e14f4a5ab3bab | 42f7bd669545560bf0deb8cb5de6852829b7f8d8 | refs/heads/master | 2021-01-17T15:24:37.614662 | 2017-05-14T00:26:01 | 2017-05-14T00:26:01 | 52,766,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,123 | cpp |
static Engine g_engine;
thread_local U32 g_threadID;
static inline B8 ExecuteTask(Worker *worker, Task task) {
switch (task.type) {
case TaskType_LoadModel: {
return CreateModelAssetFromFile(task.slotID);
} break;
}
}
static inline void FinalizeTask(Worker *worker, Task task) {
switch (task.type) {
case TaskType_LoadModel: {
CreateOpenGLResourcesForModelAsset(task.slotID);
} break;
}
}
static void WorkerThreadProc(Worker *worker) {
#ifndef VENOM_SINGLE_THREADED
g_threadID = worker->workerID;
LogDebug("Worker %u has started", worker->workerID);
Engine *engine = &g_engine;
while (engine->isEngineRunning) {
engine->workLock.lock();
if (engine->tasksToExecute.count > 0) {
Task task = engine->tasksToExecute[engine->tasksToExecute.count - 1];
engine->tasksToExecute.count -= 1;
engine->workLock.unlock();
ExecuteTask(worker, task);
engine->workLock.lock();
engine->tasksToFinalize.PushBack(task);
engine->workLock.unlock();
} else {
engine->workLock.unlock();
}
}
LogDebug("Worker %u has exited", worker->workerID);
#endif//VENOM_SINGLE_THREADED
}
static inline Engine *GetEngine() {
return &g_engine;
}
static inline U32 GetThreadID() {
return g_threadID;
}
static const size_t WORKER_STACK_MEMORY_SIZE = 1024 * 1024 * 2;
void ScheduleTask(Task task) {
auto engine = GetEngine();
engine->workLock.lock();
engine->tasksToExecute.PushBack(task);
engine->workLock.unlock();
}
void InitalizeEngine() {
BeginProfileEntry("Initalize Engine");
Engine *engine = &g_engine;
#ifdef VENOM_SINGLE_THREADED
size_t workerCount = 1;
#else VENOM_SINGLE_THREADED
size_t workerCount = std::thread::hardware_concurrency();
#endif//VENOM_SINGLE_THREADED
size_t requiredMemory = Align8(workerCount * sizeof(Worker));
requiredMemory += Align8(WORKER_STACK_MEMORY_SIZE * workerCount);
U8 *memory = (U8 *)MemoryAllocate(requiredMemory);
memset(memory, 0x00, requiredMemory);
engine->workers = (Worker *)memory;
engine->workerCount = workerCount;
engine->isRunning = true;
U8 *currentStackMemoryPtr = memory + Align8(workerCount * sizeof(Worker));
g_threadID = 0; //Set the main thread's id to 0
for (size_t i = 0; i < workerCount; i++) {
Worker *worker = &engine->workers[i];
worker->workerID = i;
worker->stackMemory.memory = currentStackMemoryPtr;
worker->stackMemory.size = WORKER_STACK_MEMORY_SIZE;
currentStackMemoryPtr += WORKER_STACK_MEMORY_SIZE;
}
for (size_t i = 1; i < workerCount; i++) {
Worker *worker = &engine->workers[i];
worker->thread = std::thread(WorkerThreadProc, worker);
}
{ //Initalize physics simulation paramaters
PhysicsSimulation *sim = &engine->physicsSimulation;
sim->gravityAcceleration = V3(0.0f, -9.81f, 0.0f);
}
InitalizeTerrain(&engine->terrain, 5, 8, 32);
#ifndef VENOM_RELEASE
OpenGLEnableDebug(&engine->debugLog);
#endif//VENOM_RELEASE
EndProfileEntry();
}
void FinalizeEngineTasks(Engine *engine) {
#ifdef VENOM_SINGLE_THREADED
for (size_t i = 0; i < engine->tasksToExecute.count; i++) {
if (ExecuteTask(&engine->workers[0], engine->tasksToExecute[i])) {
engine->tasksToFinalize.PushBack(engine->tasksToExecute[i]);
}
}
engine->tasksToExecute.count = 0;
#endif//VENOM_SINGLE_THREADED
for (size_t i = 0; i < engine->tasksToFinalize.count; i++)
FinalizeTask(&engine->workers[0], engine->tasksToFinalize[i]);
engine->tasksToFinalize.count = 0;
}
void UpdateAnimationStates(EntityContainer *entityContainer, F32 deltaTime) {
BeginTimedBlock("Update Animation States");
EntityBlock *block = entityContainer->firstAvaibleBlock;
for (U64 i = 0; i < entityContainer->capacityPerBlock; i++) {
if (block->flags[i] & EntityFlag_PRESENT) {
Entity* entity = &block->entities[i];
ModelAsset *model = GetModelAsset(entity->modelID);
if (model == nullptr) continue;
if (model->jointCount > 0) {
UpdateAnimationState(&entity->animation_state, model, deltaTime);
}
}
}
EndTimedBlock("Update Animation States");
} | [
"[email protected]"
] | |
7b3d4ff97eff2148c9bacb568ad624ca07160687 | 901569317656d88b6510f5b9014b145988858107 | /00299.cpp | a2bde8773c88c653dc6f7b86095a07eb45012072 | [] | no_license | ckpiyanon/ckp_competitive_cpp | 66753ddd0c800405242cdc641f556ba751270edd | 81afcb2deaf2cf08aa041ee064715e34bfb53b66 | refs/heads/master | 2020-05-21T23:47:56.092940 | 2019-01-24T06:41:30 | 2019-01-24T06:41:30 | 61,094,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
// freopen("in.txt","r",stdin);
int TC,n,arr[50],cnt;
scanf("%d",&TC);
while(TC--)
{
scanf("%d",&n);
for(int i = 0;i < n;i++) scanf("%d",arr + i);
cnt = 0;
for(int i = n-1;i > 0;i--) for(int j = 0;j < i;j++) if(arr[j] > arr[j+1])
{
arr[j] ^= arr[j+1],arr[j+1] ^= arr[j],arr[j] ^= arr[j+1];
cnt++;
}
printf("Optimal train swapping takes %d swaps.\n",cnt);
}
return 0;
}
| [
"Chinakrit Lorpiyanon"
] | Chinakrit Lorpiyanon |
41ee7402f39caacd062089e53cb4b4128ad0fa79 | 1e9c8b52094966603f7d9bbfde6c21904616ed3b | /函数约分.cpp | 1d4ae0298fb8b3a9f6c6387a1762042d9e10379d | [] | no_license | JorieRiddle/myGitTemp | 3cfcbcc1a4b3afad5c8c648944864226d8ec0962 | 8f568cd818e6bdf56574986a15874865bb21ca49 | refs/heads/main | 2023-02-04T08:14:15.246056 | 2020-12-25T09:14:12 | 2020-12-25T09:14:12 | 310,446,315 | 0 | 0 | null | 2020-11-06T00:24:55 | 2020-11-06T00:00:29 | null | UTF-8 | C++ | false | false | 224 | cpp | #include <stdio.h>
int gcd(int a,int b)
{
int m,n,t;
m=a;
n=b;
while(n>0)
{
t=m%n;
m=n;
n=t;
}
return printf("%d/%d\n",a/m,b/m);
}
int main()
{
int m,n;
scanf("%d/%d",&m,&n);
gcd(m,n);
return 0;
}; | [
"[email protected]"
] | |
4d545af2992408669a7338be791dd961a99bc34b | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /v8_7_5/src/objects/js-proxy.h | 009f80ed5daaca575035d843112cac62259d3f05 | [
"Apache-2.0",
"bzip2-1.0.6",
"BSD-3-Clause",
"SunPro"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 5,729 | h | // Copyright 2018 the V8 project 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 V8_OBJECTS_JS_PROXY_H_
#define V8_OBJECTS_JS_PROXY_H_
#include "src/objects/js-objects.h"
#include "torque-generated/builtin-definitions-from-dsl.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// The JSProxy describes EcmaScript Harmony proxies
class JSProxy : public JSReceiver {
public:
V8_WARN_UNUSED_RESULT static MaybeHandle<JSProxy> New(Isolate* isolate,
Handle<Object>,
Handle<Object>);
// [handler]: The handler property.
DECL_ACCESSORS(handler, Object)
// [target]: The target property.
DECL_ACCESSORS(target, Object)
static MaybeHandle<NativeContext> GetFunctionRealm(Handle<JSProxy> proxy);
DECL_CAST(JSProxy)
V8_INLINE bool IsRevoked() const;
static void Revoke(Handle<JSProxy> proxy);
// ES6 9.5.1
static MaybeHandle<Object> GetPrototype(Handle<JSProxy> receiver);
// ES6 9.5.2
V8_WARN_UNUSED_RESULT static Maybe<bool> SetPrototype(
Handle<JSProxy> proxy, Handle<Object> value, bool from_javascript,
ShouldThrow should_throw);
// ES6 9.5.3
V8_WARN_UNUSED_RESULT static Maybe<bool> IsExtensible(Handle<JSProxy> proxy);
// ES6, #sec-isarray. NOT to be confused with %_IsArray.
V8_WARN_UNUSED_RESULT static Maybe<bool> IsArray(Handle<JSProxy> proxy);
// ES6 9.5.4 (when passed kDontThrow)
V8_WARN_UNUSED_RESULT static Maybe<bool> PreventExtensions(
Handle<JSProxy> proxy, ShouldThrow should_throw);
// ES6 9.5.5
V8_WARN_UNUSED_RESULT static Maybe<bool> GetOwnPropertyDescriptor(
Isolate* isolate, Handle<JSProxy> proxy, Handle<Name> name,
PropertyDescriptor* desc);
// ES6 9.5.6
V8_WARN_UNUSED_RESULT static Maybe<bool> DefineOwnProperty(
Isolate* isolate, Handle<JSProxy> object, Handle<Object> key,
PropertyDescriptor* desc, Maybe<ShouldThrow> should_throw);
// ES6 9.5.7
V8_WARN_UNUSED_RESULT static Maybe<bool> HasProperty(Isolate* isolate,
Handle<JSProxy> proxy,
Handle<Name> name);
// This function never returns false.
// It returns either true or throws.
V8_WARN_UNUSED_RESULT static Maybe<bool> CheckHasTrap(
Isolate* isolate, Handle<Name> name, Handle<JSReceiver> target);
// ES6 9.5.8
V8_WARN_UNUSED_RESULT static MaybeHandle<Object> GetProperty(
Isolate* isolate, Handle<JSProxy> proxy, Handle<Name> name,
Handle<Object> receiver, bool* was_found);
enum AccessKind { kGet, kSet };
static MaybeHandle<Object> CheckGetSetTrapResult(Isolate* isolate,
Handle<Name> name,
Handle<JSReceiver> target,
Handle<Object> trap_result,
AccessKind access_kind);
// ES6 9.5.9
V8_WARN_UNUSED_RESULT static Maybe<bool> SetProperty(
Handle<JSProxy> proxy, Handle<Name> name, Handle<Object> value,
Handle<Object> receiver, Maybe<ShouldThrow> should_throw);
// ES6 9.5.10 (when passed LanguageMode::kSloppy)
V8_WARN_UNUSED_RESULT static Maybe<bool> DeletePropertyOrElement(
Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
// ES6 9.5.12
V8_WARN_UNUSED_RESULT static Maybe<bool> OwnPropertyKeys(
Isolate* isolate, Handle<JSReceiver> receiver, Handle<JSProxy> proxy,
PropertyFilter filter, KeyAccumulator* accumulator);
V8_WARN_UNUSED_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
LookupIterator* it);
// Dispatched behavior.
DECL_PRINTER(JSProxy)
DECL_VERIFIER(JSProxy)
static const int kMaxIterationLimit = 100 * 1024;
// Layout description.
DEFINE_FIELD_OFFSET_CONSTANTS(JSReceiver::kHeaderSize,
TORQUE_GENERATED_JSPROXY_FIELDS)
// kTargetOffset aliases with the elements of JSObject. The fact that
// JSProxy::target is a Javascript value which cannot be confused with an
// elements backing store is exploited by loading from this offset from an
// unknown JSReceiver.
STATIC_ASSERT(static_cast<int>(JSObject::kElementsOffset) ==
static_cast<int>(JSProxy::kTargetOffset));
typedef FixedBodyDescriptor<JSReceiver::kPropertiesOrHashOffset, kSize, kSize>
BodyDescriptor;
static Maybe<bool> SetPrivateSymbol(Isolate* isolate, Handle<JSProxy> proxy,
Handle<Symbol> private_name,
PropertyDescriptor* desc,
Maybe<ShouldThrow> should_throw);
OBJECT_CONSTRUCTORS(JSProxy, JSReceiver);
};
// JSProxyRevocableResult is just a JSObject with a specific initial map.
// This initial map adds in-object properties for "proxy" and "revoke".
// See https://tc39.github.io/ecma262/#sec-proxy.revocable
class JSProxyRevocableResult : public JSObject {
public:
// Layout description.
DEFINE_FIELD_OFFSET_CONSTANTS(
JSObject::kHeaderSize, TORQUE_GENERATED_JSPROXY_REVOCABLE_RESULT_FIELDS)
// Indices of in-object properties.
static const int kProxyIndex = 0;
static const int kRevokeIndex = 1;
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxyRevocableResult);
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_JS_PROXY_H_
| [
"[email protected]"
] | |
1511bbb216d204ad7520a89befbd8e15f0a95d9b | b5ae5e238ebe407b5e2c413bc1c2cea625bb50c9 | /pipelinejs.h | 6e94da46f9a037bb9a56787c825b21699d751096 | [] | no_license | adarqui/pipelinejs | 85c47acd948cebd7313916f9f9fb9b4d577d4188 | be5536fc2a35f8eab3fad2e2237d9adfadad5c3d | refs/heads/master | 2021-01-20T06:38:25.914332 | 2013-04-27T06:17:41 | 2013-04-27T06:17:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,156 | h | /* pipelinejs -- adarqui */
#ifndef PIPELINEJS_H
#define PIPELINEJS_H
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <node.h>
#include <node_buffer.h>
#include <node_version.h>
#include <v8.h>
#include <pcap.h>
#include <errno.h>
#include <pty.h>
#include <termios.h>
#include <list>
#include "pipelinejs_misc.h"
using namespace v8;
using namespace node;
using namespace std;
typedef struct proc {
char ** argv;
char ** envp;
int argc;
pid_t pid;
} proc_t;
typedef list<proc_t> PROC;
class Pipes {
public:
PROC procs;
Persistent<Function> cb;
int len;
int stdout[2];
int stderr[2];
int ctrl[2];
pid_t pid;
pid_t pid_last;
uv_poll_t * uv_stdout;
uv_poll_t * uv_stderr;
uv_poll_t * uv_ctrl;
bool stdin;
bool tty;
int tty_fd;
int tty_pfds[2];
FILE * fp;
char * fp_mode;
int bytes_written;
pid_t pgrp;
Pipes();
~Pipes();
void Clean (void);
};
typedef Pipes pipes_t;
typedef list<pipes_t> PIPES;
enum fd_wrappers_types {
FDW_STDOUT,
FDW_STDERR,
FDW_CTRL,
};
typedef struct fd_wrapper {
int type;
int fd;
pipes_t * p;
} fd_wrapper_t;
enum control_stuff {
CONTROL_EXIT
};
typedef struct control {
int pfds[2];
} control_t;
typedef struct control_data {
int type;
int arg;
} control_data_t;
extern int errno;
void init(Handle<Object> exports, Handle<Object> module);
Handle<Value> exec(const Arguments&);
Handle<Value> ctrl(const Arguments&);
void dumpit(void);
void runit(PIPES::iterator);
int execit(PIPES::iterator, PROC::iterator, PROC::iterator, PROC::iterator);
int clear_cloexec(int);
enum pipe_ops {
OP_STOP,
OP_START,
OP_STATUS,
OP_KILL
};
void pipe_op(int, int);
void erase_pid(PIPES::iterator);
void add_fd(PIPES::iterator, int);
void on_handle_close(uv_handle_t *);
void on_fd_event(uv_poll_t *, int, int);
void emit(PIPES::iterator, pipes_t *, char *, char *, int, pid_t);
void setup_control_socket(void);
void on_control_event(uv_poll_t *, int, int);
void control_write(int,int);
control_data_t * control_read(void);
/*
* List stuff
*/
#endif
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.