blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 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 listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c82294fcdf134d7104a0203fb9141b34974a4884 | 2bb4b4e4617db5552b79580bb48940a33c07b7a7 | /poin1.cpp | c6e394fa23552ae13700a5c25cb0f96b59c7e433 | [] | no_license | sheraz-n/DSASource | 31693f275710773a61f9be1ebe7e53357d9e5b2c | 70fe9f99cb506f7b9d9d42931d3fe7721d31af64 | refs/heads/master | 2021-01-10T03:47:17.900755 | 2015-12-18T06:09:39 | 2015-12-18T06:09:39 | 48,217,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | cpp | #include <iostream>
using namespace std;
int main (){
char *a = "Hello";
//cout<<a;
cout<<"Address = "<<a++<< "\n Value = "<< *(a+2);
return 0;
}
| [
"sheraz.naseer@umt.edu.pk"
] | sheraz.naseer@umt.edu.pk |
ad89186ac97d3688932200f9aa2e2396b9bcfae5 | 1560a356e7d91560723943fff249d8631287b768 | /samples/sample_tests.cpp | 70dda324db262276dc75f75f74820ef6a6a5dca6 | [
"Apache-2.0"
] | permissive | whunmr/msgtest | 6e5db82b2551041c1e5328fa069a2f51364a8069 | 0ada56dce0c23d78018b5667ea3ccf6a7ea3bae0 | refs/heads/master | 2021-01-13T15:19:03.284067 | 2017-10-14T07:07:25 | 2017-10-14T07:07:25 | 76,412,811 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,422 | cpp | #include <gtest/gtest.h>
#include <mockcpp/mockcpp.hpp>
USING_MOCKCPP_NS
#include <msgtest/msgtest.h>
USING_MSGTEST_NS
#include "common/MsgPayload.h"
#include "common/MsgId.h"
#include "app_ids.h"
#include "app.h"
StubActor alice(id_of_alice, msg_proc_of_alice);
StubActor bob(id_of_bob, msg_proc_of_bob);
StubActor clair(id_of_clair, msg_proc_of_clair);
StubActor dan(id_of_dan, msg_proc_of_dan);
TEST(msgtest, should_able_to_support_send_stub_msg__in__DSL_style) {
MsgPayload payload;
alice---->bob(EV_ALICE_REQ, &payload, sizeof(payload));
alice<----bob(EV_ALICE_REQ, &payload, sizeof(payload));
}
TEST(msgtest, should_able_to__auto_detect_payload_len___according_payload_type) {
MsgPayload payload;
alice---->bob(EV_ALICE_REQ, &payload);
alice<----bob(EV_ALICE_REQ, &payload);
}
TEST(msgtest, should_able_to__check_expected___ack_msg_from_bob) {
MsgPayload payload;
msg_interaction(
alice ---->bob(EV_ALICE_REQ, &payload);
alice<<----bob(EV_BOB_RSP);
);
}
TEST(msgtest, should_able_to__check_expected___ack_msg_from_bob____in_reverse_messaging_direction_of_DSL) {
static MsgPayload payload;
msg_interaction(
bob<---- alice(EV_ALICE_REQ, &payload);
bob---->>alice(EV_BOB_RSP);
);
}
TEST(msgtest, should_able_to__support__multiple__msg_interaction) {
MsgPayload payload;
msg_interaction(
alice ---->bob(EV_ALICE_REQ, &payload);
alice<<----bob(EV_BOB_RSP);
);
msg_interaction(
bob<---- alice(EV_ALICE_REQ, &payload);
bob---->>alice(EV_BOB_RSP);
);
}
TEST(msgtest, should_able_to__save_msg_payload___for_further_check_and_inspection) {
MsgSaver<MsgPayloadRsp> rspMsg;
MsgPayload payload;
msg_interaction(
alice ---->bob(EV_ALICE_REQ, &payload);
alice<<----bob(EV_BOB_RSP, ___save_to(rspMsg));
);
EXPECT_EQ(kfieldA_value_in_bob_to_alice_rsp, rspMsg->fieldA);
EXPECT_EQ(kfieldB_value_in_bob_to_alice_rsp, rspMsg->fieldB);
EXPECT_EQ(kfieldC_value_in_bob_to_alice_rsp, rspMsg->fieldC);
}
TEST(msgtest, should_able_to__check_schedule_order___of_expected_msgs) {
MsgSaver<MsgPayloadRsp> bob_to_alice_rsp;
MsgSaver<MsgPayload> alice_to_bob_ack;
MsgPayload payload;
msg_interaction(
alice ------>bob(EV_ALICE_REQ, &payload);
alice<<------bob(EV_BOB_RSP , ___save_to(bob_to_alice_rsp));
alice------>>bob(EV_ALICE_ACK , ___save_to(alice_to_bob_ack));
alice<<------bob(EV_BOB_RELEASE_RESOURCE, ___type(MsgPayloadXXXXX));
alice------>>bob(EV_ALICE_REL_ACK , ___type(MsgPayloadYYY));
);
EXPECT_EQ(kfieldA_value_in_bob_to_alice_rsp, bob_to_alice_rsp->fieldA);
EXPECT_EQ(kfieldA_value_in_alice_to_bob_ack, alice_to_bob_ack->fieldA);
}
TEST(msgtest, should_able_to__let_actor_offline) {
MsgSaver<MsgPayloadRsp> bob_to_alice_rsp;
MsgPayload payload;
alice.offline();
msg_interaction(
alice ------>bob(EV_ALICE_REQ, &payload);
alice<<------bob(EV_BOB_RSP , ___save_to(bob_to_alice_rsp));
alice ------>bob(EV_ALICE_ACK, &payload);
alice<<------bob(EV_BOB_RELEASE_RESOURCE, ___type(MsgPayloadXXXXX));
);
EXPECT_EQ(kfieldA_value_in_bob_to_alice_rsp, bob_to_alice_rsp->fieldA);
}
| [
"whunmr@gmail.com"
] | whunmr@gmail.com |
f4842b4aac48d2e77d4a35d828f211a81887e14b | 618627ee21039a0618ec5f0eba48139c02627e58 | /accelerated_c++/chapter_11/Student_info.cpp | 7e09c613f6669ed77847696265b35e9d4f9a79e4 | [] | no_license | khiner/notebooks | 600cdabcde7e37e997b8b4b7d9a1f6695659c73c | 3a384115bc55bdd0e0b0f784c313d22caf09c987 | refs/heads/master | 2023-02-06T11:09:02.742255 | 2023-02-04T04:02:09 | 2023-02-04T04:02:09 | 114,580,562 | 65 | 12 | null | null | null | null | UTF-8 | C++ | false | false | 1,819 | cpp | #include "Student_info.h"
#include "../chapter_10/grade.h"
#include <algorithm>
#include <iostream>
using std::istream; using std::vector; using std::cout;
using std::copy; using std::back_inserter;
using std::cout; using std::endl;
istream& read_hw(istream& in, vector<double>& hw) {
if (in) {
hw.clear();
double x;
while (in >> x) {
hw.push_back(x);
}
in.clear();
}
return in;
}
Student_info::Student_info(): midterm(0), final(0) { }
Student_info::Student_info(istream& is) {
read(is);
}
Student_info::Student_info(const Student_info& other) {
n = other.n;
midterm = other.midterm;
final = other.final;
total_grade = other.total_grade;
homework = other.homework;
++copy_count;
}
Student_info& Student_info::operator=(const Student_info& other) {
if (this != &other) {
n = other.n;
midterm = other.midterm;
final = other.final;
total_grade = other.total_grade;
homework = other.homework;
}
++assign_count;
return *this;
}
Student_info::~Student_info() {
++destroy_count;
}
double Student_info::grade() const {
return ::grade(midterm, final, homework);
}
bool Student_info::passed_for_pass_fail() const {
return ::passed_for_pass_fail(midterm, final);
}
istream& Student_info::read(istream& is) {
is >> n >> midterm >> final;
read_hw(is, homework);
total_grade = valid() ? grade() : 0;
return is;
}
bool compare(const Student_info& x, const Student_info& y) {
return x.name() < y.name();
}
void print_instrumentation() {
std::cout << "Total copies: " << copy_count << std::endl;
std::cout << "Total assignments: " << assign_count << std::endl;
std::cout << "Total destroys: " << destroy_count << std::endl;
}
| [
"karl.hiner@gmail.com"
] | karl.hiner@gmail.com |
0766775ec3cc46be0df3270236fd6aad84908687 | ab6de7c1dd21518133eace41dd60b7d6de88ef3d | /duilib-master3/libiphone/tools/idevicebackup2/stdafx.cpp | 16f659b01cdf65622ecb4bf37d1f5c7afa10d0d1 | [
"MIT",
"BSD-2-Clause"
] | permissive | HSHtime/myduilib1 | 407c3bc07ed1363285f498ae8f30d2d3cf275add | 67ed9c636d0a6b7677b24d8d8824aece11e08db2 | refs/heads/master | 2020-06-03T19:35:50.504165 | 2015-07-13T02:01:00 | 2015-07-13T02:01:00 | 32,507,322 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | // stdafx.cpp : source file that includes just the standard includes
// idevicebackup2.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"747423692@qq.com"
] | 747423692@qq.com |
6b4f1034a14ad92cae49bd5da7126e083d824d62 | 35be548bf0644ed170bff1fb79e216cb577e6f9d | /db/kv_store_iterator.hh | 838be178d25b791c5d961623e83450806aaa429d | [] | no_license | olzhabay/mobiledb | da251f96b0eed055d46745ac2107e45f5c978eb7 | 1fbdb16c36f8b8d6709ec8f36cf5b97a999381d0 | refs/heads/master | 2020-03-20T05:40:13.327027 | 2018-06-27T09:23:00 | 2018-06-27T09:23:00 | 137,222,698 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | hh | #ifndef MOBILEDB_KV_STORE_ITERATOR_HH
#define MOBILEDB_KV_STORE_ITERATOR_HH
#include "../common/iterator.hh"
#include "btree_iterator.hh"
class KVStoreIterator : public Iterator {
public:
explicit KVStoreIterator(Btree* btree) : btree_iterator(new BtreeIterator(btree)) { }
~KVStoreIterator() override;
bool Valid() const override;
void SeekToFirst() override;
void SeekToLast() override;
void Seek(const Slice& target) override;
void Next() override;
void Prev() override;
Slice key() const override;
Slice value() const override;
Status status() const override;
private:
BtreeIterator* btree_iterator;
};
#endif //MOBILEDB_KV_STORE_ITERATOR_HH
| [
"olzhabay.i@gmail.com"
] | olzhabay.i@gmail.com |
8d7be92a7c3e2a95bac94d5b143f71099efc0864 | 8361892bf82ba74678c2d9cb17007eac89ed4b1a | /modul6/6_4_4.4/main.cpp | bd605523ecf934feca2a67ad57d2256e19383b5e | [] | no_license | sergey-buryakov/CEssLabs | d53c898e589d7163fac9a49999e07b73aa70fe66 | bef827736f5e7b559b609ace94194ee35c8f8eff | refs/heads/master | 2021-08-30T07:42:45.060856 | 2017-12-16T20:33:48 | 2017-12-16T20:33:48 | 110,965,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 782 | cpp | #include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int myfield[3][3], enemyfield[3][3];
int main()
{
cout << "BattleShip. Draw your battlefield and setup ships. Then enter coordinates of your shoot in format x y" << endl;
srand(time(0));
myfield[rand() % 3][rand() % 3] = 1;
string line = "";
int xe, ye, x, y;
do {
do {
x = rand() % 3;
y = rand() % 3;
} while (enemyfield[x][y] == -1);
enemyfield[x][y] = -1;
do
{
cin >> line;
xe = atoi(line.c_str());
cin >> line;
ye = atoi(line.c_str());
} while (myfield[xe][ye] == -1);
if (myfield[xe][ye] == 1) break;
myfield[xe][ye] = -1;
cout << "comp: ";
cout << x << " " << y << endl;
} while(true);
cout << "you win" << endl;
return 0;
}
| [
"sergey12.01.98@gmail.com"
] | sergey12.01.98@gmail.com |
c583a29b9f5163af89a549f167bbc7b4fe027f88 | dc664b270b75290c8d5839845309cf7e3cf9928d | /DataStructure_Lab/LAB06/DS-Lab06-HeterogeneousLists-solution/DS-Lab06-HeterogeneousLists-solution (Ver. Console)/Application.cpp | 08f9375ae10309d5bb8f64724028e80725bbb285 | [] | no_license | Hoony0321/DataStructure_LAB1-8 | 069ff82ac92e9abfa4b0906a502751ba210e822e | 0ed45d628549bfdd372d5af3efc4e2c80f95c858 | refs/heads/master | 2023-01-06T01:11:26.413122 | 2020-10-31T08:28:13 | 2020-10-31T08:28:13 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,087 | cpp | #include "Application.h"
/*====================================================================================
// Function : default constructor, Initialize member variables.
// Pre : None
// Post : None
=====================================================================================*/
Application::Application()
{
m_NewNode = NULL;
}
/*====================================================================================
// Function : default destructor,
// Pre : None
// Post : None
=====================================================================================*/
Application::~Application()
{
}
/*====================================================================================
// Function : Program driver
// Pre : none
// Post : none
=====================================================================================*/
void Application::Run()
{
List gObj;
int ex = 1, tmp;
while(ex)
{
system("cls");
m_NewNode = NULL;
switch(tmp = GetCommand())
{
case 0:
ex = 0;
break;
case 1:
m_NewNode = new CircleNode();
m_NewNode->draw();
break;
case 2:
m_NewNode = new RectangleNode();
m_NewNode->draw();
break;
case 3:
m_NewNode = new PolygonNode();
m_NewNode->draw();
break;
case 4:
gObj.drawAll();
break;
default:
cout << " Invalid Command. Try Again \n";
}
if (m_NewNode != NULL)
{
m_NewNode->draw();
gObj.Attach(m_NewNode);
}
system("pause");
}
}
/*====================================================================================
// Function: Display command on screen and get a input from keyboard
// Pre:
// Post : get command number.
=====================================================================================*/
int Application::GetCommand()
{
int cmmd;
cout << "\n << Graphic Object 입력(draw)와 출력(display) >>\n";
cout << " 1: Circle Draw \n";
cout << " 2: Rectangle Draw \n";
cout << " 3: Polygon Draw \n";
cout << " 4: Display All \n";
cout << " 0: Quit \n";
cin >> cmmd;
return cmmd;
} | [
"eogns0824@naver.com"
] | eogns0824@naver.com |
2df133476f7e928bf4a012d21d545d872d6925e6 | 260e5dec446d12a7dd3f32e331c1fde8157e5cea | /Indi/SDK/Indi_ConversationWidget_BP_parameters.hpp | 5726985ff0e33c1c0c8adbdc8f0049d3d49a9c50 | [] | no_license | jfmherokiller/TheOuterWorldsSdkDump | 6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0 | 18a8c6b1f5d87bb1ad4334be4a9f22c52897f640 | refs/heads/main | 2023-08-30T09:27:17.723265 | 2021-09-17T00:24:52 | 2021-09-17T00:24:52 | 407,437,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,714 | hpp | #pragma once
// TheOuterWorlds SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "Indi_ConversationWidget_BP_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function ConversationWidget_BP.ConversationWidget_BP_C.OnIntro
struct UConversationWidget_BP_C_OnIntro_Params
{
struct FScriptDelegate* AnimationCompleteCallback; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function ConversationWidget_BP.ConversationWidget_BP_C.Get_Line0_Visibility_1
struct UConversationWidget_BP_C_Get_Line0_Visibility_1_Params
{
ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function ConversationWidget_BP.ConversationWidget_BP_C.Get_Line1_Visibility_1
struct UConversationWidget_BP_C_Get_Line1_Visibility_1_Params
{
ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function ConversationWidget_BP.ConversationWidget_BP_C.SetConversationBackingFillRatio
struct UConversationWidget_BP_C_SetConversationBackingFillRatio_Params
{
float* DesiredOverlayHeight; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function ConversationWidget_BP.ConversationWidget_BP_C.SetHistoryBackingFillRatio
struct UConversationWidget_BP_C_SetHistoryBackingFillRatio_Params
{
float* DesiredHistoryHeight; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function ConversationWidget_BP.ConversationWidget_BP_C.Construct
struct UConversationWidget_BP_C_Construct_Params
{
};
// Function ConversationWidget_BP.ConversationWidget_BP_C.ExecuteUbergraph_ConversationWidget_BP
struct UConversationWidget_BP_C_ExecuteUbergraph_ConversationWidget_BP_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"peterpan0413@live.com"
] | peterpan0413@live.com |
37bb6060d4328b866cec7e2065f25d43a3d5ea1c | e48f8d266f91916c868c536b940cdb0bc86fd46e | /a3_handout/demosaic.cpp | ce71a205299c1aa9f3bed86b0a29ef41aed1b349 | [] | no_license | VictorCheng98/6.815 | ef5562ae2aa026fdd297e76cd565cc629fa21085 | f86cc0dc2dfb2a4f10d31f7e597a55a243ee87bd | refs/heads/master | 2020-07-22T10:30:00.653636 | 2019-10-01T20:22:43 | 2019-10-01T20:22:43 | 207,168,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,655 | cpp | /* --------------------------------------------------------------------------
* File: demosaic.cpp
* Created: 2015-10-01
* --------------------------------------------------------------------------
*
*
*
* ------------------------------------------------------------------------*/
#include "demosaic.h"
#include <cmath>
using namespace std;
Image basicGreen(const Image &raw, int offset) {
// --------- HANDOUT PS03 ------------------------------
// Takes as input a raw image and returns a single-channel
// 2D image corresponding to the green channel using simple interpolation
return raw;
}
Image basicRorB(const Image &raw, int offsetX, int offsetY) {
// --------- HANDOUT PS03 ------------------------------
// Takes as input a raw image and returns a single-channel
// 2D image corresponding to the red or blue channel using simple
// interpolation
return raw;
}
Image basicDemosaic(const Image &raw, int offsetGreen, int offsetRedX,
int offsetRedY, int offsetBlueX, int offsetBlueY) {
// --------- HANDOUT PS03 ------------------------------
// takes as input a raw image and returns an rgb image
// using simple interpolation to demosaic each of the channels
return raw;
}
Image edgeBasedGreen(const Image &raw, int offset) {
// --------- HANDOUT PS03 ------------------------------
// Takes a raw image and outputs a single-channel
// image corresponding to the green channel taking into account edges
return raw;
}
Image edgeBasedGreenDemosaic(const Image &raw, int offsetGreen, int offsetRedX,
int offsetRedY, int offsetBlueX, int offsetBlueY) {
// --------- HANDOUT PS03 ------------------------------
// Takes as input a raw image and returns an rgb image
// using edge-based green demosaicing for the green channel and
// simple interpolation to demosaic the red and blue channels
return raw;
}
Image greenBasedRorB(const Image &raw, Image &green, int offsetX, int offsetY) {
// --------- HANDOUT PS03 ------------------------------
// Takes as input a raw image and returns a single-channel
// 2D image corresponding to the red or blue channel using green based
// interpolation
return raw;
}
Image improvedDemosaic(const Image &raw, int offsetGreen, int offsetRedX,
int offsetRedY, int offsetBlueX, int offsetBlueY) {
// // --------- HANDOUT PS03 ------------------------------
// Takes as input a raw image and returns an rgb image
// using edge-based green demosaicing for the green channel and
// simple green based demosaicing of the red and blue channels
return raw;
}
| [
"vbc@mit.edu"
] | vbc@mit.edu |
8211a895bc5c5b78d54109fc27ba3594911d6132 | e43451d16e7ae4dd1b1720b6aa5b36cc7cc5a879 | /include/openeaagles/maps/rpf/CadrgFile.hpp | 551987f4ec5f5798c932ab0a2b9daa8f7b15874d | [] | no_license | whztt1989/OpenEaagles | 8909c5308626479168bb8303c9307d408f627488 | 804bd58e3193d4cde87cf30e772cf218ce552f0b | refs/heads/master | 2021-01-12T11:43:17.150736 | 2016-10-28T18:15:59 | 2016-10-28T18:15:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | hpp |
#ifndef __oe_maps_rpf_CadrgFile_H__
#define __oe_maps_rpf_CadrgFile_H__
#include "openeaagles/base/Object.hpp"
namespace oe {
namespace base { class String; }
namespace rpf {
class CadrgTocEntry;
//------------------------------------------------------------------------------
// Class: CadrgFile
//
// Description:
// This is the data file that is created by CadrgMap when the CADRG files are '
// initially loaded. These files contain all the TocEntries that are created,
// and can be accessed by the MapDrawer to draw easily.
//
// Subroutines:
// entry() - Returns a Toc Entry at the boundary given, if it's within
// our boundaries.
// int getNumBoundaries() { return numBoundaries; }
//
// entry() - Returns a CONST Toc Entry at the boundary given, if it's within
// our boundaries.
// const CadrgTocEntry* entry(int boundaryIndex) const;
//
// entry() - Returns a Toc Entry at the boundary given, if it's within
// our boundaries.
// CadrgTocEntry* entry(int boundaryIndex);
//
// setEntries() - Sets a whole new list of Toc Entries.
// virtual void setEntries(CadrgTocEntry* newEntries[MAX_TOC_ENTRIES]);
//
// addTocEntry() - Adds a Toc entry
// virtual void addTocEntry(CadrgTocEntry* newEntry, const int idx);
//
// removeTocEntry() - Removes a Toc entry
// virtual void removeTocEntry(const int idx);
//
// initialize our file to create entries and such
// virtual void initialize(const char* dir);
//
// check for map data in a particular directory
// virtual bool checkForMap(const char* dir)
//
// Note - when creating an instance of this, make sure to initialize it or the
// file will never get loaded.
//
//------------------------------------------------------------------------------
class CadrgFile : public base::Object
{
DECLARE_SUBCLASS(CadrgFile, base::Object)
public:
CadrgFile();
// Max number of Toc entries we can have.
static const int MAX_TOC_ENTRIES = 50;
// Get / Set / Add / Initialize
int getNumBoundaries() { return numBoundaries; }
const CadrgTocEntry* entry(int boundaryIndex) const;
CadrgTocEntry* entry(int boundaryIndex);
virtual void setEntries(CadrgTocEntry* newEntries[MAX_TOC_ENTRIES]);
virtual void addTocEntry(CadrgTocEntry* newEntry, const int idx);
virtual void removeTocEntry(const int idx);
// Initialize our file to create entries and such
virtual bool initialize(const char* dir);
// check for map data in a certain directory
static bool checkForMap(const char* dir);
// get our original directory
const char* getDirectory();
void setDirectory(const char* x);
private:
int numBoundaries; // How many boundaries are there?
CadrgTocEntry* entries[MAX_TOC_ENTRIES]; // Holds our table of contents entries
bool cib; // CIB flag
base::String* originalDir; // directory of the file we are associated with
};
}
}
#endif
| [
"doug@openeaagles.org"
] | doug@openeaagles.org |
f0a04bfe7156b732f2a402fb12d039de9320b440 | afdfe6b9f9871c6432fbe35c3ee4ac031cfee576 | /Src/RenderClasses/R0032Bh.h | ea91e5d267ba6fb5295fa12755c29f56445c9787 | [] | no_license | RomanHargrave/skulls3d | df5986c8286f1485678dc209c4a9a79a2026fa4f | 9a810c510fe57144c071f8f96ba58d5a5ff45cc0 | refs/heads/master | 2020-04-06T06:49:23.831615 | 2012-08-09T17:57:46 | 2012-08-09T17:57:46 | 35,354,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | h |
#ifndef SWE_R0032BH
#define SWE_R0032BH
#include "R0030FlatVirtual.h"
class R0032Bh : public R0030FlatVirtual
{
public:
R0032Bh(Scene *scene, Camera *camera, ViewPort *viewport);
void FillOrderedPoly(const Vec3f & v0, const Vec3f & v1, const Vec3f & v2, unsigned char shade);
};
#endif // SWE_R0032BH | [
"gabriel.bizzotto@9012b7bc-1e1c-11df-ae22-3371deb0c1a1"
] | gabriel.bizzotto@9012b7bc-1e1c-11df-ae22-3371deb0c1a1 |
9f6d5829777e14862d15bebd811feb899ec7a18f | 08c9ff62adfe33bf42f2dfb452221b569cca2f84 | /include/elemental/lapack-like/HPSDSquareRoot.hpp | 92a3d6a1fc29d60156ca2ee192cafed59cdcad11 | [] | no_license | fagan2888/Elemental | b07b6277b6dc0c8e8511de36e96b880b27f6d5c7 | ee8155dce27a3b25d8869122f2d916fdda70f415 | refs/heads/master | 2021-01-06T13:50:54.671009 | 2013-04-22T16:50:15 | 2013-04-22T16:50:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,229 | hpp | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef LAPACK_HPSDSQUAREROOT_HPP
#define LAPACK_HPSDSQUAREROOT_HPP
#ifdef HAVE_PMRRR
#include "elemental/lapack-like/HermitianFunction.hpp"
#include "elemental/lapack-like/Norm/Max.hpp"
namespace elem {
//
// Square root the eigenvalues of A (and treat the sufficiently small negative
// ones as zero).
//
template<typename F>
inline void
HPSDSquareRoot( UpperOrLower uplo, DistMatrix<F>& A )
{
#ifndef RELEASE
PushCallStack("HPSDSquareRoot");
#endif
typedef typename Base<F>::type R;
// Get the EVD of A
const Grid& g = A.Grid();
DistMatrix<R,VR,STAR> w(g);
DistMatrix<F> Z(g);
HermitianEig( uplo, A, w, Z );
// Compute the two-norm of A as the maximum absolute value of the eigvals
const R twoNorm = MaxNorm( w );
// Compute the smallest eigenvalue of A
R minLocalEig = twoNorm;
const int numLocalEigs = w.LocalHeight();
for( int iLocal=0; iLocal<numLocalEigs; ++iLocal )
{
const R omega = w.GetLocal(iLocal,0);
minLocalEig = std::min(minLocalEig,omega);
}
R minEig;
mpi::AllReduce( &minLocalEig, &minEig, 1, mpi::MIN, g.VCComm() );
// Set the tolerance equal to n ||A||_2 eps
const int n = A.Height();
const R eps = lapack::MachineEpsilon<R>();
const R tolerance = n*twoNorm*eps;
// Ensure that the minimum eigenvalue is not less than - n ||A||_2 eps
if( minEig < -tolerance )
throw NonHPSDMatrixException();
// Overwrite the eigenvalues with f(w)
for( int iLocal=0; iLocal<numLocalEigs; ++iLocal )
{
const R omega = w.GetLocal(iLocal,0);
if( omega > R(0) )
w.SetLocal(iLocal,0,Sqrt(omega));
else
w.SetLocal(iLocal,0,0);
}
// Form the pseudoinverse
hermitian_function::ReformHermitianMatrix( uplo, A, w, Z );
#ifndef RELEASE
PopCallStack();
#endif
}
} // namespace elem
#endif // ifdef HAVE_PMRRR
#endif // ifndef LAPACK_HPSDSQUAREROOT_HPP
| [
"jack.poulson@gmail.com"
] | jack.poulson@gmail.com |
ce4e7db64f3cdf3b8f8ce018623d9beb06362e65 | 53f343023df12ac59d9489de9c0c3611b2cb6bfa | /Chapter7/ex7_4.cpp | 674ab5fd534056c108029e1eb8ff3f365281f8d3 | [] | no_license | Sparrow-hawks/C-Primer-Plus-Exercises | 0b1884a25e08fe77cc7bd2038b4602376a11961e | ae9e3df0336b6edaa969d9aae2b04e6808ed8c87 | refs/heads/master | 2021-04-09T15:44:10.300636 | 2018-03-18T14:54:45 | 2018-03-18T14:54:45 | 125,735,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 881 | cpp | // Book: C++ Primer Plus
// Chapter: 7
// Exercise: 4
#include <iostream>
long double probality(unsigned numbers, unsigned picks);
int main(void) {
double total, choices, mega;
std::cout << "Podaj największą liczbę, jaką można wybrać, oraz\n"
"liczbę skreśleń, oraz megaliczbę:\n";
while ((std::cin >> total >> choices >> mega) && choices <= total) {
std::cout << "Szansa wygranej to jeden do ";
std::cout << probality(total, choices) * probality(mega, 1);
std::cout << ".\n";
std::cout << "Następne dwie liczby (q, aby zakończyć): ";
std::cout.flush();
}
std::cout << "Do widzenia!" << std::endl;
return 0;
}
long double probality(unsigned numbers, unsigned picks) {
long double result = 1.0;
long double n = numbers;
for (unsigned p = picks; p > 0; n--, p--)
result = result * n / p;
return result;
}
| [
"sparrow-hawk@hotmail.com"
] | sparrow-hawk@hotmail.com |
03e0e857be82c57b3372570d5cb9f6b0a7748865 | c8c809988c1ea78dd7b267158f193b43233b7055 | /include/simulator.hh | 037a5a1551a00e83e848841241f10b23f9e93ccb | [] | no_license | aschiffer186/Analysis | 7c6a0debfe86defb0e72a25b3886ee897c98ec54 | b5b52e7c5f9034548c0debb9f630e5c3f2c0f1b6 | refs/heads/main | 2023-03-16T01:34:34.406449 | 2021-02-25T22:07:02 | 2021-02-25T22:07:02 | 339,808,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,991 | hh | #ifndef SIMULATOR_HH
#define SIMULATOR_HH
#include <vector>
#include <array>
#include "wrappers.hh"
#include <random>
#include <chrono>
struct ecdf_t
{
std::vector<double> _M_xpts;
std::vector<double> _M_cdf_pts;
};
class simulator
{
private:
struct func_params
{
double _M_u;
spline_ptr _M_spline;
};
public:
//Creates a new simulator that will provide a predictive model for the given set
//data points.
//
//@param data the data to use for the simulation
simulator(const std::vector<double>& data);
std::vector<double> simulate(size_t num_sims, size_t num_people);
template<typename _FuncTp, typename... _ArgsTp>
std::vector<std::vector<double>> simulate(size_t num_sims, size_t num_people, _FuncTp coupled, _ArgsTp&&... args)
{
std::vector<double> results(num_sims);
std::vector<double> matching(num_sims);
for(size_t i = 0; i < num_sims; ++i)
{
double realization = 0;
double matching_realization = 0;
for(size_t j = 0; j < num_people; ++j)
{
double u = unif(rng);
double sample = perform_sample(u);
realization += sample;
u = unif(rng);
matching_realization += coupled(sample, u, std::forward<_ArgsTp>(args)...);
}
results[i] = realization;
matching[i] = matching_realization;
}
return {results, matching};
}
private:
void make_ecdf(std::vector<double> data);
double perform_sample(double u);
static double cdf_inv(double x, void* p);
static double cdf_func(double x, gsl_spline* s);
private:
std::uniform_real_distribution<double> unif;
std::mt19937_64 rng;
ecdf_t _M_ecdf;
};
#endif | [
"aschiffe@umich.edu"
] | aschiffe@umich.edu |
9150e4e7976b86ab48018b63e7f73eca8bc578be | 9aa40cfa1091bb187a42ac017b3bf5488c9763d4 | /Futures/src/AsyncAwait.h | a867290036791f965faa87e41559022e78a3422d | [] | no_license | LeeHowes/CPP | d00604a529bceb74e648cb12d5c912bd97089798 | ec3b0a33957ca62eab4a1ad8d18146d406be69b6 | refs/heads/master | 2022-07-23T07:30:50.395540 | 2022-07-14T22:27:22 | 2022-07-14T22:27:22 | 102,652,869 | 2 | 6 | null | 2022-05-14T00:00:16 | 2017-09-06T20:03:14 | HTML | UTF-8 | C++ | false | false | 3,216 | h | #pragma once
#include <experimental/coroutine>
#include "Executor.h"
template<class T>
struct AsyncAwaitAwaitable {
struct promise_type;
using handle = std::experimental::coroutine_handle<promise_type>;
AsyncAwaitAwaitable(AsyncAwaitAwaitable&& rhs) : coroutine_handle_{std::move(rhs.coroutine_handle_)} {
rhs.coroutine_handle_ = {};
}
AsyncAwaitAwaitable(handle&& rhs) : coroutine_handle_{std::move(rhs)} {
}
~AsyncAwaitAwaitable() {
if(coroutine_handle_) {
coroutine_handle_.destroy();
}
}
struct promise_type {
T value{};
std::shared_ptr<DrivenExecutor> executor;
std::function<void(T)> callback;
// Sync awaitable has an executor that will be driven inline in the caller
promise_type() {
}
struct final_suspend_result : std::experimental::suspend_always {
promise_type *promise_;
final_suspend_result(promise_type* promise) : promise_{promise} {}
bool await_ready(){ return false; }
void await_suspend(std::experimental::coroutine_handle<>) {
promise_->executor->execute(
[cb = std::move(promise_->callback), val = promise_->value](){
cb(std::move(val));
});
}
void await_resume() {}
};
auto initial_suspend() {
return std::experimental::suspend_always{};
}
auto final_suspend() {
return final_suspend_result{this};
}
void return_value(T val) {
value = std::move(val);
}
auto get_return_object() {
return AsyncAwaitAwaitable{handle::from_promise(*this)};
}
void unhandled_exception() {
}
};
void setExecutor(std::shared_ptr<DrivenExecutor> exec) {
coroutine_handle_.promise().executor = exec;
}
void setCallback(std::function<void(T)> callback) {
coroutine_handle_.promise().callback = std::move(callback);
}
handle coroutine_handle_;
};
// async_await will call callback on exec when the awaitable completes.
template<class Awaitable, class T = std::decay_t<decltype(std::declval<Awaitable>().await_resume())>, class F>
void async_await(
std::shared_ptr<DrivenExecutor> exec,
Awaitable&& aw,
F&& callback) {
auto a = [](Awaitable aw) -> AsyncAwaitAwaitable<T> {
int val = co_await aw;
co_return val;
};
auto spa = std::make_shared<AsyncAwaitAwaitable<T>>(a(std::forward<Awaitable>(aw)));
spa->setExecutor(exec);
// Ensure that spa stays alive at least until the callback completes
spa->setCallback(std::function<void(T)>{[spa, cb = std::move(callback)](T&& val){
cb(std::move(val));
}});
// Move awaitable onto the heap to extend its lifetime, enqueue a task that resumes it
spa->coroutine_handle_.promise().executor->execute([spa](){
spa->coroutine_handle_.resume();});
spa.reset();
}
| [
"lwh@fb.com"
] | lwh@fb.com |
c26fa690bb816e0066a281b36562e672f4bbaad0 | 269e13a077d3ef90d4c352249fb6e32d2360a4ec | /leetcode/tree/199-Binary-Tree-Right-Side-View.cpp | 4441650ec8da11b0749b0b7b81438b7825b41ad5 | [] | no_license | luckyzahuo/Snorlax | d3df462ee484ecd338cde05869006f907e684153 | 51cf7e313fddee6fd00c2a276b43c48013375618 | refs/heads/master | 2023-08-21T11:02:01.975516 | 2021-10-10T08:50:40 | 2021-10-10T08:50:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | cpp |
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/*
* 返回二叉树的“右视图”,其实就是每一层中最右边的元素,队列实现即可。
* 如果题目修改要求,求“左视图”的话,对代码稍加修改即可
*/
class Solution {
private:
vector<int> res;
public:
vector<int> rightSideView(TreeNode* root) {
if (root == nullptr) return res;
TreeNode *current = root;
queue<TreeNode *> levelQueue;
levelQueue.push(current);
while (!levelQueue.empty()) {
int queueSize = levelQueue.size();
// 如果要求“左视图”的话, levelQueue.back() 替换成 levelQueue.front() 即可
res.push_back(levelQueue.back()->val);
for (int i = 0; i < queueSize; i++) {
current = levelQueue.front();
levelQueue.pop();
if (current->left) levelQueue.push(current->left);
if (current->right) levelQueue.push(current->right);
}
}
return res;
}
};
| [
"smartkeyerror@gmail.com"
] | smartkeyerror@gmail.com |
482dc9a9056c8b56c7e28baa4b9dfbb69a8b987d | 067690553cf7fa81b5911e8dd4fb405baa96b5b7 | /2079/2079.cpp14.cpp | bc9010da8b8e1aca0c044af67445708dc0f2f127 | [
"MIT"
] | permissive | isac322/BOJ | 4c79aab453c884cb253e7567002fc00e605bc69a | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | refs/heads/master | 2021-04-18T22:30:05.273182 | 2019-02-21T11:36:58 | 2019-02-21T11:36:58 | 43,806,421 | 14 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 1,566 | cpp | #include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
class OnlinePalindromeChecker {
private:
/* Number of characters in the alphabet */
const int d;
/* modulo constant */
const int M;
/* hashcode of first half and second half */
long long half1 = 0, half2 = 0;
long long coefficient = 1;
std::string s;
public:
OnlinePalindromeChecker(const int d = 26, const int M = 1'000'000'007) : d(d), M(M) {}
bool insertChar(const char ch) {
s.push_back(ch);
const std::size_t len = s.size();
if (len < 3) {
if (len == 1) {
half1 = ch % M;
return true;
}
else if (len == 2) {
half2 = ch % M;
return s[0] == s[1];
}
}
else if (len & 1) {
half2 = (d*(M + half2 - (s[len / 2] * coefficient) % M) % M + ch) % M;
}
else {
coefficient = coefficient*d % M;
half1 = (half1 + coefficient*s[len / 2 - 1]) % M;
half2 = (half2*d + ch) % M;
}
if (half1 == half2) {
bool isPalindrome = true;
for (int i = 0; i < len / 2; i++) {
if (s[i] != s[len - i - 1]) isPalindrome = false;
}
return isPalindrome;
}
else return false;
}
};
char str[2001];
int dp[2000], n;
int solve(int index) {
if (index >= n) return 0;
int &p = dp[index];
if (p != -1) return p;
OnlinePalindromeChecker checker;
p = n - index - 1;
for (int i = index; i < n; i++) {
if (checker.insertChar(str[i] - 'a')) {
p = min(p, solve(i + 1));
}
}
return ++p;
}
int main() {
scanf("%s", str);
n = strlen(str);
fill_n(dp, n, -1ll);
printf("%d", solve(0));
} | [
"isac322@naver.com"
] | isac322@naver.com |
8bac41892793009f893bdbab50c52038d4c6b685 | fb653a222497d03db916b84824bebaf98cf302bb | /src/qt/notificator.cpp | 223bdc08650da582dbb858de1c22037e69e247af | [
"MIT"
] | permissive | bumbacoin/CommunityCoin1.5.1 | e3581f7ca06e06d6c86118ab54164d1836002720 | 59edc82ed438d5f0036fab66b879cadca768cbb1 | refs/heads/master | 2021-01-13T14:20:11.965494 | 2015-07-22T09:30:03 | 2015-07-22T09:30:03 | 37,983,671 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,090 | cpp | #include "notificator.h"
#include <QMetaType>
#include <QVariant>
#include <QIcon>
#include <QApplication>
#include <QStyle>
#include <QByteArray>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QTemporaryFile>
#include <QImageWriter>
#ifdef USE_DBUS
#include <QtDBus/QtDBus>
#include <stdint.h>
#endif
#ifdef Q_OS_MAC
#include "macnotificationhandler.h"
#include <ApplicationServices/ApplicationServices.h>
#endif
// https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;
Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):
QObject(parent),
parent(parent),
programName(programName),
mode(None),
trayIcon(trayicon)
#ifdef USE_DBUS
,interface(0)
#endif
{
if(trayicon && trayicon->supportsMessages())
{
mode = QSystemTray;
}
#ifdef USE_DBUS
interface = new QDBusInterface("org.freedesktop.Notifications",
"/org/freedesktop/Notifications", "org.freedesktop.Notifications");
if(interface->isValid())
{
mode = Freedesktop;
}
#endif
#ifdef Q_OS_MAC
// check if users OS has support for NSUserNotification
if( MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) {
mode = UserNotificationCenter;
}
else {
// Check if Growl is installed (based on Qt's tray icon implementation)
CFURLRef cfurl;
OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
if (status != kLSApplicationNotFoundErr) {
CFBundleRef bundle = CFBundleCreate(0, cfurl);
if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {
if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/")))
mode = Growl13;
else
mode = Growl12;
}
CFRelease(cfurl);
CFRelease(bundle);
}
}
#endif
}
Notificator::~Notificator()
{
#ifdef USE_DBUS
delete interface;
#endif
}
#ifdef USE_DBUS
// Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
class FreedesktopImage
{
public:
FreedesktopImage() {}
FreedesktopImage(const QImage &img);
static int metaType();
// Image to variant that can be marshalled over DBus
static QVariant toVariant(const QImage &img);
private:
int width, height, stride;
bool hasAlpha;
int channels;
int bitsPerSample;
QByteArray image;
friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);
friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);
};
Q_DECLARE_METATYPE(FreedesktopImage);
// Image configuration settings
const int CHANNELS = 4;
const int BYTES_PER_PIXEL = 4;
const int BITS_PER_SAMPLE = 8;
FreedesktopImage::FreedesktopImage(const QImage &img):
width(img.width()),
height(img.height()),
stride(img.width() * BYTES_PER_PIXEL),
hasAlpha(true),
channels(CHANNELS),
bitsPerSample(BITS_PER_SAMPLE)
{
// Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.constBits());
unsigned int num_pixels = width * height;
image.resize(num_pixels * BYTES_PER_PIXEL);
for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)
{
image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R
image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; // G
image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; // B
image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A
}
}
QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)
{
a.beginStructure();
a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)
{
a.beginStructure();
a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
a.endStructure();
return a;
}
int FreedesktopImage::metaType()
{
return qDBusRegisterMetaType<FreedesktopImage>();
}
QVariant FreedesktopImage::toVariant(const QImage &img)
{
FreedesktopImage fimg(img);
return QVariant(FreedesktopImage::metaType(), &fimg);
}
void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
Q_UNUSED(cls);
// Arguments for DBus call:
QList<QVariant> args;
// Program Name:
args.append(programName);
// Unique ID of this notification type:
args.append(0U);
// Application Icon, empty string
args.append(QString());
// Summary
args.append(title);
// Body
args.append(text);
// Actions (none, actions are deprecated)
QStringList actions;
args.append(actions);
// Hints
QVariantMap hints;
// If no icon specified, set icon based on class
QIcon tmpicon;
if(icon.isNull())
{
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch(cls)
{
case Information: sicon = QStyle::SP_MessageBoxInformation; break;
case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
default: break;
}
tmpicon = QApplication::style()->standardIcon(sicon);
}
else
{
tmpicon = icon;
}
hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
args.append(hints);
// Timeout (in msec)
args.append(millisTimeout);
// "Fire and forget"
interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
}
#endif
void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
Q_UNUSED(icon);
QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
switch(cls) // Set icon based on class
{
case Information: sicon = QSystemTrayIcon::Information; break;
case Warning: sicon = QSystemTrayIcon::Warning; break;
case Critical: sicon = QSystemTrayIcon::Critical; break;
}
trayIcon->showMessage(title, text, sicon, millisTimeout);
}
// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
{
const QString script(
"tell application \"%5\"\n"
" set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
" set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
" register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
" notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
"end tell"
);
QString notificationApp(QApplication::applicationName());
if (notificationApp.isEmpty())
notificationApp = "Application";
QPixmap notificationIconPixmap;
if (icon.isNull()) { // If no icon specified, set icon based on class
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch (cls)
{
case Information: sicon = QStyle::SP_MessageBoxInformation; break;
case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
}
notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
}
else {
QSize size = icon.actualSize(QSize(48, 48));
notificationIconPixmap = icon.pixmap(size);
}
QString notificationIcon;
QTemporaryFile notificationIconFile;
if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
QImageWriter writer(¬ificationIconFile, "PNG");
if (writer.write(notificationIconPixmap.toImage()))
notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
}
QString quotedTitle(title), quotedText(text);
quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
quotedText.replace("\\", "\\\\").replace("\"", "\\");
QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
MacNotificationHandler::instance()->sendAppleScript(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp));
}
void Notificator::notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon) {
// icon is not supported by the user notification center yet. OSX will use the app icon.
MacNotificationHandler::instance()->showNotification(title, text);
}
#endif
void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
switch(mode)
{
#ifdef USE_DBUS
case Freedesktop:
notifyDBus(cls, title, text, icon, millisTimeout);
break;
#endif
case QSystemTray:
notifySystray(cls, title, text, icon, millisTimeout);
break;
#ifdef Q_OS_MAC
case UserNotificationCenter:
notifyMacUserNotificationCenter(cls, title, text, icon);
break;
case Growl12:
case Growl13:
notifyGrowl(cls, title, text, icon);
break;
#endif
default:
if(cls == Critical)
{
// Fall back to old fashioned pop-up dialog if critical and no other notification available
QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
}
break;
}
} | [
"bumbacoin@gmail.com"
] | bumbacoin@gmail.com |
f6b9f3894da84c498a2db1fed1f4adaa4c1568e1 | 827d09cc9b6f4856c2e9d6f1fd90bf224b8bf3a2 | /sources/antimalware_client.cpp | 018f976713196cc53c509835b4a9f841461112ea | [] | no_license | NickBabakin/antimalware | 2a0cfd32d3c7a92f36cfc51efe9fe6f91347e79b | 605bb33d2edfabe3da17999c94c713c8d494ec6f | refs/heads/master | 2023-06-11T07:48:49.786755 | 2021-07-07T20:36:45 | 2021-07-07T20:36:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,372 | cpp | //
// Created by niickson on 7/5/21.
//
#include "antimalware_client.hpp"
antimalware_client::antimalware_client() {}
std::string antimalware_client::request() {
nlohmann::json req;
std::cout << "Enter directory name: ";
std::string input;
std::cin >> input;
req["directory"] = input;
return req.dump();
}
void antimalware_client::parse_response(const std::string &response, std::ostream& out) {
nlohmann::json res;
try {
res = nlohmann::json::parse(response);
} catch (const nlohmann::detail::parse_error &e) {
throw std::runtime_error("Not json response");
}
if (res.contains("error")){
out << res["error"] << std::endl;
} else {
out << "=========== SCAN RESULT ============ " << std::endl
<< res["directory"] << " scanned" << std::endl
<< "Processed files: " << res["files_count"] << std::endl
<< "JS detects: " << res["js_detects"] << std::endl
<< "Unix detects: " << res["unix_detects"] << std::endl
<< "macOS detects: " << res["macos_detects"] << std::endl
<< "Errors: " << res["file_errors"] << std::endl
<< "Execution time: " << res["microsec_time"]
<< " microseconds" << std::endl
<< "==================================== " << std::endl
<< std::endl;
}
}
| [
"nickgeo.winner@gmail.com"
] | nickgeo.winner@gmail.com |
35c8fd4778a0ff4f1365a837e17844b60e7af4b3 | ec0b0a09a456f23f45ece61cd0f3481c07178d06 | /Server/Src/ServerEngine/CommonFunc.cpp | 5a0d2033907c2d6bedb1ec8476cf1339534bb640 | [] | no_license | leafcutter-ant/GameProject3 | 80f09e6c10c8fba26d266f82089f38c32a4e10ac | d1b7795184aecc8d948bd9ed12b1d2585f165082 | refs/heads/master | 2022-10-13T12:55:08.068247 | 2020-06-09T10:10:36 | 2020-06-09T10:10:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,049 | cpp | #include "stdafx.h"
#include "CommonFunc.h"
UINT32 CommonFunc::GetProcessorNum()
{
UINT32 dwNum = 0;
#ifdef WIN32
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
dwNum = sysInfo.dwNumberOfProcessors;
#else
dwNum = sysconf(_SC_NPROCESSORS_CONF);
#endif
return dwNum;
}
std::string CommonFunc::GetCurrentWorkDir()
{
char szPath[1024];
#ifdef WIN32
_getcwd(szPath, 1024);
#else
getcwd(szPath, 1024);
#endif
return std::string(szPath);
}
std::string CommonFunc::GetCurrentExeDir()
{
char szPath[1024] = {0};
#ifdef WIN32
GetModuleFileName(NULL, szPath, 1024);
char* p = strrchr(szPath, '\\');
#else
readlink("/proc/self/exe", szPath, sizeof(szPath));
char* p = strrchr(szPath, '/');
#endif
*p = 0;
return std::string(szPath);
}
BOOL CommonFunc::SetCurrentWorkDir(std::string strPath)
{
if (strPath.empty())
{
strPath = GetCurrentExeDir();
}
#ifdef WIN32
SetCurrentDirectory(strPath.c_str());
#else
chdir(strPath.c_str());
#endif
return TRUE;
}
UINT64 CommonFunc::GetCurrTime()
{
time_t t;
t = time(0);
return (UINT64)t;
}
tm CommonFunc::GetCurrTmTime()
{
time_t rawtime;
struct tm* timeinfo;
time (&rawtime);
timeinfo = localtime(&rawtime);
return *timeinfo;
}
UINT64 CommonFunc::GetDayBeginTime()
{
time_t t;
t = time(0);
tm* t_tm = localtime(&t);
t_tm->tm_hour = 0;
t_tm->tm_min = 0;
t_tm->tm_sec = 0;
t = mktime(t_tm);
return (UINT64)t;
}
UINT64 CommonFunc::GetWeekBeginTime()
{
time_t t;
t = time(0);
tm* t_tm = localtime(&t);
t_tm->tm_hour = 0;
t_tm->tm_min = 0;
t_tm->tm_sec = 0;
t_tm->tm_wday = 0;
t = mktime(t_tm);
return (UINT64)t;
}
time_t CommonFunc::YearTimeToSec(INT32 nYear, INT32 nMonth, INT32 nDay, INT32 nHour, INT32 nMin, INT32 nSec)
{
time_t timer;
time(&timer);
tm* t_tm = localtime(&timer);
tm newtm;
newtm.tm_year = (nYear < 0) ? t_tm->tm_year : nYear;
newtm.tm_mon = (nMonth < 0) ? t_tm->tm_mon : nMonth;
newtm.tm_mday = (nDay < 0) ? t_tm->tm_mday : nDay;
newtm.tm_hour = (nHour < 0) ? t_tm->tm_hour : nHour;
newtm.tm_min = (nMin < 0) ? t_tm->tm_min : nMin;
newtm.tm_sec = (nSec < 0) ? t_tm->tm_sec : nSec;
return mktime(&newtm);;
}
std::string CommonFunc::TimeToString(time_t tTime)
{
tm* t_tm = localtime(&tTime);
if (t_tm == NULL)
{
return "";
}
char szTime[128] = { 0 };
strftime(szTime, 128, "%Y-%m-%d %H:%M:%S", t_tm);
return std::string(szTime);
}
UINT64 CommonFunc::GetTickCount()
{
#ifdef WIN32
return ::GetTickCount64();
#else
UINT64 uTickCount = 0;;
struct timespec on;
if(0 == clock_gettime(CLOCK_MONOTONIC, &on) )
{
uTickCount = on.tv_sec * 1000 + on.tv_nsec / 1000000;
}
return uTickCount;
#endif
}
BOOL CommonFunc::CreateDir( std::string& strDir )
{
int nRet = 0;
#ifdef WIN32
nRet = _mkdir(strDir.c_str());
#else
nRet = mkdir(strDir.c_str(), S_IRWXU);
#endif
if(nRet == 0)
{
return TRUE;
}
if(errno == EEXIST)
{
return TRUE;
}
return FALSE;
}
BOOL CommonFunc::GetDirFiles(const char* pszDir, char* pszFileType, std::vector<std::string>& vtFileList, BOOL bRecursion)
{
if (pszDir == NULL || pszFileType == NULL)
{
return FALSE;
}
char szTem[1024] = { 0 };
char szDir[1024] = { 0 };
strcpy(szTem, pszDir);
if (szTem[strlen(szTem) - 1] != '\\' || szTem[strlen(szTem) - 1] != '/')
{
strcat(szTem, "/");
}
strcpy(szDir, szTem);
strcat(szDir, pszFileType);
#ifdef WIN32
struct _finddata_t tFileInfo = { 0 };
long long hFile = _findfirst(szDir, &tFileInfo);
if (hFile == -1)
{
return FALSE;
}
do
{
if (strcmp(tFileInfo.name, ".") == 0 || strcmp(tFileInfo.name, "..") == 0)
{
continue;
}
if ((tFileInfo.attrib & _A_SUBDIR) && bRecursion)
{
char szSub[1024] = { 0 };
strcpy(szSub, pszDir);
if (szSub[strlen(szSub) - 1] != '\\' || szSub[strlen(szSub) - 1] != '/')
{
strcat(szSub, "/");
}
strcat(szSub, tFileInfo.name);
GetDirFiles(szSub, pszFileType, vtFileList, bRecursion);
}
else
{
vtFileList.push_back(std::string(szTem) + std::string(tFileInfo.name));
}
}
while (_findnext(hFile, &tFileInfo) == 0);
_findclose(hFile);
#else
DIR* pDirInfo;
struct dirent* tFileInfo;
struct stat statbuf;
if((pDirInfo = opendir(pszDir)) == NULL)
{
return FALSE;
}
while((tFileInfo = readdir(pDirInfo)) != NULL)
{
if (strcmp(".", tFileInfo->d_name) == 0 || strcmp("..", tFileInfo->d_name) == 0)
{
continue;
}
lstat(tFileInfo->d_name, &statbuf);
if((S_IFDIR & statbuf.st_mode) && bRecursion)
{
GetDirFiles(tFileInfo->d_name, pszFileType, vtFileList, bRecursion);
}
else
{
vtFileList.push_back(std::string(szTem) + std::string(tFileInfo->d_name));
}
}
closedir(pDirInfo);
#endif
return TRUE;
}
BOOL CommonFunc::IsSameDay(UINT64 uTime)
{
#ifdef WIN32
return ((uTime - _timezone) / 86400) == ((GetCurrTime() - _timezone) / 86400);
#else
return ((uTime - timezone) / 86400) == ((GetCurrTime() - timezone) / 86400);
#endif
}
UINT32 CommonFunc::GetCurThreadID()
{
UINT32 dwThreadID = 0;
#ifdef WIN32
dwThreadID = ::GetCurrentThreadId();
#else
dwThreadID = (UINT32)pthread_self();
#endif
return dwThreadID;
}
UINT32 CommonFunc::GetCurProcessID()
{
UINT32 dwProcessID = 0;
#ifdef WIN32
dwProcessID = ::GetCurrentProcessId();
#else
dwProcessID = (UINT32)getpid();
#endif
return dwProcessID;
}
VOID CommonFunc::Sleep(UINT32 dwMilliseconds)
{
#ifdef WIN32
::Sleep(dwMilliseconds);
#else
struct timespec req;
req.tv_sec = 0;
req.tv_nsec = dwMilliseconds * 1000000;
nanosleep(&req, NULL);
#endif
return;
}
UINT32 CommonFunc::GetFreePhysMemory()
{
UINT32 dwFreeSize = 0;
#ifdef WIN32
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
dwFreeSize = (UINT32)(statex.ullAvailPhys / 1024 / 1024);
#else
UINT32 dwPageSize;
UINT32 dwFreePages;
dwPageSize = sysconf (_SC_PAGESIZE) / 1024;
dwFreePages = sysconf (_SC_AVPHYS_PAGES) / 1024;
dwFreeSize = dwFreePages * dwPageSize;
#endif
return dwFreeSize;
}
INT32 CommonFunc::GetRandNum(INT32 nType)
{
if(nType >= 100 || nType < 0)
{
return 0;
}
static INT32 nRandIndex[100] = {0};
static INT32 vtGlobalRankValue[10000];
static BOOL bInit = FALSE;
if(bInit == FALSE)
{
bInit = TRUE;
INT32 nTempIndex;
UINT32 nTemp;
for(int j = 0; j < 10000; j++ )
{
vtGlobalRankValue[j] = j + 1;
}
for(int i = 0; i < 10000; i++ )
{
nTempIndex = rand() % (i + 1);
if (nTempIndex != i)
{
nTemp = vtGlobalRankValue[i];
vtGlobalRankValue[i] = vtGlobalRankValue[nTempIndex];
vtGlobalRankValue[nTempIndex] = nTemp;
}
}
}
return vtGlobalRankValue[(nRandIndex[nType]++) % 10000];
}
UINT32 CommonFunc::GetLastError()
{
#ifdef WIN32
return ::GetLastError();
#else
return errno;
#endif
}
//s:10m:6:p:16
HANDLE CommonFunc::CreateShareMemory(UINT32 dwModuleID, INT32 nPage, INT32 nSize)
{
HANDLE hShare = NULL;
#ifdef WIN32
CHAR szMemName[128] = {0};
snprintf(szMemName, 128, "SM_%d", dwModuleID << 16 | nPage);
hShare = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, nSize, szMemName);
if (hShare != NULL)
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hShare);
hShare = NULL;
}
}
#else
hShare = shmget(dwModuleID << 16 | nPage, nSize, 0666 | IPC_CREAT | IPC_EXCL);
if (hShare == -1)
{
hShare = NULL;
}
#endif
return hShare;
}
// HANDLE CommonFunc::CreateShareMemory(std::string strName, INT32 nSize)
// {
// HANDLE hShare = NULL;
// #ifdef WIN32
// hShare = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, nSize, strName.c_str());
// if(hShare != NULL)
// {
// if(GetLastError() == ERROR_ALREADY_EXISTS)
// {
// CloseHandle(hShare);
// hShare = NULL;
// }
// }
// #else
// key_t key = ftok(strName.c_str(), 201);
// hShare = shmget(key, nSize, 0666 | IPC_CREAT | IPC_EXCL);
// if(hShare == -1)
// {
// hShare = NULL;
// }
// #endif
// return hShare;
// }
//s:10m:6:p:16
HANDLE CommonFunc::OpenShareMemory(UINT32 dwModuleID, INT32 nPage)
{
HANDLE hShare = NULL;
#ifdef WIN32
CHAR szMemName[128] = {0};
snprintf(szMemName, 128, "SM_%d", dwModuleID << 16 | nPage);
hShare = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, szMemName);
#else
hShare = shmget(dwModuleID << 16 | nPage, 0, 0);
if (hShare == -1)
{
return NULL;
}
#endif
return hShare;
}
// HANDLE CommonFunc::OpenShareMemory(std::string strName)
// {
// #ifdef WIN32
// HANDLE hShare = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, strName.c_str());
// #else
// key_t key = ftok(strName.c_str(), 201);
// HANDLE hShare = shmget(key, 0, 0);
// if (hShare == -1)
// {
// return NULL;
// }
// #endif
// return hShare;
// }
CHAR* CommonFunc::GetShareMemory(HANDLE hShm)
{
#ifdef WIN32
CHAR* pdata = (CHAR*)MapViewOfFile(hShm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
#else
CHAR* pdata = (CHAR*)shmat(hShm, (void*)0, 0);
#endif
return pdata;
}
BOOL CommonFunc::ReleaseShareMemory(CHAR* pMem)
{
#ifdef WIN32
return UnmapViewOfFile(pMem);
#else
return (0 == shmdt(pMem));
#endif
}
BOOL CommonFunc::CloseShareMemory(HANDLE hShm)
{
#ifdef WIN32
return CloseHandle(hShm);
#else
return (0 == shmctl(hShm, IPC_RMID, 0));
#endif
}
BOOL CommonFunc::DbgTrace(char* format, ...)
{
#if (defined WIN32) && (defined _DEBUG)
char szLog[1024] = { 0 };
va_list argptr;
va_start(argptr, format);
vsnprintf(szLog, 1023, format, argptr);
va_end(argptr);
OutputDebugString(szLog);
#endif
return TRUE;
}
BOOL CommonFunc::KillProcess(UINT64 dwPid)
{
#ifdef WIN32
HANDLE hPrc;
if (0 == dwPid)
{
return FALSE;
}
hPrc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)dwPid);
if (hPrc == NULL)
{
return TRUE;
}
if (!TerminateProcess(hPrc, 0))
{
CloseHandle(hPrc);
return FALSE;
}
else
{
WaitForSingleObject(hPrc, 200);
}
CloseHandle(hPrc);
#else
kill(dwPid, SIGKILL);
#endif
return TRUE;
}
INT32 CommonFunc::Min(INT32 nValue1, INT32 nValue2)
{
return (nValue1 < nValue2) ? nValue1 : nValue2;
}
BOOL CommonFunc::IsAlreadyRun(std::string strSignName)
{
#ifdef WIN32
HANDLE hMutex = NULL;
hMutex = CreateMutex(NULL, FALSE, strSignName.c_str());
if (hMutex != NULL)
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex);
return TRUE;
}
}
return FALSE;
#else
INT32 fd;
CHAR szbuf[32] = {0};
std::string strLockFile = "/var/run/" + strSignName + ".pid";
fd = open(strLockFile.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd < 0)
{
return TRUE;
}
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_start = 0;
fl.l_whence = SEEK_SET;
fl.l_len = 0;
if (fcntl(fd, F_SETLK, &fl) < 0)
{
close(fd);
return TRUE;
}
ftruncate(fd, 0);
snprintf(szbuf, 32, "%ld", (long)getpid());
write(fd, szbuf, strlen(szbuf) + 1);
return FALSE;
#endif
}
BOOL CommonFunc::PrintColorText(CHAR* pSzText, INT32 nColor)
{
//nColor 0:默认 1:红; 2:黄; 3; 绿
#ifdef WIN32
switch (nColor)
{
case 1:
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED);
printf(pSzText);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
break;
case 2:
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
printf(pSzText);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
break;
case 3:
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN);
printf(pSzText);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
break;
default:
{
printf(pSzText);
}
break;
}
#else
switch (nColor)
{
case 1:
{
printf("\033[1;31;40m%s\033[0m", pSzText);
}
break;
case 2:
{
printf("\033[1;33;40m%s\033[0m", pSzText);
}
break;
case 3:
{
printf("\033[1;32;40m%s\033[0m", pSzText);
}
break;
default:
{
printf(pSzText);
}
break;
}
#endif
return TRUE;
}
| [
"ylmbtm@163.com"
] | ylmbtm@163.com |
b7e4a915716550141f237028e5223023916b45d4 | 3e1ac5a6f5473c93fb9d4174ced2e721a7c1ff4c | /build/iOS/Preview/include/Fuse.Controls.CommonNavigationPages.AddedPage.h | 526b066f59fc25b9946c2983b91f191070fb3b7f | [] | no_license | dream-plus/DreamPlus_popup | 49d42d313e9cf1c9bd5ffa01a42d4b7c2cf0c929 | 76bb86b1f2e36a513effbc4bc055efae78331746 | refs/heads/master | 2020-04-28T20:47:24.361319 | 2019-05-13T12:04:14 | 2019-05-13T12:04:14 | 175,556,703 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Controls.Navigation/1.9.0/CommonNavigationPages.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Controls{struct CommonNavigationPages__AddedPage;}}}
namespace g{namespace Fuse{namespace Navigation{struct RouterPage;}}}
namespace g{namespace Fuse{struct Visual;}}
namespace g{
namespace Fuse{
namespace Controls{
// private sealed class CommonNavigationPages.AddedPage :88
// {
uType* CommonNavigationPages__AddedPage_typeof();
void CommonNavigationPages__AddedPage__ctor__fn(CommonNavigationPages__AddedPage* __this);
void CommonNavigationPages__AddedPage__New1_fn(CommonNavigationPages__AddedPage** __retval);
struct CommonNavigationPages__AddedPage : uObject
{
uStrong<uString*> Template;
uStrong< ::g::Fuse::Visual*> Visual;
uStrong<uObject*> Data;
uStrong< ::g::Fuse::Navigation::RouterPage*> Page;
void ctor_();
static CommonNavigationPages__AddedPage* New1();
};
// }
}}} // ::g::Fuse::Controls
| [
"cowodbs156@gmail.com"
] | cowodbs156@gmail.com |
fe937efc4dae69faff96ce8311383175b870ebfa | 5cf04a4324110ace538302aaa8484a05f09f0d9c | /Sourcecode/mx/core/elements/DisplayOctave.h | d826c64d9f9689219b484ab417e7c0bf837aaa20 | [
"MIT"
] | permissive | jsj2008/MusicXML-Class-Library | ebce53a1d1fea280141c84b62b232c3395ad0eb6 | 079c4b87835cc9942c052571d7ee3ebfdb91fa31 | refs/heads/master | 2020-05-31T16:05:09.402234 | 2017-03-10T23:02:09 | 2017-03-10T23:02:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,508 | h | // MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#pragma once
#include "mx/core/ForwardDeclare.h"
#include "mx/core/ElementInterface.h"
#include "mx/core/Integers.h"
#include <iosfwd>
#include <memory>
#include <vector>
namespace mx
{
namespace core
{
MX_FORWARD_DECLARE_ELEMENT( DisplayOctave )
inline DisplayOctavePtr makeDisplayOctave() { return std::make_shared<DisplayOctave>(); }
inline DisplayOctavePtr makeDisplayOctave( const OctaveValue& value ) { return std::make_shared<DisplayOctave>( value ); }
inline DisplayOctavePtr makeDisplayOctave( OctaveValue&& value ) { return std::make_shared<DisplayOctave>( std::move( value ) ); }
class DisplayOctave : public ElementInterface
{
public:
DisplayOctave();
DisplayOctave( const OctaveValue& value );
virtual bool hasAttributes() const;
virtual bool hasContents() const;
virtual std::ostream& streamAttributes( std::ostream& os ) const;
virtual std::ostream& streamName( std::ostream& os ) const;
virtual std::ostream& streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const;
OctaveValue getValue() const;
void setValue( const OctaveValue& value );
bool fromXElement( std::ostream& message, xml::XElement& xelement );
private:
OctaveValue myValue;
};
}
}
| [
"matthew.james.briggs@gmail.com"
] | matthew.james.briggs@gmail.com |
fde1200c9584cdc440adbf189685b8a2f0ec40d5 | e24a366a7ac5dfb5975a468046c8626a9d56fa6d | /llvm/Source/llvm/include/llvm/TextAPI/MachO/ArchitectureSet.h | d8dfc7f1af214aa98787a91118915d2d7128be07 | [
"MIT",
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | fengjixuchui/iOS-Reverse | 01e17539bdbff7f2a783821010d3f36b5afba910 | 682a5204407131c29588dd22236babd1f8b2889d | refs/heads/master | 2021-06-26T17:25:41.993771 | 2021-02-11T10:33:32 | 2021-02-11T10:33:32 | 210,527,924 | 0 | 0 | MIT | 2021-02-11T10:33:33 | 2019-09-24T06:26:57 | null | UTF-8 | C++ | false | false | 4,258 | h | //===- llvm/TextAPI/MachO/ArchitectureSet.h - ArchitectureSet ---*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Defines the architecture set.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TEXTAPI_MACHO_ARCHITECTURE_SET_H
#define LLVM_TEXTAPI_MACHO_ARCHITECTURE_SET_H
#include "llvm/Support/raw_ostream.h"
#include "llvm/TextAPI/MachO/Architecture.h"
#include <cstddef>
#include <iterator>
#include <limits>
#include <vector>
namespace llvm {
namespace MachO {
class ArchitectureSet {
private:
using ArchSetType = uint32_t;
const static ArchSetType EndIndexVal =
std::numeric_limits<ArchSetType>::max();
ArchSetType ArchSet{0};
public:
constexpr ArchitectureSet() = default;
constexpr ArchitectureSet(ArchSetType Raw) : ArchSet(Raw) {}
ArchitectureSet(Architecture Arch) : ArchitectureSet() { set(Arch); }
ArchitectureSet(const std::vector<Architecture> &Archs);
void set(Architecture Arch) {
if (Arch == AK_unknown)
return;
ArchSet |= 1U << static_cast<int>(Arch);
}
void clear(Architecture Arch) { ArchSet &= ~(1U << static_cast<int>(Arch)); }
bool has(Architecture Arch) const {
return ArchSet & (1U << static_cast<int>(Arch));
}
bool contains(ArchitectureSet Archs) const {
return (ArchSet & Archs.ArchSet) == Archs.ArchSet;
}
size_t count() const;
bool empty() const { return ArchSet == 0; }
ArchSetType rawValue() const { return ArchSet; }
template <typename Ty>
class arch_iterator
: public std::iterator<std::forward_iterator_tag, Architecture, size_t> {
private:
ArchSetType Index;
Ty *ArchSet;
void findNextSetBit() {
if (Index == EndIndexVal)
return;
while (++Index < sizeof(Ty) * 8) {
if (*ArchSet & (1UL << Index))
return;
}
Index = EndIndexVal;
}
public:
arch_iterator(Ty *ArchSet, ArchSetType Index = 0)
: Index(Index), ArchSet(ArchSet) {
if (Index != EndIndexVal && !(*ArchSet & (1UL << Index)))
findNextSetBit();
}
Architecture operator*() const { return static_cast<Architecture>(Index); }
arch_iterator &operator++() {
findNextSetBit();
return *this;
}
arch_iterator operator++(int) {
auto tmp = *this;
findNextSetBit();
return tmp;
}
bool operator==(const arch_iterator &o) const {
return std::tie(Index, ArchSet) == std::tie(o.Index, o.ArchSet);
}
bool operator!=(const arch_iterator &o) const { return !(*this == o); }
};
ArchitectureSet operator&(const ArchitectureSet &o) {
return {ArchSet & o.ArchSet};
}
ArchitectureSet operator|(const ArchitectureSet &o) {
return {ArchSet | o.ArchSet};
}
ArchitectureSet &operator|=(const ArchitectureSet &o) {
ArchSet |= o.ArchSet;
return *this;
}
ArchitectureSet &operator|=(const Architecture &Arch) {
set(Arch);
return *this;
}
bool operator==(const ArchitectureSet &o) const {
return ArchSet == o.ArchSet;
}
bool operator!=(const ArchitectureSet &o) const {
return ArchSet != o.ArchSet;
}
bool operator<(const ArchitectureSet &o) const { return ArchSet < o.ArchSet; }
using iterator = arch_iterator<ArchSetType>;
using const_iterator = arch_iterator<const ArchSetType>;
iterator begin() { return {&ArchSet}; }
iterator end() { return {&ArchSet, EndIndexVal}; }
const_iterator begin() const { return {&ArchSet}; }
const_iterator end() const { return {&ArchSet, EndIndexVal}; }
operator std::string() const;
operator std::vector<Architecture>() const;
void print(raw_ostream &OS) const;
};
inline ArchitectureSet operator|(const Architecture &lhs,
const Architecture &rhs) {
return ArchitectureSet(lhs) | ArchitectureSet(rhs);
}
raw_ostream &operator<<(raw_ostream &OS, ArchitectureSet Set);
} // end namespace MachO.
} // end namespace llvm.
#endif // LLVM_TEXTAPI_MACHO_ARCHITECTURE_SET_H
| [
"374619540@qq.com"
] | 374619540@qq.com |
6e7619a751bd722cb86ee74a85f99e94c3750b12 | 5a2349399fa9d57c6e8cc6e0f7226d683391a362 | /src/qt/qtbase/src/corelib/kernel/qsystemsemaphore_android.cpp | 6251cd822a7269ad82ff3fe41b7a191b8831353a | [
"LGPL-2.1-only",
"GPL-3.0-only",
"LicenseRef-scancode-digia-qt-commercial",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-digia-qt-preview",
"LGPL-2.0-or-later",
"GFDL-1.3-only",
"BSD-3-Clause"
] | permissive | aharthcock/phantomjs | e70f3c379dcada720ec8abde3f7c09a24808154c | 7d7f2c862347fbc7215c849e790290b2e07bab7c | refs/heads/master | 2023-03-18T04:58:32.428562 | 2023-03-14T05:52:52 | 2023-03-14T05:52:52 | 24,828,890 | 0 | 0 | BSD-3-Clause | 2023-03-14T05:52:53 | 2014-10-05T23:38:56 | C++ | UTF-8 | C++ | false | false | 2,982 | cpp | /****************************************************************************
**
** Copyright (C) 2012 Collabora Ltd, author <robin.burchell@collabora.co.uk>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/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 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsystemsemaphore.h"
#include "qsystemsemaphore_p.h"
#include <qdebug.h>
#ifndef QT_NO_SYSTEMSEMAPHORE
QT_BEGIN_NAMESPACE
QSystemSemaphorePrivate::QSystemSemaphorePrivate() :
semaphore(-1), createdFile(false),
createdSemaphore(false), unix_key(-1), error(QSystemSemaphore::NoError)
{
}
void QSystemSemaphorePrivate::setErrorString(const QString &function)
{
Q_UNUSED(function);
qWarning() << Q_FUNC_INFO << "Not yet implemented on Android";
}
key_t QSystemSemaphorePrivate::handle(QSystemSemaphore::AccessMode mode)
{
Q_UNUSED(mode);
qWarning() << Q_FUNC_INFO << "Not yet implemented on Android";
return -1;
}
void QSystemSemaphorePrivate::cleanHandle()
{
qWarning() << Q_FUNC_INFO << "Not yet implemented on Android";
}
bool QSystemSemaphorePrivate::modifySemaphore(int count)
{
Q_UNUSED(count);
qWarning() << Q_FUNC_INFO << "Not yet implemented on Android";
return false;
}
QT_END_NAMESPACE
#endif // QT_NO_SYSTEMSEMAPHORE
| [
"ariya.hidayat@gmail.com"
] | ariya.hidayat@gmail.com |
62317487b194b718fbde5b357f6f7bd773792926 | e8089ee27a0c9a9b91ef4aa0470c7b16fe8692ad | /catane/Player.cpp | 76013a82270d2af31ad693ed3000fe4207296031 | [] | no_license | harrahx3/catane_sfml | f764f5362082c528f171b764e1f4860bd637386a | 0133e4d5392a4de3ab1d781522146ce955fcf68e | refs/heads/main | 2023-03-12T22:28:40.775645 | 2021-02-26T16:02:25 | 2021-02-26T16:02:25 | 342,626,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,459 | cpp | #include "inc.h"
using namespace std;
using namespace sf;
Player::Player(Players player,string name, int points, string texturePath, string fontPath) : m_player(player), m_name(name), m_points(points)
{
m_ressources.push_back(WOOD);
m_ressources.push_back(WHEAT);
m_ressources.push_back(CLAY);
m_ressources.push_back(WOOL);
m_ressources.push_back(WOOD);
m_ressources.push_back(WHEAT);
m_ressources.push_back(CLAY);
m_ressources.push_back(WOOL);
m_ressources.push_back(STONE);
if (!m_texture.loadFromFile(texturePath))
cout<<"erreur chargement sprite Player"<<endl;
m_sprite = Sprite(m_texture);
if (!m_font.loadFromFile(fontPath)) ///load the font
std::cout<<"erreur chargement fonte Player\n";
else
m_text.setFont(m_font);
m_text.setPosition(400,10);
m_text.setColor(sf::Color::Blue);
m_text.setCharacterSize(10);
m_text.setString("a");
m_text.setFont(m_font);
m_state = NOTPLAYING;
}
Players Player::getPlayer()
{
return m_player;
}
State Player::getState()
{
return m_state;
}
void Player::setState(State state)
{
m_state = state;
}
bool Player::buyElement(Elements* element, vector<Ressources> ressourcesAPayees)
{
cout <<"buyElement()\n";
if(!element->canBeBought())
{
cout <<"erreur achat : canBeBought\n";
return false;
}
if (!this->hasRessources(ressourcesAPayees))
{
cout <<"erreur achat : hasRessources\n";
return false;
}
for (int unsigned i=0; i<ressourcesAPayees.size(); i++)
this->loseResource(ressourcesAPayees[i]);
if (element->setPlayer(this))
{
cout<<"element achete"<<endl;
return true;
}
return false;
}
void Player::collectRessource(Ressources ressource)
{
//m_ressources.push_back(WOOL);
cout <<"collectRessource()\n";
m_ressources.push_back(ressource);
// this->printRessources();
}
bool Player::loseResource(Ressources ressource, int quantity )
{
cout <<"loseRessource()\n";
return eraseListElements<Ressources>(m_ressources, ressource);
}
bool Player::hasRessources(std::vector<Ressources> ressources)
{
cout <<"hasRessources()\n";
list<Ressources> m_ressources_copie = m_ressources;
for (int unsigned i=0; i<ressources.size(); i++)
if (!eraseListElements(m_ressources_copie, ressources[i]))
return false;
cout <<"hasRessources() true\n";
return true;
}
void Player::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= getTransform();
int i = 500;
int j = 10;
int inc = 15;
//m_ressources.sort();
/*cout<<m_name<<" : r= ";
for(list<Ressources>::iterator it = m_ressources.begin(); it!=m_ressources.end(); ++it)
cout<<*it<<" ; ";
cout<<endl;*/
std::list<Ressources> ressources = m_ressources;
for(std::list<Ressources>::iterator it = ressources.begin(); it!=ressources.end(); ++it)
{
i += inc;
target.draw(Ressource_graph(*it, i, j), states);
}
sf::Text text;
text.setFont(m_font);
text.setString(m_name);
text.setPosition(400,10);
text.setCharacterSize(10);
target.draw(text, states);
}
std::string Player::getName() const
{
return m_name;
}
/**
Player::Player(Players player,string name, int points) : m_player(player), m_name(name), m_points(points)
{
m_ressources.push_back(WOOD);
m_ressources.push_back(WOOD);
m_ressources.push_back(CLAY);
m_ressources.push_back(CLAY);
}
Players Player::getPlayer()
{
return m_player;
}
bool Player::buyElement(Elements* element, vector<Ressources> ressourcesAPayees)
{
cout <<"buyElement()\n";
if(!element->canBeBought())
{
cout <<"erreur achat : canBeBought\n";
return false;
}
if (!this->hasRessources(ressourcesAPayees))
{
cout <<"erreur achat : hasRessources\n";
return false;
}
for (int i=0; i<ressourcesAPayees.size(); i++)
this->loseResource(ressourcesAPayees[i]);
if (element->setPlayer(this))
{
cout<<"element achete"<<endl;
return true;
}
return false;
}
void Player::collectRessource(Ressources ressource)
{
//m_ressources.push_back(WOOL);
cout <<"collectRessource()\n";
m_ressources.push_back(ressource);
this->printRessources();
}
bool Player::loseResource(Ressources ressource, int quantity )
{
cout <<"loseRessource()\n";
return eraseListElements<Ressources>(m_ressources, ressource);
}
bool Player::hasRessources(std::vector<Ressources> ressources)
{
cout <<"hasRessources()\n";
list<Ressources> m_ressources_copie = m_ressources;
for (int i=0; i<ressources.size(); i++)
if (!eraseListElements(m_ressources_copie, ressources[i]))
return false;
cout <<"hasRessources() true\n";
return true;
}
void Player::printRessources()
{
cout<<m_name<<" : r= ";
for(list<Ressources>::iterator it = m_ressources.begin(); it!=m_ressources.end(); ++it)
cout<<*it<<" ; ";
cout<<endl;
}
Tile::Tile(Tiles tile, int num) : m_tile(tile), m_num(num)
{
}
Tiles Tile::getTile()
{
return m_tile;
}
int Tile::getNum()
{
return m_num;
}
Board::Board()
{
std::vector<Ressources> roadPrice;
roadPrice.push_back(WOOD);
roadPrice.push_back(CLAY);
std::vector<Ressources> intersectionPrice;
intersectionPrice.push_back(WOOD);
intersectionPrice.push_back(CLAY);
intersectionPrice.push_back(WHEAT);
intersectionPrice.push_back(WOOL);
int test = 1;
//int width = 5;
//int height = 5;
Tiles tiles [m_bWidth][m_bHeight] = {{SEA,FIELD,FOREST,FIELD,SEA},{FOREST,FIELD,FOREST,FIELD,HILL},{FOREST,HILL,FOREST,HILL,HILL},{FOREST,FIELD,FOREST,FIELD,HILL},{SEA,SEA,FOREST,SEA,SEA}};
for (int i=0; i<m_bWidth; i++)
{
vector<Tile> v;
for (int j=0; j<m_bHeight; j++)
{
v.push_back(Tile(tiles[i][j]));
}
m_tiles.push_back(v);
}
**/
/*m_tiles.push_back(vector<Tile>(5,Tile(FOREST, 3)));
m_tiles.push_back(vector<Tile>(5,Tile(HILL, 4)));
m_tiles.push_back(vector<Tile>(5,Tile(SEA, 5)));
m_tiles.push_back(vector<Tile>(5,Tile(FIELD, 6)));
m_tiles.push_back(vector<Tile>(5,Tile(MOUNTAIN, 7)));*/
/*
Player redPlayer = Player(RED, "redP");
Player bluePlayer = Player(BLUE, "blueP");
Player yellowPlayer = Player(YELLOW, "yellowP");
Player whitePlayer = Player(WHITE, "whiteP");
vector<Player> players({redPlayer, bluePlayer, yellowPlayer, whitePlayer});
m_players = players;
*/
// m_players = vector<Player> {Player(RED,"redP"), Player(BLUE,"blueP"), Player(YELLOW,"yellowP"), Player(WHITE,"whiteP
/** Player players[] = {Player(RED,"redP"), Player(BLUE,"blueP"), Player(YELLOW,"yellowP"), Player(WHITE,"whiteP")};
for (int i=0; i<4; i++)
m_players.push_back(players[i]);
**/
/* m_players.push_back(Player(RED,"redP"));
m_players.push_back(Player(BLUE, "blueP"));
m_players.push_back(Player(YELLOW, "yellowP"));
m_players.push_back(Player(WHITE,"whiteP"));*/
/** m_currentPlayer = m_players.begin();
for (int i=0; i<m_width; i++)
for (int j=0; j<m_height; j++)
m_elements[i][j] = new SubTile(0);
for (int i=0; i<m_bWidth; i++)
{
for (int j=0; j<m_bHeight; j++)
{
for (int a=1; a<4; a++)
for (int b=2; b<5; b++)
{
if ((4*i+2*(j%2)+a) < m_width)
{
cout<<"a"<<endl;
delete m_elements[4*i+2*(j%2)+a +test][4*j+b +test];
m_elements[4*i+2*(j%2)+a +test][4*j+b +test] = new SubTile(&m_tiles[i][j]);
cout<<"a"<<endl;
}
}
delete m_elements[4*i+2*(j%2)+2 +test][4*j+1 +test];
m_elements[4*i+2*(j%2)+2 +test][4*j+1 +test] = new SubTile(&m_tiles[i][j]);
delete m_elements[4*i+2*(j%2)+2 +test][4*j+5 +test];
m_elements[4*i+2*(j%2)+2 +test][4*j+5 +test] = new SubTile(&m_tiles[i][j]);
if (m_tiles[i][j].getTile() != SEA)
{
for (int a=0; a<7; a+=2)
{
if (a == 0 || a == 6)
{
delete m_elements[4*i+2+2*(j%2) +test][4*j+a +test];
m_elements[4*i+2+2*(j%2) +test][4*j+a +test] = new Intersection(0, intersectionPrice);
}
else
for (int b=0; b<5; b+=4)
{
delete m_elements[4*i+b+2*(j%2) +test][4*j+a +test];
m_elements[4*i+b+2*(j%2) +test][4*j+a+ test] = new Intersection(0, intersectionPrice);
}
}
for (int b=1; b<6; b+=2)
{
if (b == 3)
for (int a=0; a<5; a+=4)
{
delete m_elements[4*i+a+2*(j%2) +test][4*j+b +test];
m_elements[4*i+a+2*(j%2) +test][4*j+b +test] = new Road (0, roadPrice);
}
else
for (int a=1; a<4; a+=2)
{
delete m_elements[4*i+a+2*(j%2) +test][4*j+b +test];
m_elements[4*i+a+2*(j%2) +test][4*j+b +test] = new Road(0, roadPrice);
}
}
}
}
}
}
Board::~Board()
{
for (int i=0; i<m_width; i++)
for (int j=0; j<m_height; j++)
{
delete m_elements[i][j];
m_elements[i][j] = 0;
}
}
void Board::draw(sf::RenderWindow& app, int tileSize)
{
for (int i=0; i<m_width; i++)
for (int j=0; j<m_height; j++)
{
sf::Sprite sprite = m_elements[i][j]->draw();
sprite.setPosition(Vector2f(i*tileSize, j*tileSize));
app.draw(sprite);
}
}
Elements* Board::getElement(int i, int j)
{
return m_elements[i][j];
}
void Board::product()
{
cout <<"Board::product()\n";
int randNum = this->throwDice();
cout<<"randnum= "<<randNum<<endl;
for (int i=1; i<m_width-1; i++)
for (int j=1; j<m_height-1; j++)
{
m_elements[i][j]->collectProduct(this, i, j, randNum);
}
}
int Board::throwDice()
{
return rand()%6 + rand()%6 + 2;
}
void Board::building(int x, int y)
{
if (x>0 && x<m_width && y>0 && y<m_height)
{
m_currentPlayer->buyElement(this->getElement(x,y), this->getElement(x,y)->getPrice());
m_currentPlayer->printRessources();
}
}
void Board::nextPlayer()
{
m_currentPlayer++;
if (m_currentPlayer == m_players.end())
m_currentPlayer = m_players.begin();
cout<<endl<<"new player = ";
m_currentPlayer->printRessources();
}**/
/*
void Board::play(sf::RenderWindow& app)
{
int tileSize = 15;
vector<Ressources> roadPrice;
roadPrice.push_back(WOOD);
roadPrice.push_back(CLAY);
//production
this->product();
//commerce
//construction
m_currentPlayer->printRessources();
while (!sf::Mouse::isButtonPressed(Mouse::Right))
{
app.clear();
this->draw(app, tileSize);
app.display();
if (sf::Mouse::isButtonPressed(Mouse::Left))
{
int x = ((sf::Mouse::getPosition(app).x - (sf::Mouse::getPosition(app).x % tileSize)) / tileSize);
int y = ((sf::Mouse::getPosition(app).y - (sf::Mouse::getPosition(app).y % tileSize)) / tileSize);
if (x>0 && x<m_width && y>0 && y<m_height)
{
m_currentPlayer->buyElement(this->getElement(x,y), this->getElement(x,y)->getPrice());
m_currentPlayer->printRessources();
}
while(sf::Mouse::isButtonPressed(Mouse::Left))
{
}
}
}
//next player
m_currentPlayer++;
if (m_currentPlayer == m_players.end())
m_currentPlayer = m_players.begin();
}
*/
| [
"hyacinthe.menard@gmail.com"
] | hyacinthe.menard@gmail.com |
a47b1a678dda664633290369d15205d4e1dc23d3 | aa4899ac6c2b1eb0eb22d15953e18f7d1cdd4ee4 | /code/foundation/system/win32/win32registry.cc | 9635de9e885b9abf7f9e1de07b88d0624a58c98f | [] | no_license | dzw/stellar2008 | bc2647f2a9eea03dea233335af66e9a916d2b1e3 | 5ff28d25b8cafdfccc79fa7e916b5cdc4f36b4ac | refs/heads/master | 2021-01-10T12:26:08.853827 | 2012-01-04T17:15:42 | 2012-01-04T17:15:42 | 36,920,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,747 | cc | //------------------------------------------------------------------------------
// win32registry.cc
// (C) 2007 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "system/win32/win32registry.h"
namespace System
{
//------------------------------------------------------------------------------
/**
Convert a RootKey value into a Win32 key handle.
*/
HKEY
Win32Registry::RootKeyToWin32KeyHandle(RootKey rootKey)
{
switch (rootKey)
{
case ClassesRoot: return HKEY_CLASSES_ROOT;
case CurrentUser: return HKEY_CURRENT_USER;
case LocalMachine: return HKEY_LOCAL_MACHINE;
case Users: return HKEY_USERS;
}
// can't happen
n_error("Can't happen!");
return 0;
}
//------------------------------------------------------------------------------
/**
Return true if a specific entry exists in the registry. To check only
for the existence of a key without the contained value, pass an
empty 'name' string.
*/
bool
Win32Registry::Exists(RootKey rootKey, const Util::String& key, const Util::String& name)
{
n_assert(key.IsValid());
HKEY win32RootKey = RootKeyToWin32KeyHandle(rootKey);
HKEY hKey = 0;
LONG res = RegOpenKeyEx(win32RootKey, // hKey
key.AsCharPtr(), // lpSubKey
0, // ulOptions (reserved)
KEY_READ, // samDesired
&hKey);
if (ERROR_SUCCESS != res)
{
// key does not exist
return false;
}
if (name.IsValid())
{
res = RegQueryValueEx(hKey, // hKey
name.AsCharPtr(), // lpValueName
NULL, // lpReserved
NULL, // lpType
NULL, // lpData
NULL); // lpcbData
RegCloseKey(hKey);
return (ERROR_SUCCESS == res);
}
else
{
// key exists, value name was empty
RegCloseKey(hKey);
return true;
}
}
//------------------------------------------------------------------------------
/**
Set a key value in the registry. This will create the key if it doesn't
exist.
*/
bool
Win32Registry::Write(RootKey rootKey, const Util::String& key, const Util::String& name, const Util::String& value)
{
n_assert(key.IsValid());
n_assert(name.IsValid());
HKEY win32RootKey = RootKeyToWin32KeyHandle(rootKey);
HKEY hKey = 0;
LONG res = RegCreateKeyEx(win32RootKey, // hKey
key.AsCharPtr(), // lpSubKey
0, // Reserved
NULL, // lpClass
REG_OPTION_NON_VOLATILE, // dwOptions
KEY_ALL_ACCESS, // samDesired
NULL, // lpSecurityAttribute
&hKey, // phkResult
NULL); // lpdwDisposition
if (ERROR_SUCCESS == res)
{
res = RegSetValueEx(hKey, // hKey
name.AsCharPtr(), // lpValueName
0, // Reserved
REG_SZ, // dwType (normal string)
(const BYTE*) value.AsCharPtr(), // lpData
value.Length() + 1); // cbData
RegCloseKey(hKey);
return (ERROR_SUCCESS == res);
}
else
{
return false;
}
}
//------------------------------------------------------------------------------
/**
Get a value from the registry. Fails hard if the key doesn't exists
(use the Exists() method to make sure that the key exists!).
*/
Util::String
Win32Registry::Read(RootKey rootKey, const Util::String& key, const Util::String& name)
{
n_assert(key.IsValid());
HKEY win32RootKey = RootKeyToWin32KeyHandle(rootKey);
HKEY hKey = 0;
LONG res = RegOpenKeyEx(win32RootKey, // hKey
key.AsCharPtr(), // lpSubKey
0, // ulOptions (reserved)
KEY_READ, // samDesired
&hKey);
n_assert(ERROR_SUCCESS == res);
// HACK: don't accept data > 1 KByte
char buf[1024];
DWORD bufSize = sizeof(buf);
res = RegQueryValueEx(hKey, // hKey
name.AsCharPtr(), // lpValueName
NULL, // lpReserved
NULL, // lpType
(BYTE*)buf, // lpData
&bufSize); // lpcbData
n_assert(ERROR_SUCCESS == res);
buf[bufSize - 1] = 0;
Util::String returnString = buf;
return returnString;
}
//------------------------------------------------------------------------------
/**
This deletes a complete registry key with all its values.
*/
bool
Win32Registry::Delete(RootKey rootKey, const Util::String& key)
{
n_assert(key.IsValid());
HKEY win32RootKey = RootKeyToWin32KeyHandle(rootKey);
LONG res = RegDeleteKey(win32RootKey, // hKey
key.AsCharPtr()); // lpSubKey
return (ERROR_SUCCESS == res);
}
} // namespace System
| [
"ctuoMail@gmail.com"
] | ctuoMail@gmail.com |
a58b03c475d03bb042cf8c2eee36626c7b9ad022 | 2a2db85e525d0a40965951f31a40b65b3e310c72 | /Homework2/Assignment2.cpp | f4331aff78df049d711e00eee36d851d32506e82 | [] | no_license | Werstef/Data-Security | 5b9bf2d10e9e18038230e42939db69f3fc8f6a03 | 01a81e100a94c0821217333c419c333046eb2a20 | refs/heads/main | 2023-02-08T14:01:12.044775 | 2020-12-23T13:10:04 | 2020-12-23T13:10:04 | 311,699,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,941 | cpp | #include <iostream>
#include <fstream>
using namespace std;
string encrypt(string text, int s)
{
string result = "";
if (s < 0) {
do {
s += 26;
} while (s < 0);
}
for (int i = 0; i < text.length(); i++)
{
if (isupper(text[i]))
result += char(int(text[i] + s - 65) % 26 + 65);
else
result += char(int(text[i] + s - 97) % 26 + 97);
}
return result;
}
string decrypt(string text, int s)
{
string result = "";
for (int i = 0; i < text.length(); i++)
{
if (isupper(text[i])) {
char temp = char(int(text[i] - s - 65) % 26 + 65);
if (temp < 'A') {
temp = temp + 'Z' - 'A' + 1;
}
result += temp;
}
else {
char temp = char(int(text[i] - s - 65) % 26 + 65);
if (temp < 'a') {
temp = temp + 'z' - 'a' + 1;
}
result += temp;
}
}
// Return the resulting string
return result;
}
int main()
{
char x;
int shift = 0;
int choice;
string word;
ifstream fin("text2.in");
ofstream fout("text2.out");
cout << "Tasteaza 1 pentru Decriptare sau 2 pentru Criptare\n";
cin >> choice;
if (choice == 2) {
cout << "Tasteaza parola de Criptare\n";
cin >> shift;
}
string result;
while (fin >> word) {
if (choice == 1) {
fout << "Decypther results for " << word << " : \n";
for (int i = 0; i < 26; i++) {
result = decrypt(word, i);
fout << "For passwrod " << i << " we have the decryption: \n";
fout << result << endl << endl;
}
}
else {
result = encrypt(word, shift);
fout << result << endl;
}
}
fin.close();
fout.close();
return 0;
} | [
"32906385+Werstef@users.noreply.github.com"
] | 32906385+Werstef@users.noreply.github.com |
a8ed160d26e468a4c4e8adf78282b2d9b2c45e3f | 5456502f97627278cbd6e16d002d50f1de3da7bb | /ui/gfx/geometry/size_f.h | 073148619480d4b70ac259f66188a13e6f30af66 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_GEOMETRY_SIZE_F_H_
#define UI_GFX_GEOMETRY_SIZE_F_H_
#include <iosfwd>
#include <string>
#include "base/compiler_specific.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/gfx_export.h"
namespace gfx {
// A floating version of gfx::Size.
class GFX_EXPORT SizeF {
public:
constexpr SizeF() : width_(0.f), height_(0.f) {}
constexpr SizeF(float width, float height)
: width_(width >= 0 ? width : 0), height_(height >= 0 ? height : 0) {}
constexpr explicit SizeF(const Size& size)
: SizeF(static_cast<float>(size.width()),
static_cast<float>(size.height())) {}
constexpr float width() const { return width_; }
constexpr float height() const { return height_; }
void set_width(float width) { width_ = fmaxf(0, width); }
void set_height(float height) { height_ = fmaxf(0, height); }
float GetArea() const;
void SetSize(float width, float height) {
set_width(width);
set_height(height);
}
void Enlarge(float grow_width, float grow_height);
void SetToMin(const SizeF& other);
void SetToMax(const SizeF& other);
bool IsEmpty() const { return !width() || !height(); }
void Scale(float scale) {
Scale(scale, scale);
}
void Scale(float x_scale, float y_scale) {
SetSize(width() * x_scale, height() * y_scale);
}
std::string ToString() const;
private:
float width_;
float height_;
};
inline bool operator==(const SizeF& lhs, const SizeF& rhs) {
return lhs.width() == rhs.width() && lhs.height() == rhs.height();
}
inline bool operator!=(const SizeF& lhs, const SizeF& rhs) {
return !(lhs == rhs);
}
GFX_EXPORT SizeF ScaleSize(const SizeF& p, float x_scale, float y_scale);
inline SizeF ScaleSize(const SizeF& p, float scale) {
return ScaleSize(p, scale, scale);
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const SizeF& size, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_SIZE_F_H_
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
2244a6e883c7285ccfe0016c3e638e7723cdf8d6 | 73f5012c3ab6b9e2e8282b9e853feceadab3ede9 | /Pool/mainwindow.cpp | 33559cfcdfccd10a7b8c53e84d4b83a555b8d05f | [] | no_license | KittenHero/QtPoolGame | 14f8351635e6f6eaabbc1c221f016bf5c78d8637 | f9eb51cb328a3054b2173283a328a25053363767 | refs/heads/master | 2020-03-09T12:18:25.065379 | 2018-06-21T08:03:46 | 2018-06-21T08:03:46 | 128,782,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | cpp | #include "mainwindow.h"
MainWindow::MainWindow(unique_ptr<SceneManager> pool_scene, QWidget *parent)
: QMainWindow(parent), updater(this), ticker(this), timer(), scene(std::move(pool_scene))
{
this->resize(this->scene->veiwPort());
this->setStyleSheet("Background-color: #000;");
connect(&this->updater, SIGNAL(timeout()), this, SLOT(nextFrame()));
connect(&this->ticker, SIGNAL(timeout()), this, SLOT(tick()));
this->updater.start(1000 / FRAME_RATE);
this->ticker.start(1000 / TICK_RATE);
this->timer.start();
}
void MainWindow::nextFrame() {
this->update();
}
void MainWindow::tick() {
double dtime = timer.restart() / 1000.0;
this->scene->tick(dtime);
}
void MainWindow::paintEvent(QPaintEvent *) {
QPainter painter(this);
this->scene->draw(painter);
}
MainWindow::~MainWindow()
{}
| [
"nariscatboy@gmail.com"
] | nariscatboy@gmail.com |
8d14e5f648fcecb84bb36344c281f9bc28a7134a | b59cceebacb423b54f38775bd88a99f5a15d013b | /aoj/cgl/cgl_7_e.cpp | 393d03d33df0cd6cdc5b9aa4058fe6bc3e6e7bfc | [
"MIT"
] | permissive | yu3mars/proconVSCodeGcc | 5e434133d4e9edf80d02a8ca4b95ee77833fbee7 | fcf36165bb14fb6f555664355e05dd08d12e426b | refs/heads/master | 2021-06-06T08:32:06.122671 | 2020-09-13T05:49:32 | 2020-09-13T05:49:32 | 151,394,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,129 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pic = pair<int, char>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
//region geometry begin
static const double EPS = (1e-10);
double equals(double a, double b) {return (fabs((a)-(b))<EPS);}
class Point{
public:
double x,y;
Point(double x=0, double y=0):x(x),y(y){}
Point operator + (Point p) {return Point(x+p.x, y+p.y);}
Point operator - (Point p) {return Point(x-p.x, y-p.y);}
Point operator * (double a) {return Point(x*a, y*a);}
Point operator / (double a) {return Point(x/a, y/a);}
double abs() {return sqrt(norm());}
double norm() {return x*x+y*y;}
bool operator < (const Point &p) const{
return x!=p.x? x<p.x : y<=p.y;
}
bool operator == (const Point &p) const{
return fabs(x-p.x)<EPS && fabs(y-p.y)<EPS;
}
};
typedef Point Vector;
//senbun
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(), Point p2=Point()):p1(p1),p2(p2){}
};
//tyokusen
typedef Segment Line;
class Circle{
public:
Point c;
double r;
Circle(Point c = Point(), double r=0.0):c(c),r(r){}
};
//takakkei
typedef vector<Point> Polygon;
//naiseki
double dot(Vector a, Vector b){
return a.x*b.x+a.y*b.y;
}
//gaiseki
double cross(Vector a, Vector b){
return a.x*b.y-a.y*b.x;
}
//tyokkou
bool isOrthogonal(Vector a, Vector b)
{
return equals(dot(a,b), 0.0);
}
bool isOrthogonal(Point a1, Point a2, Point b1, Point b2)
{
return equals(dot(a1-a2, b1-b2), 0.0);
}
bool isOrthogonal(Segment a, Segment b)
{
return equals(dot(a.p2-a.p1,b.p2-b.p1), 0.0);
}
//heikou
bool isParallel(Vector a, Vector b)
{
return equals(cross(a,b), 0.0);
}
bool isParallel(Point a1, Point a2, Point b1, Point b2)
{
return equals(cross(a1-a2, b1-b2), 0.0);
}
bool isParallel(Segment a, Segment b)
{
return equals(cross(a.p2-a.p1,b.p2-b.p1), 0.0);
}
// syaei
Point project(Segment s, Point p){
Vector base = s.p2-s.p1;
double r = dot(p-s.p1, base) / base.norm();
return s.p1 + base*r;
}
// hansya
Point reflect(Segment s, Point p){
return p + (project(s,p)-p)*2.0;
}
// ccw
int ccw(Point p0, Point p1, Point p2)
{
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>EPS) return 1; //ccw
if(cross(a,b)<-EPS) return -1; //cw
if(dot(a,b)<-EPS) return 2; //p2-p0-p1
if(a.norm()<b.norm()) return -2; //p0-p1-p2
return 0; //p0-p2-p1
}
// kousa
bool intersect(Point p1, Point p2, Point p3, Point p4){
return (ccw(p1,p2,p3) * ccw(p1,p2,p4)<=0 &&
ccw(p3,p4,p1) * ccw(p3,p4,p2)<=0);
}
bool intersect(Segment s1, Segment s2){
return intersect(s1.p1, s1.p2, s2.p1, s2.p2);
}
double getDistance(Point p1, Point p2)
{
return (p1-p2).abs();
}
double getDistanceLP(Line l, Point p){
return abs(cross(l.p2-l.p1, p-l.p1))/(l.p2-l.p1).abs();
}
double getDistanceSP(Segment s, Point p){
if(dot(s.p2-s.p1, p-s.p1)<-0.0) return (p-s.p1).abs();
if(dot(s.p1-s.p2, p-s.p2)<-0.0) return (p-s.p2).abs();
return getDistanceLP(s,p);
}
double getDistance(Segment s1, Segment s2){
if(intersect(s1,s2)) return 0.0;
return min(min(getDistanceSP(s1,s2.p1),getDistanceSP(s1,s2.p2)),
min(getDistanceSP(s2,s1.p1),getDistanceSP(s2,s1.p2)));
}
Point getCrossPoint(Segment s1, Segment s2){
Vector base = s2.p2-s2.p1;
double d1 = abs(cross(base, s1.p1-s2.p1));
double d2 = abs(cross(base, s1.p2-s2.p1));
double t = d1/(d1+d2);
return s1.p1 + (s1.p2-s1.p1)*t;
}
bool intersect(Circle c, Line l){
return (c.r - getDistanceLP(l,c.c) >=0);
}
pair<Point,Point> getCrossPoints(Circle c, Line l){
assert(intersect(c,l));
Vector pr = project(l, c.c);
Vector e = (l.p2-l.p1)/(l.p2-l.p1).abs();
double base = sqrt(c.r*c.r - (pr-c.c).norm());
pair<Point,Point> ret = make_pair(pr+e*base, pr-e*base);
if(ret.second<ret.first) swap(ret.first, ret.second);
return ret;
}
bool intersect(Circle c1, Circle c2){
return((c1.c-c2.c).abs()<=(c1.r+c2.r+EPS));
}
// kakudo
double arg(Vector p){return atan2(p.y,p.x);}
// hankei, kakudo -> Vector
Vector polar(double a, double r) {return Point(cos(r)*a, sin(r)*a);}
pair<Point,Point> getCrossPoints(Circle c1, Circle c2){
assert(intersect(c1,c2));
double d = (c2.c-c1.c).abs();
double a = acos((c1.r*c1.r + d*d - c2.r*c2.r) / (2*c1.r*d));
double t = arg(c2.c - c1.c);
pair<Point,Point> ret = make_pair(c1.c+polar(c1.r, t+a), c1.c+polar(c1.r,t-a));
if(ret.second<ret.first) swap(ret.first, ret.second);
return ret;
}
// region geometry end
int main(){
std::cout << std::fixed;
std::cout << std::setprecision(10);
double cx,cy,r;
cin>>cx>>cy>>r;
Circle c1 = Circle(Point(cx,cy),r);
cin>>cx>>cy>>r;
Circle c2 = Circle(Point(cx,cy),r);
pair<Point,Point> cp = getCrossPoints(c1,c2);
cout<<cp.first.x<<" "<<cp.first.y<<" "<<cp.second.x<<" "<<cp.second.y<<endl;
return 0;
} | [
"yu3mars@users.noreply.github.com"
] | yu3mars@users.noreply.github.com |
1ef7f44c8fc0b55544efca3e5b2625901efaf53f | 58c5ed40f4ca2487b74d9cea6718f713825f9cb4 | /ogredeps/OgreMain/OgreMain_pch.cpp | 017a346074ac5d2ebe55adee2a40f70f40ba090e | [
"MIT"
] | permissive | maomaoGod/OgreSDK | 594f5501a227bb9b4d5a8de3f48bfca7c154ec95 | f380e274fa6166d9eedd968d93f908ed2fe633f8 | refs/heads/master | 2022-11-16T00:30:04.104799 | 2020-07-11T09:56:33 | 2020-07-11T09:56:33 | 278,834,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 82 | cpp | #include "F:/CPlusPlus/OGRE/OgreSDK/ogre-1.12.6/OgreMain/src/OgreStableHeaders.h"
| [
"linuszhong@tencent.com"
] | linuszhong@tencent.com |
c041eb9d52c0dddc1fc0824f615f7a4fc67b505f | 1a0a58485abd8f8d09cb4efe4945c6285b2bbc06 | /Machiavelli/Machiavelli/stdafx.cpp | baf1077b9ce5bb5bca5511499e1571f837f2ccd2 | [] | no_license | thijnofant/Machiavelli | 48b6c62bdbc0502ed9c44cf740bebe239f888faa | 4bd5113c6f48091f69c9ac2e467cb0de64c183fe | refs/heads/master | 2021-06-10T12:23:05.916967 | 2017-01-24T13:12:05 | 2017-01-24T13:12:05 | 76,498,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Machiavelli.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// NOTE: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"tavandijk@live.nl"
] | tavandijk@live.nl |
4843566d7ab36e1ba1f008a7b61a3b41597b0176 | a454957d997b5dfec4f70271f29e3c842ec1b92b | /DataStructure/test/aizu_dsl_2_h_segment_tree_rangeaddmin.test.cpp | 357d9352dcfc323e412f0723e91a3a7137a6931f | [] | no_license | ngthanhtrung23/ACM_Notebook_new | 5c7337e8d048254b6d20a5ad3c28aa74b49ecde4 | af9432d38a1f0afff373a34e04762aee458b6c6c | refs/heads/master | 2023-08-04T08:14:50.563695 | 2023-05-27T09:22:44 | 2023-05-27T09:22:44 | 29,093,099 | 473 | 185 | null | 2022-11-13T12:56:21 | 2015-01-11T13:46:06 | C++ | UTF-8 | C++ | false | false | 940 | cpp | #define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_H"
#include "../../template.h"
#include "../LazySegTree.h"
void solve() {
int n, q; cin >> n >> q;
vector<RangeSetAddMinSumOps::S> nodes;
REP(i,n) nodes.push_back(RangeSetAddMinSumOps::S{0, 0, 1});
LazySegTree<
RangeSetAddMinSumOps::S,
RangeSetAddMinSumOps::op,
RangeSetAddMinSumOps::e,
RangeSetAddMinSumOps::F,
RangeSetAddMinSumOps::mapping,
RangeSetAddMinSumOps::composition,
RangeSetAddMinSumOps::id
> st(nodes);
while (q--) {
int typ; cin >> typ;
if (typ == 0) {
int l, r, val; cin >> l >> r >> val;
++r;
st.apply(l, r, RangeSetAddMinSumOps::F { RangeSetAddMinSumOps::NOT_SET, val });
} else {
int l, r; cin >> l >> r;
++r;
cout << st.prod(l, r).min << '\n';
}
}
}
| [
"ngthanhtrung23@gmail.com"
] | ngthanhtrung23@gmail.com |
c4deb5b9a50fe3825f09cec94dc27b8895470dc3 | 40ee1f0673bfa1201b6276088157542e0ec850cf | /src/drafted/governance-types.h | 6d3f6a81081084d79d7272a43beb27409930fcde | [
"MIT"
] | permissive | faresd/dacash | 79350abeaa163a17eeb62cc420655b4a0895b828 | 4022fbce0220a472f4ae39f06771750db446d083 | refs/heads/master | 2021-10-24T00:46:57.103190 | 2019-03-20T22:18:27 | 2019-03-20T22:18:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | h |
/*
Main governance types are 1-to-1 matched with governance classes
- subtypes like a DAO is a categorical classification (extendable)
- see governance-classes.h for more information
*/
enum GovernanceObjectType {
// Programmatic Functionality Types
Root = -3,
AllTypes = -2,
Error = -1,
// --- Zero ---
// Actions
ValueOverride = 1,
// -------------------------------
// DACashNetwork - is the root node
DACashNetwork = 1000,
DACashNetworkVariable = 1001,
Category = 1002,
// Actors
// -- note: DAOs can't own property... property must be owned by
// -- legal entities in the local jurisdiction
// -- this is the main reason for a two tiered company structure
// -- people that operate DAOs will own companies which can own things legally
Group = 2000,
User = 2001,
Company = 2002,
// Project - Generic Base
Project = 3000,
ProjectReport = 3001,
ProjectMilestone = 3002,
// Budgets & Funding
Proposal = 4000,
Contract = 4001
};
// Functions for converting between the governance types and strings
extern GovernanceObjectType GovernanceStringToType(std::string strType);
extern std::string GovernanceTypeToString(GovernanceObjectType type);
#endif
| [
"dacash-publisher@dacash.org"
] | dacash-publisher@dacash.org |
b2225a3fa4a557e7124ac988af1302040f63e943 | ac47a421ca3bbba0c0cb80f2ed3b3e5609716681 | /ykgl/jmsh2.cpp | c3281cf59d1395249a0aee13e36a508fdd8488c4 | [] | no_license | along-wds/jiaofeiji_ykgl | 643b826d618408debc680fcb677d62bc39b32ae5 | a1ba335992673aaa6a7c744b3127d57a66eeafce | refs/heads/master | 2020-05-07T18:29:23.010957 | 2019-04-11T09:21:52 | 2019-04-11T09:21:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,015 | cpp | #include "jmsh2.h"
#include "ui_jmsh2.h"
#include "homepage.h"
#include "jmsh1.h"
#include "jmsh3.h"
Jmsh2::Jmsh2(QWidget *parent) :
CommonWidget(0,0,parent),
ui(new Ui::Jmsh2)
{
ui->setupUi(this);
Timer_Label=ui->label_14;
Timer_LcdNumber=ui->lcdNumber;
QPalette lcdpat =ui->lcdNumber->palette();
/*设置颜色,整体背景颜色 颜色蓝色,此函数的第一个参数可以设置多种。如文本、按钮按钮文字、多种*/
lcdpat.setColor(QPalette::Normal,QPalette::WindowText,Qt::white);
//设置当前窗口的调色板
ui->lcdNumber->setPalette(lcdpat);
ui->frame->setObjectName("frame");
ui->frame_2->setObjectName("frame2");
ui->frame_3->setObjectName("frame3");
ui->frame_5->setObjectName("frame5");
ui->frame_6->setObjectName("frame6");
ui->frame->setStyleSheet("QFrame#frame{border-image: url(:/image/picture/ykgl/lineedit.png);}");
ui->frame_2->setStyleSheet("QFrame#frame2{border-image: url(:/image/picture/ykgl/lineedit.png);}");
ui->frame_3->setStyleSheet("QFrame#frame3{border-image: url(:/image/picture/ykgl/lineedit.png);}");
ui->frame_6->setStyleSheet("QFrame#frame6{border-image: url(:/image/picture/ykgl/lineedit.png);}");
ui->frame_5->setStyleSheet("QFrame#frame5{border-image: url(:/image/picture/qietu/xiadaohang.jpg);}");
ui->pushButton_end->setStyleSheet("QPushButton{border-image: url(:/image/picture/ykgl/end.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/ykgl/end.png);}");
ui->pushButton_next->setStyleSheet("QPushButton{border-image: url(:/image/picture/ykgl/next.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/ykgl/next.png);}");
ui->pushButton_pre->setStyleSheet("QPushButton{border-image: url(:/image/picture/ykgl/pre.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/ykgl/pre.png);}");
ui->pushButton_home->setStyleSheet("QPushButton{border-image: url(:/image/picture/qietu/home.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/qietu/home+.png);}");
ui->pushButton_purchase->setStyleSheet("QPushButton{border-image: url(:/image/picture/qietu/purchase.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/qietu/purchase+.png);}");
ui->pushButton_search->setStyleSheet("QPushButton{border-image: url(:/image/picture/qietu/search.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/qietu/search+.png);}");
ui->pushButton_public->setStyleSheet("QPushButton{border-image: url(:/image/picture/qietu/public.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/qietu/public+.png);}");
ui->pushButton_zdbd->setStyleSheet("QPushButton{border-image: url(:/image/picture/qietu/zdbd.png);}"
"QPushButton:pressed{border-image: url(:/image/picture/qietu/zdbd+.png);}");
QFont lablefont;
lablefont.setFamily("Microsoft YaHei UI");
lablefont.setPointSize(12);
ui->label_name->setText(" 姓名");
ui->label_name->setStyleSheet("color:white;");
ui->label_name->setFont(lablefont);
}
void Jmsh2::init()
{
startTimer();
}
Jmsh2::~Jmsh2()
{
delete ui;
}
void Jmsh2::on_pushButton_back_clicked()
{
disconnectSlots();
socket->effect->begin(this, OperateFile::ui_homepage,RIGHTTOLEFT,NONE,CLOSE);
OperateFile::ui_jmsh1->deleteLater();
}
void Jmsh2::on_pushButton_pre_clicked()
{
disconnectSlots();
socket->effect->begin(this, OperateFile::ui_jmsh1,RIGHTTOLEFT,NONE,CLOSE);
}
void Jmsh2::on_pushButton_next_clicked()
{
disconnectSlots();
OperateFile::ui_jmsh3=new Jmsh3();
OperateFile::ui_jmsh3->setAttribute(Qt::WA_DeleteOnClose);
socket->effect->begin(this, OperateFile::ui_jmsh3,LEFTTORIGHT,NONE,HIDE);
}
| [
"wrf0517@163.com"
] | wrf0517@163.com |
e6d225342ecae7558e1b173fd6f81f130ecccb86 | 5908c584b22d8f152deeb4082ff6003d841deaa9 | /Physics_RT/Havok/Source/Geometry/Internal/Algorithms/TreeQueries/hkcdAabbTreeQueries.h | 65e548525811cade42237272c4b4394a5c721dcc | [] | no_license | imengyu/Physics_RT | 1e7b71912e54b14679e799e7327b7d65531811f5 | b8411b4bc483d6ce5c240ae4c004f3872c64d073 | refs/heads/main | 2023-07-17T20:55:39.303641 | 2021-08-28T18:25:01 | 2021-08-28T18:25:01 | 399,414,182 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,354 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HKAI_TREE_QUERIES
#define HKAI_TREE_QUERIES
class hkAabb;
/// Interface for queries through an hkcdStaticAabbTree or hkcdDynamicAabbTree
class hkcdAabbTreeQueries
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_AI, hkcdAabbTreeQueries);
/// Interface for raycasting
class RaycastCollector
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_AI, RaycastCollector );
RaycastCollector() {}
virtual ~RaycastCollector() {}
/// Callback that is triggered when the ray reaches a leaf of the tree.
/// Returns true if the ray hit the leaf.
/// If the cast against the leaf hits, hitFractionInOut should be updated to the smaller hit fraction.
virtual hkBool32 processLeaf( hkUint32 leafKey, const hkAabb& leafAabb, hkSimdReal& hitFractionInOut) = 0;
};
/// Interface for AABB querues
class AabbCollector
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_AI, AabbCollector );
AabbCollector() {}
virtual ~AabbCollector() {}
/// Callback that is triggered when the AABB overlaps a leaf of the tree
/// The query will stop if it returns false.
virtual hkBool32 processLeaf( hkUint32 leafKey, const hkAabb& leafAabb ) = 0;
};
/// Interface for closest point queries
class ClosestPointCollector
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_AI, ClosestPointCollector );
ClosestPointCollector() {}
virtual ~ClosestPointCollector() {}
/// Callback that is triggered when the query is near a leaf of the tree.
/// Returns the distance squared to leaf, and sets closestPointOut to be the closest point on the leaf
virtual hkSimdReal processLeaf( hkUint32 leafKey, const hkAabb& leafAabb, hkVector4Parameter queryPoint, hkVector4& closestPointOut, hkSimdRealParameter closestDistanceSquared ) = 0;
};
/// Interface for all-pairs queries
class AllPairsCollector
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_AI, AllPairsCollector );
AllPairsCollector() {}
virtual ~AllPairsCollector() {}
virtual void processPair( hkUint32 leafKeyA, const hkAabb& leafAabbA, hkUint32 leafKeyB, const hkAabb& leafAabbB ) = 0;
};
};
#endif //HKAI_TREE_QUERIES
/*
* Havok SDK - Base file, BUILD(#20131218)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from salesteam@havok.com.
*
*/
| [
"1501076885@qq.com"
] | 1501076885@qq.com |
e2c8379c35af4804b62287dc25b16a3b8ec1a048 | 244231ebd1a44da9e9b3a2394e2a9d018c824bdf | /数据结构、算法与应用-C++语言描述(第二版)/本书的codes/mergeSort.h | d6293720c19d51b703eb4da8f604b1638185854c | [] | no_license | lchy1037/Algorithm-Notes | df7e4576a4fe040f579ff27217c915ea2d7e158a | 5c0516fc1da685dc0b6b51ecd82166705482f3b3 | refs/heads/master | 2021-01-20T07:18:46.951135 | 2017-09-20T12:05:46 | 2017-09-20T12:05:46 | 101,531,372 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,843 | h |
// iterative merge sort
#ifndef mergeSort_
#define mergeSort_
using namespace std;
template <class T>
void mergeSort(T a[], int n)
{// Sort a[0 : n - 1] using the merge sort method.
T *b = new T [n];
int segmentSize = 1;
while (segmentSize < n)
{
mergePass(a, b, n, segmentSize); // merge from a to b
segmentSize += segmentSize;
mergePass(b, a, n, segmentSize); // merge from b to a
segmentSize += segmentSize;
}
}
template <class T>
void mergePass(T x[], T y[], int n, int segmentSize)
{// Merge adjacent segments from x to y.
int i = 0; // start of the next segment
while (i <= n - 2 * segmentSize)
{// merge two adjacent segments from x to y
merge(x, y, i, i + segmentSize - 1, i + 2 * segmentSize - 1);
i = i + 2 * segmentSize;
}
// fewer than 2 full segments remain
if (i + segmentSize < n)
// 2 segments remain
merge(x, y, i, i + segmentSize - 1, n - 1);
else
// 1 segment remains, copy to y
for (int j = i; j < n; j++)
y[j] = x[j];
}
template <class T>
void merge(T c[], T d[], int startOfFirst, int endOfFirst,
int endOfSecond)
{// Merge two adjacent segments from c to d.
int first = startOfFirst, // cursor for first segment
second = endOfFirst + 1, // cursor for second
result = startOfFirst; // cursor for result
// merge until one segment is done
while ((first <= endOfFirst) && (second <= endOfSecond))
if (c[first] <= c[second])
d[result++] = c[first++];
else
d[result++] = c[second++];
// take care of leftovers
if (first > endOfFirst)
for (int q = second; q <= endOfSecond; q++)
d[result++] = c[q];
else
for (int q = first; q <= endOfFirst; q++)
d[result++] = c[q];
}
#endif
| [
"lchyhust@qq.com"
] | lchyhust@qq.com |
d147860c0da6cd2ce9e8ad0ac6579da27442d8a4 | bc71140d481370d14e29ef3d9f3fc650089942fc | /ncap/Ifc58/examples/PC2-Vision/SeqSnap/TrgSheet.h | d8c738dadb046fca53712d7bae4d3b592ac28e51 | [] | no_license | thangduong/optical_imaging | ca65682ec0633b8271098ca3e56d840774adfedf | bc8b4e49c44e5484a6f21c63658ad15929d0ae63 | refs/heads/master | 2021-09-15T13:47:37.153018 | 2018-03-10T00:18:56 | 2018-03-10T00:18:56 | 124,606,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,908 | h | /******************************************************************************
*
* MODULE
* TrgSheet.h
*
* REVISION INFORMATION
* $Logfile: /ifc/examples/PCVision2/SeqSnap/TrgSheet.h $
* $Revision: 1.1 $
* $Modtime: 9/16/02 9:35a $
*
* ABSTRACT
* PCVision2 Example Program
*
* TECHNICAL NOTES
*
*
* Copyright (c) 2000 Coreco Imaging, Inc. All rights reserved.
*
******************************************************************************/
#if !defined(AFX_TRGSHEET_H__237127C8_334A_11D1_AE32_00A0C959E757__INCLUDED_)
#define AFX_TRGSHEET_H__237127C8_334A_11D1_AE32_00A0C959E757__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// TrgSheet.h : header file
//
class CTrgSheet;
#include "trgGrab.h"
#include "seqsnapV.h"
#include "trigpro.h"
/////////////////////////////////////////////////////////////////////////////
// CTrgSheet
class CTrgSheet : public CPropertySheet
{
DECLARE_DYNAMIC(CTrgSheet)
// Construction
public:
CTrgSheet(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
CTrgSheet(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTrgSheet)
public:
virtual BOOL OnInitDialog();
virtual BOOL DestroyWindow();
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CTrgSheet();
CTrgGrab *m_trigProp;
CSeqsnapView *m_vparent;
CTrigPro *m_trigAttr[2];
// Generated message map functions
protected:
//{{AFX_MSG(CTrgSheet)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TRGSHEET_H__237127C8_334A_11D1_AE32_00A0C959E757__INCLUDED_)
| [
"thang@quantee.com"
] | thang@quantee.com |
62698a121e2ff6b19dad20f16c97be23542e8213 | 5fb53d866d2db9bdf259326b549611709cdb1dca | /controller/simple/simple.ino | 4270e37a7d9777ffeacb6462b411a1e5ea2f1daa | [] | no_license | ajmendez/graffito | 3a2adacd95682b37abfd0d49e38eac4b3d2a00d7 | 72d37df2bb333724115ee0b93b5aec4652f1d9b3 | refs/heads/master | 2016-09-06T03:42:36.550991 | 2014-07-04T07:08:47 | 2014-07-04T07:08:47 | 19,099,674 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | ino | /* Debug communication
Mendez May 2014
Take in data from the serial, and push it out to the telescope
CMD: 59 4 13 17 36 9 177
CMD: 59 4 13 17 37 0 185
*/
#include <LiquidCrystal.h>
#define HWSERIAL Serial1 //switch to this
LiquidCrystal lcd(PIN_B0, PIN_B1, PIN_B2, PIN_B3, PIN_B7, PIN_D0);
//HardwareSerial Uart = HardwareSerial();
#define Uart Serial1
int inbyte;
char outbyte;
String outstr = "";
char sep = ' ';
char newline = '\n';
boolean isdone = false;
boolean ispython = true;
int iskip = 59;
int ichar = 0;
void communicate() {
while (Uart.available() > 0 ) {
inbyte = Uart.read();
if (ispython) {
Serial.print((char)inbyte);
} else {
if (inbyte == 59) Serial.println();
Serial.print(inbyte);
Serial.print(' ');
}
}
while (Serial.available() > 0) {
outbyte = Serial.read();
// if (outbyte == newline) isdone = true;
if ((outbyte == sep)|(outbyte==newline)) break;
outstr += outbyte;
}
}
void sendMesg() {
if (outstr.length() > 0 ) {
outstr += ' ';
int s = outstr.toInt();
lcd.setCursor(ichar, 1);
if (s == iskip) ichar = 0;
ichar += outstr.length();
lcd.print(s);
Uart.write((char)s);
outstr = "";
}
}
void setup() {
Serial.begin(19200);
Uart.begin(19200);
lcd.begin(16,4);
}
void loop() {
communicate();
sendMesg();
lcd.setCursor(0,0);
lcd.print(millis()/100);
}
| [
"bluespace@gmail.com"
] | bluespace@gmail.com |
41d5d5f491eddd033664bb401f7c4555aaf6aae6 | 08e8f2e9654a3611e7c8e79d334699ae6b526cb0 | /main.cpp | cc21397d76a1715498e7d39d68a9ccc52ce52b5b | [] | no_license | Sedovlas96/QueneOnSingleLinkedList | f62bf572dd2dbf9b97ae3188cee988c4524137f8 | 68a084e88565fff77731e50196128be91510c374 | refs/heads/master | 2016-09-05T09:22:49.927775 | 2014-05-22T20:09:17 | 2014-05-22T20:09:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,684 | cpp | #include <iostream>
#include "list.h"
#include "list.console.h"
#include <stdlib.h>
using namespace std;
int main()
{
QueneOnSingleLinkedList = quene;
Data data;
int key = 0;
do
{
cout << " It's Singly-Linked List: " << endl;
showNumber( firstNumber );
cout<<endl;
showNumber( secondNumber );
cout << endl;
cout << " What do you want to do with these QUENE? " << endl;
cout << " ~1~ - For enter data into the tail " << endl;
cout << " ~2~ - For delete element from the head " << endl;
cout << " ~3~ - For show the Singly-Linked List " << endl;
cout << " ~4~ - For clear the whole list " << endl;
cout << " ~5~ - For check the list is empty or not " << endl;
cout << " ~0~ - For exit " << endl;
cin >> key;
switch( key )
{
case 1:
{
system( " cls " );
data = inputData( data );
quene.push( data );
}
break;
case 2:
{
system( " cls " );
quene.pop( );
}
break;
case 3:
{
system( " cls " );
quene.showQuene( );
}
break;
case 4:
{
system( " cls " );
quene.clearQuene( );
}
break;
case 5:
{
system( " cls " );
if( quene.queneIsEmpty( ) )
{
cout << " Quene isn't empty ";
}
else
{
cout << " Quene is empty ";
}
}
break;
}
while( key );
return 0;
}
| [
"Egolior@mail.ru"
] | Egolior@mail.ru |
a85d95dc52bb60012618063bc54d3dd552626d57 | 7a00f32084031bf4bf025d6680200da5a48f3e26 | /basic_game_engine/game.cpp | 98786e8fcd8ed36d8ccb6e033156846596447e70 | [] | no_license | MusaTamzid05/C-Plus-Plus_Pros | a99848062926ff673c3da02883c50fad8136a745 | 444ace26e0978e42e4b5d1d93fefc1bf8e88fa02 | refs/heads/master | 2021-01-12T07:24:31.015274 | 2017-11-15T10:45:03 | 2017-11-15T10:45:03 | 76,951,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,633 | cpp | #include "game.h"
#include <iostream>
#include <stdlib.h>
#include <string>
namespace GameEngine{
Game::Game(const std::string& window_name , int width_ , int height_){
initialize_font();
initialize_states();
m_window = new sf::RenderWindow(sf::VideoMode(width_ , height_), window_name);
}
Game::~Game(){
delete m_window;
}
void Game::run(int minimum_framerate){
sf::Clock clock;
sf::Time time_since_last_update = sf::Time::Zero;
sf::Time time_per_frame = sf::seconds(1.0 / minimum_framerate);
while(m_window->isOpen()){
process_event();
time_since_last_update += clock.restart();
// if the time since the last update is better than the time per frame
// then we need to do some extra updates
if(time_since_last_update > time_per_frame){
time_since_last_update -= time_per_frame;
process_event();
update(time_per_frame);
}
render();
}
}
void Game::process_event(){
sf::Event event;
while(m_window->pollEvent(event)){
if(event.type == sf::Event::Closed)
m_window->close();
}
}
void Game::update(sf::Time& delta_time){
}
void Game::render(){
m_window->clear();
show_framerate();
m_window->display();
}
void Game::initialize_font(){
if(!m_font.loadFromFile("font/default.ttf")){
std::cerr << "Could not load the font.\n";
exit(1);
}
initialize_text();
}
void Game::initialize_text(){
m_text.setFont(m_font);
m_text.setCharacterSize(24);
m_text.setFillColor(sf::Color::Red);
m_text.setStyle(sf::Text::Bold | sf::Text::Underlined);
}
void Game::initialize_states(){
statistics_time = sf::Time::Zero;
num_frames = 0;
}
void Game::update_states(sf::Time& elasped_time){
statistics_time += elasped_time;
num_frames += 1;
calculate_framerate();
}
void Game::calculate_framerate(){
if(statistics_time >= sf::seconds(1.0f)){
m_text.setString("Frame / Second = " + std::to_string(num_frames) + "\n" +
"Time / Update = " + std::to_string(statistics_time.asMicroseconds() / num_frames) + " us");
statistics_time -= sf::seconds(1.0f);
num_frames = 0;
}
}
void Game::show_framerate(){
m_window->draw(m_text);
}
};
| [
"tamzid834@gmail.com"
] | tamzid834@gmail.com |
34ca5be3181d3b94e0d4c0ddd61e09cb9e5b5011 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14079/function14079_schedule_37/function14079_schedule_37.cpp | d05e173eccb5bc542d93bba1eaaf9d744f4f0b0a | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14079_schedule_37");
constant c0("c0", 128), c1("c1", 128), c2("c2", 64), c3("c3", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i1, i3}, p_int32);
input input01("input01", {i0, i1, i2}, p_int32);
input input02("input02", {i3}, p_int32);
computation comp0("comp0", {i0, i1, i2, i3}, input00(i1, i3) - input01(i0, i1, i2) - input02(i3));
comp0.tile(i0, i1, i2, 64, 128, 32, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf00("buf00", {128, 64}, p_int32, a_input);
buffer buf01("buf01", {128, 128, 64}, p_int32, a_input);
buffer buf02("buf02", {64}, p_int32, a_input);
buffer buf0("buf0", {128, 128, 64, 64}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf0}, "../data/programs/function14079/function14079_schedule_37/function14079_schedule_37.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
e60ed0e13bdcee6c6821956512fef7ccbd742528 | 67bf93cfae8f8153e65601fd3bc5442349ee665c | /Chapter4/pe4-3.cpp | b637d52883f18a74e0edb55d67030420fd9b79b3 | [] | no_license | Ali-Fawzi-Lateef/C-PrimerPlus | ce86c880dc3a2b6b4eda6a277463563136c1cc00 | f53bca85c36dffb768aa18a15d0446dd766fe309 | refs/heads/master | 2023-08-02T02:38:05.418154 | 2021-09-23T18:06:47 | 2021-09-23T18:06:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 662 | cpp | // pe4-3.cpp -- asks for the user's name and displays it using char arrays and the cstring header file
// This is exercise 3 of chapter 4 in C++ Primer Plus by Stephen Prata
#include<iostream>
#include<cstring>
int main(void)
{
using namespace std;
cout << "Enter your first name: ";
char first_name[20];
cin.getline(first_name,20);
first_name[19] = '\0';
cout << "Enter your last name: ";
char last_name[20];
cin.getline(last_name,20);
last_name[19] = '\0';
char full_name[40];
strcpy(full_name, strcat(strcat(last_name, ", "), first_name));
cout << "Here's the information on a single string: "
<< full_name
<< endl;
return 0;
}
| [
"nruderman.s@gmail.com"
] | nruderman.s@gmail.com |
9bb907b8994ba32a9f3718a12324950392060be0 | 522a944acfc5798d6fb70d7a032fbee39cc47343 | /d6k/trunk/src/scadastudio/aicumulativestatisticsmodel.h | 64b07c8f9de8910c403ee31c99cfbc62d557eee2 | [] | no_license | liuning587/D6k2.0master | 50275acf1cb0793a3428e203ac7ff1e04a328a50 | 254de973a0fbdd3d99b651ec1414494fe2f6b80f | refs/heads/master | 2020-12-30T08:21:32.993147 | 2018-03-30T08:20:50 | 2018-03-30T08:20:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,550 | h | #ifndef AICUMULATIVESTATISTICSMODEL_H
#define AICUMULATIVESTATISTICSMODEL_H
#include <QAbstractTableModel>
class CAICumulativeStatisticsModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum COLUMN
{
ID, TagName, Desc, OccNo, BlockOccNo/*, DataType*/, InitQua, Address, PinLabel, InitValue, /*Format,*/ Unit, Enable,
MaxRaw, MinRaw, MaxConvert, MinConvert, ScaleTagName, /*ScaleType*//*, ScaleDesc,*/ RangeL, RangeH, HighQua, LowQua,
SaveDisk, SaveDiskPeriod, SaveDB, SaveDBPeriod, Sensitivity, SensitivityType, AlarmTagName, /*AlarmType*//*, AlarmDesc,*/
ChannelOccNo, DeviceOccNo, ReferenceCount, DataSource, Express,
};
public:
CAICumulativeStatisticsModel(QObject *parent);
~CAICumulativeStatisticsModel();
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
void RefrushModel();
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
//void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
bool InsertRows(int position, int rows, const QModelIndex &parent = QModelIndex());
bool RemoveRows(int position, int rows, const QModelIndex &parent = QModelIndex());
private:
void InitPara();
private:
QStringList m_lstHorizontalHeader;
};
#endif // AICUMULATIVESTATISTICSMODEL_H
| [
"xingzhibing_ab@hotmail.com"
] | xingzhibing_ab@hotmail.com |
b8ee97186f6042bfe9b001ee918273e401b503c5 | 67b12f8403572d8114b6baccc58d20661159a2ee | /src/media/base/neva/neva_mime_util_internal_stub.cc | fdf0ff3d8a925b24f058fa33eaf760b31ba35aee | [
"BSD-3-Clause"
] | permissive | Igalia/chromium68 | 08b257ce3b99bb827c2eaf701f61752cc31d6333 | c4d219c3e4b8936e1a94a77bc047b2a08dfd09b8 | refs/heads/integrate_upstream_ozone | 2021-06-30T18:23:01.034847 | 2018-12-06T08:12:07 | 2018-12-06T08:12:07 | 159,666,720 | 0 | 4 | null | 2018-12-18T14:17:14 | 2018-11-29T12:59:43 | null | UTF-8 | C++ | false | false | 944 | cc | // Copyright (c) 2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "media/base/neva/neva_mime_util_internal.h"
namespace media {
namespace internal {
NevaMimeUtil::NevaMimeUtil() {}
NevaMimeUtil::~NevaMimeUtil() {}
void NevaMimeUtil::InitializeMimeTypeMaps() {}
void NevaMimeUtil::AddSupportedMediaFormats() {}
} // namespace internal
} // namespace media
| [
"lokeshkumar.goel@lge.com"
] | lokeshkumar.goel@lge.com |
f7b8087aedd0958921c2e48d23f05aa7c100b82c | 541475dd2f653df6a077efaeeea5df9ba9eeb0b7 | /windows/OpenCV-Template/Debug.cpp | 1719403e25d307faf89a12dcb4ed47908e932710 | [] | no_license | yoursoultree/ANE-Windows-Template | e5279696de8eed95c0997b667160fff6faf88c60 | a503c54003ca4c17e469fab8fdd215c8d2b56f56 | refs/heads/master | 2021-04-15T08:46:23.503989 | 2014-06-16T00:58:40 | 2014-06-16T00:58:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224 | cpp | #include "Debug.h"
namespace ANE {
using namespace std;
void log(string msg) {
string s = "ANE >> ";
s += msg;
wstring stemp = wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
OutputDebugString(sw);
}
} | [
"sewon.ahn@itpointlab.com"
] | sewon.ahn@itpointlab.com |
28697054f29a1163e7a3304b59aa3c52fe207b1e | 20b49a6ef1fa417d67abef2d29a598c9e41c478e | /atCoder/Beginner Contests/Beginner Contest 141/A.cpp | 2e12215c7f2e2528b6d5442ca6128ce1376f4a73 | [] | no_license | switchpiggy/Competitive_Programming | 956dac4a71fdf65de2959dd142a2032e2f0710e1 | beaaae4ece70889b0af1494d68c630a6e053558a | refs/heads/master | 2023-04-15T19:13:12.348433 | 2021-04-04T06:12:29 | 2021-04-04T06:12:29 | 290,905,106 | 1 | 3 | null | 2020-10-05T20:16:53 | 2020-08-27T23:38:48 | C++ | UTF-8 | C++ | false | false | 291 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
string s;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> s;
if(s == "Sunny") cout << "Cloudy\n";
else if(s == "Cloudy") cout << "Rainy\n";
else cout << "Sunny\n";
return 0;
} | [
"switchpiggy@users.noreply.github.com"
] | switchpiggy@users.noreply.github.com |
a987abe40b22c62e64d90ada533f497df357c9b2 | e2e4a5e8763c2e3dcddf0ce5027db29b0526f164 | /src/GuessingGameState.cpp | 3284138957b024a62a5e9ba9e547d92e3d1aa20d | [] | no_license | szykol/design-patterns-proj | ac5d870b074407515a69f3924a1530d67dbd94d0 | 676d80cc472805cad724f91e6a0f64d90ac732bd | refs/heads/master | 2022-06-20T04:33:00.687296 | 2020-05-06T07:01:28 | 2020-05-06T07:01:28 | 261,291,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include "GuessingGame.h"
#include "GuessingGameState.h"
#include <memory>
void GuessingGameState::start(GuessingGame &game) {}
void GuessingGameState::finish(GuessingGame &game) {}
void GameStartingState::finish(GuessingGame &game)
{
game.setState(std::make_unique<GameFinishingState>());
}
void GameFinishingState::start(GuessingGame &game)
{
game.setState(std::make_unique<GameStartingState>());
}
| [
"szymonkolton@gmail.com"
] | szymonkolton@gmail.com |
4f38dce9ca5af2b5ee721fbf55ba27e0193e8b57 | f9fb4d3f243beadd010e119f38523a62cc235288 | /next_greater_element.cpp | 45c4e7a75c21d18a4a97ab3f05ca54f75018294f | [] | no_license | Wonkyu-Lee/LogicPractice | c539839b25bd79bb0e8867237d4e175b6ee84a10 | 08306a31b574f66b53538afa91c69579a2b5c1c1 | refs/heads/master | 2021-09-12T13:18:30.026362 | 2018-04-17T06:25:51 | 2018-04-17T06:25:51 | 107,825,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | cpp | //
// Created by blazeq on 2018. 2. 6..
//
#include "catch.hpp"
#include <iostream>
#include <stack>
namespace {
using namespace std;
void findNextGreaterElement(int array[], int n, int result[]) {
stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && array[st.top()] < array[i]) {
result[st.top()] = i;
st.pop();
}
st.push(i);
}
while (!st.empty()) {
result[st.top()] = n;
st.pop();
}
}
} // namespace
TEST_CASE("Next greater element", "[next greater element]") {
int array[] = {4, 5, 7, 5, 2, 25};
int n = sizeof(array) / sizeof(int);
int result[n];
findNextGreaterElement(array, n, result);
for (int i = 0; i < n; ++i) {
printf("NGE of %d = %d, ", array[i], (result[i] == n ? -1 : array[result[i]]));
}
cout << endl;
} | [
"wkyulees@gmail.com"
] | wkyulees@gmail.com |
9a4b5e2566ec375348ee50995b0de096c650e7d7 | 9da42e04bdaebdf0193a78749a80c4e7bf76a6cc | /third_party/gecko-10/win32/include/nsIDOMSVGAnimatedLengthList.h | a86fc97ee9c75756481c61bf2dd07ddcf15caab5 | [
"Apache-2.0"
] | permissive | bwp/SeleniumWebDriver | 9d49e6069881845e9c23fb5211a7e1b8959e2dcf | 58221fbe59fcbbde9d9a033a95d45d576b422747 | refs/heads/master | 2021-01-22T21:32:50.541163 | 2012-11-09T16:19:48 | 2012-11-09T16:19:48 | 6,602,097 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,523 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/dom/interfaces/svg/nsIDOMSVGAnimatedLengthList.idl
*/
#ifndef __gen_nsIDOMSVGAnimatedLengthList_h__
#define __gen_nsIDOMSVGAnimatedLengthList_h__
#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMSVGLengthList; /* forward declaration */
/* starting interface: nsIDOMSVGAnimatedLengthList */
#define NS_IDOMSVGANIMATEDLENGTHLIST_IID_STR "bfa6e42b-bc9d-404d-8688-729fdbfff801"
#define NS_IDOMSVGANIMATEDLENGTHLIST_IID \
{0xbfa6e42b, 0xbc9d, 0x404d, \
{ 0x86, 0x88, 0x72, 0x9f, 0xdb, 0xff, 0xf8, 0x01 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMSVGAnimatedLengthList : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSVGANIMATEDLENGTHLIST_IID)
/* readonly attribute nsIDOMSVGLengthList baseVal; */
NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGLengthList * *aBaseVal) = 0;
/* readonly attribute nsIDOMSVGLengthList animVal; */
NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGLengthList * *aAnimVal) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSVGAnimatedLengthList, NS_IDOMSVGANIMATEDLENGTHLIST_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMSVGANIMATEDLENGTHLIST \
NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGLengthList * *aBaseVal); \
NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGLengthList * *aAnimVal);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMSVGANIMATEDLENGTHLIST(_to) \
NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGLengthList * *aBaseVal) { return _to GetBaseVal(aBaseVal); } \
NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGLengthList * *aAnimVal) { return _to GetAnimVal(aAnimVal); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMSVGANIMATEDLENGTHLIST(_to) \
NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGLengthList * *aBaseVal) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetBaseVal(aBaseVal); } \
NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGLengthList * *aAnimVal) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAnimVal(aAnimVal); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMSVGAnimatedLengthList : public nsIDOMSVGAnimatedLengthList
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMSVGANIMATEDLENGTHLIST
nsDOMSVGAnimatedLengthList();
private:
~nsDOMSVGAnimatedLengthList();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMSVGAnimatedLengthList, nsIDOMSVGAnimatedLengthList)
nsDOMSVGAnimatedLengthList::nsDOMSVGAnimatedLengthList()
{
/* member initializers and constructor code */
}
nsDOMSVGAnimatedLengthList::~nsDOMSVGAnimatedLengthList()
{
/* destructor code */
}
/* readonly attribute nsIDOMSVGLengthList baseVal; */
NS_IMETHODIMP nsDOMSVGAnimatedLengthList::GetBaseVal(nsIDOMSVGLengthList * *aBaseVal)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMSVGLengthList animVal; */
NS_IMETHODIMP nsDOMSVGAnimatedLengthList::GetAnimVal(nsIDOMSVGLengthList * *aAnimVal)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMSVGAnimatedLengthList_h__ */
| [
"haleokekahuna@gmail.com"
] | haleokekahuna@gmail.com |
937f638747d9478365501f873bfb147d974defb4 | a3969761862ed18cfe34a0861a04ee0c8fc9415d | /tester/tests/stack.cpp | 875bb27c9ceda25a6d1cbdf1c7bedbcbf8e3b585 | [] | no_license | timlecou/ft_containers | feea7c07f3394b07033ea3d1e309bc30859af0a3 | bbd3da8c85a9e888860deb31731fada20c61f7b5 | refs/heads/main | 2023-04-03T10:19:41.002932 | 2021-04-03T17:15:41 | 2021-04-03T17:15:41 | 341,824,046 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | cpp | #include "tests.hpp"
static void constructors(void)
{
print_header("Constructor");
ft::stack<int> q1;
std::stack<int> q2;
check("q1.size() == q2.size()", q1.size() == q2.size());
check("q1.empty() == q2.empty()", q1.empty() == q2.empty());
}
static void front_back(void)
{
print_header("Front / Back / Push / Pop");
ft::stack<int> q1;
std::stack<int> q2;
q1.push(0);
q1.push(1);
q1.push(2);
q2.push(0);
q2.push(1);
q2.push(2);
check("q1.size() == q2.size()", q1.size() == q2.size());
check("q1.empty() == q2.empty()", q1.empty() == q2.empty());
check("q1.top() == q2.top()", q1.top(), q2.top());
q1.pop();
q2.pop();
check("q1.size() == q2.size()", q1.size() == q2.size());
check("q1.top() == q2.top()", q1.top(), q2.top());
}
void test_stack(void)
{
print_header("Stack");
constructors();
front_back();
}
| [
"timlecou@student.42.fr"
] | timlecou@student.42.fr |
52404d3b9bd0e6565bcd211df51844290a4cd19d | 0408d086a3fd502113588a61b36755fe23f55b10 | /code/7983 내일 할거야.cpp | 7fa6bcca9d8c141fafa208370618e90f19bc7bee | [] | no_license | dwax1324/baekjoon | 6dfcf62f2b1643480b16777c37f4e5d711b932d9 | 3a6daf8a66dbb304af8a4002989c081dcffc831d | refs/heads/main | 2023-04-03T03:56:50.410972 | 2021-03-29T11:51:30 | 2021-03-29T11:51:30 | 310,809,466 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,506 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int, int>
#define pic pair<int, char>
#define pipii pair<int, pii>
#define pll pair<long, long>
#define ror(begin, end, i) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define fastio ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout)
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define is ==
#define isnot !=
#define F first
#define S second
#define error(args...) \
{ \
string _s = #args; \
replace(_s.begin(), _s.end(), ',', ' '); \
stringstream _ss(_s); \
istream_iterator<string> _it(_ss); \
err(_it, args); \
cout << '\n'; \
}
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cout << *it << " = " << a << ' ';
err(++it, args...);
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
그리디
블럭쌓아가듯이 맨뒤에서부터
변수 cur을 끝나는시간 - 걸리는시간 로 초기화 시키고
만약 cur이 다음 끝나는 시간보다 일찍 끝나면
cur을 다음시간의 끝나는 시간으로 초기화시키고
아니면 시간이 연장됐기 때문에 cur을 cur+ 걸리는 시간으로 초기화한다.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
void preprocess() {
}
void solve() {
int n;
cin >> n;
vector<pii> v(n);
ror(0, n, i) {
cin >> v[i].F >> v[i].S;
}
sort(all(v), [](pii a, pii b) {
if (a.S == b.S) return a.F > b.F;
return a.S < b.S;
});
int cur = v[n - 1].S - v[n - 1].F;
ror(n - 1, 0, i) {
if (cur > v[i].S) {
cur = v[i].S - v[i].F;
} else {
cur = cur - v[i].F;
}
}
cout << cur;
}
int main() {
fastio;
debug; // ✨✨✨✨✨✨✨✨✨✨✨✨✨✨
int t = 1;
// cin >> t; // ✨✨✨✨✨✨✨✨✨✨✨✨✨✨
preprocess();
ror(0, t, i) {
// cout << "case #" << t << ": ";
solve();
}
} | [
"dwax1324@gmail.com"
] | dwax1324@gmail.com |
f02dbf4915eff194e712a7a2ba03192d1440b4b4 | 6406df4295b6ed6d54ddd7463dfc6df74e2930f1 | /src/aarch64.cpp | 0f254cf5a6cfc79f8d31458e1d4fae90dc071833 | [] | no_license | machinamentum/irplaygroundthingy | 2c0a16cb079170dac3a7e0806d27c41021cc2444 | 2bdf22a26738373b431e519d83c4d51172c6a004 | refs/heads/master | 2023-04-18T04:09:16.139168 | 2021-05-03T05:02:30 | 2021-05-03T05:02:30 | 284,346,468 | 13 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 40,620 | cpp | #include "general.h"
#include "linker_object.h"
#include "ir.h"
#include "aarch64.h"
using namespace josh;
enum Integer_Register : u8 {
GP_R0 = 0,
GP_R7 = 7,
GP_R9 = 9,
GP_R29 = 29,
GP_R30 = 30,
GP_MAX = GP_R30,
SP = 31,
// PC = 32,
};
#define OP_GROUP(op) (((op) & 0xFF) << 25)
#define OP0_RESERVED OP_GROUP(0b0000)
#define _OP0_UNALLOCATED OP_GROUP(0b0001)
#define OP0_SVE OP_GROUP(0b0010)
#define _OP0_UNALLOCATED2 OP_GROUP(0b0011)
#define OP0_DATA_IMM OP_GROUP(0b1000) // 100x
#define OP0_BRANCH OP_GROUP(0b1010) // 101x
#define OP0_LOAD_STORE OP_GROUP(0b0100) // x1x0
#define OP0_DATA_REG OP_GROUP(0b0101) // x101
#define OP0_SCALAR_FLOAT OP_GROUP(0b0111)
#define DATA_IMM_SUBOP0(op0) (((op0) & 0b111) << 23)
#define DATA_IMM_ADD_SUB DATA_IMM_SUBOP0(0b010)
#define DATA_IMM_ADD_SUB_W_TAGS DATA_IMM_SUBOP0(0b011)
#define DATA_IMM_ADR DATA_IMM_SUBOP0(0b000)
#define DATA_IMM_ADRP (1 << 31)
#define DATA_IMM_ADR_IMMHI(imm) ((((imm) >> 2) & 0x7FFFF) << 5) // 19 bits >.>
#define DATA_IMM_ADR_IMMLO(imm) (((imm) & 0b11) << 29)
#define DATA_IMM_ADR_Rd(Rd) ((Rd) & 0x1F)
#define BRANCH_SUBOP0(op0) (((op0) & 0b111) << 29)
#define BRANCH_SUBOP1(op1) (((op1) & 0x3FFF) << 12)
#define BRANCH_SUBOP2(op2) (((op2) & 0x1F))
#define BRANCH_UNC_REG_CLASS (OP0_BRANCH | BRANCH_SUBOP0(0b110) | (1 << 25))
#define BRANCH_UNC_REG_OPC(opc) (((opc) & 0xF) << 21)
#define BRANCH_UNC_REG_OP2(op2) (((op2) & 0x1F) << 16)
#define BRANCH_UNC_REG_OP3(op3) (((op3) & 0x3F) << 10)
#define BRANCH_UNC_REG_Rn(Rn) (((Rn) & 0x1F) << 5)
#define BRANCH_UNC_REG_OP4(op4) ((op4) & 0x1F)
#define BRANCH_UNC_IMM_IMM26(imm26) ((imm26) & 0x3FFFFFF)
#define BRANCH_UNC_IMM_BL (1 << 31)
#define EXCEPTION_CLASS (OP0_BRANCH | BRANCH_SUBOP0(0b110))
#define EXCEPTION_OPC(opc) (((opc) & 0b111) << 21)
#define EXCEPTION_IMM16(imm16) (((imm16) & 0xFFFF) << 5)
#define EXCEPTION_OP2(op2) (((op2) & 0b111) << 2)
#define EXPCETION_LL(ll) ((ll) & 0b11)
#define LOAD_STORE_OP0(op0) (((op0) & 0xF) << 28)
#define LOAD_STORE_OP1(op1) (((op1) & 1) << 26)
#define LOAD_STORE_OP2(op2) (((op2) & 0b11) << 23)
#define LOAD_STORE_OP3(op3) (((op3) & 0x3F) << 16)
#define LOAD_STORE_OP4(op4) (((op4) & 0b11) << 10)
// Load/Store Pair Register
#define LSPPI_IMM7(imm7) (((imm7) & 0x7F) << 15)
#define LSPPI_Rt2(Rt2) (((Rt2) & 0x1F) << 10)
#define LSPPI_Rn(Rn) (((Rn) & 0x1F) << 5)
#define LSPPI_Rt(Rt) (((Rt) & 0x1F))
// sf = 64-bit if 1, 32-bit otherwise
// op = sub if 1, add otherwise
// S = set flags if 1
#define SF_OP_S(sf, op, S) ((((sf) & 1) << 31) | (((op) & 1) << 30) | (((S) & 1) << 29))
#define Rn(reg) (reg << 5)
#define Rd(reg) (reg)
// ADD/S, SUB/S support an optional shift of imm12 in bit 22
static
void sub_imm12_from_reg64(Data_Buffer *dataptr, u8 dst, u8 src, u16 imm12, u8 size = 8, bool set_flags = false) {
// imm12 is zext'd to 'datasize' (8 or 4 bytes)
assert(imm12 & 0x0FFF);
dataptr->append<u32>(OP0_DATA_IMM | DATA_IMM_ADD_SUB | SF_OP_S(size == 8 ? 1 : 0, 1, set_flags ? 1 : 0) | Rd(dst) | Rn(src) | (imm12 << 10));
}
static
void add_imm12_to_reg64(Data_Buffer *dataptr, u8 dst, u8 src, u16 imm12, u8 size = 8, bool set_flags = false) {
// imm12 is zext'd to 'datasize' (8 or 4 bytes)
assert((imm12 & ~0x0FFF) == 0);
dataptr->append<u32>(OP0_DATA_IMM | DATA_IMM_ADD_SUB | SF_OP_S(size == 8 ? 1 : 0, 0, set_flags ? 1 : 0) | Rd(dst) | Rn(src) | (imm12 << 10));
}
static
void debugbreak(Data_Buffer *dataptr) {
// TODO I am not really sure if the immediate in the brk instruction is the same for all software breakpoints on
// all ARM64 operating systems. #0xF000 is what is generated by Clang on macOS
dataptr->append<u32>(EXCEPTION_CLASS | EXCEPTION_OPC(0b001) | EXCEPTION_IMM16(0xF000));
}
static
void ret(Data_Buffer *dataptr, Integer_Register Rn = GP_R30) {
dataptr->append<u32>(BRANCH_UNC_REG_CLASS | BRANCH_UNC_REG_OPC(0b0010) | BRANCH_UNC_REG_OP2(0b11111) | BRANCH_UNC_REG_Rn(Rn));
}
// PC-relative address calculation
// Immediate is a +/- 1MB offset from PC
static
void adr(Data_Buffer *dataptr, s32 immediate, u8 Rd) {
assert(fits_into_bits(immediate, 21));
dataptr->append<u32>(OP0_DATA_IMM | DATA_IMM_SUBOP0(0b000) | DATA_IMM_ADR_IMMHI(immediate) | DATA_IMM_ADR_IMMLO(immediate) | DATA_IMM_ADR_Rd(Rd));
}
// PC-relative address calculation
// Immediate is a +/- 4GB offset from PC
// Calculated by PC += sext(immediate21) * 4096 /* page size */
static
void adrp(Data_Buffer *dataptr, s32 immediate, u8 Rd) {
assert(fits_into_bits(immediate, 21));
dataptr->append<u32>(DATA_IMM_ADRP | OP0_DATA_IMM | DATA_IMM_SUBOP0(0b000) | DATA_IMM_ADR_IMMHI(immediate) | DATA_IMM_ADR_IMMLO(immediate) | DATA_IMM_ADR_Rd(Rd));
}
static
void b(Data_Buffer *dataptr, s32 imm26) {
assert(fits_into_bits(imm26, 26));
dataptr->append<u32>(OP0_BRANCH | BRANCH_UNC_IMM_IMM26(imm26));
}
static
void bl(Data_Buffer *dataptr, s32 imm26) {
assert(fits_into_bits(imm26, 26));
dataptr->append<u32>(OP0_BRANCH | BRANCH_UNC_IMM_BL | BRANCH_UNC_IMM_IMM26(imm26));
}
static
void br(Data_Buffer *dataptr, u8 Rn) {
dataptr->append<u32>(BRANCH_UNC_REG_CLASS | BRANCH_UNC_REG_OPC(0b0000) | BRANCH_UNC_REG_OP2(0b11111) | BRANCH_UNC_REG_Rn(Rn));
}
static
void blr(Data_Buffer *dataptr, u8 Rn) {
dataptr->append<u32>(BRANCH_UNC_REG_CLASS | BRANCH_UNC_REG_OPC(0b0001) | BRANCH_UNC_REG_OP2(0b11111) | BRANCH_UNC_REG_Rn(Rn));
}
static
void _load_store_pair_impl(Data_Buffer *dataptr, u8 Rt, u8 Rt2, u8 Rn, s32 imm7, bool load, bool post_index) {
assert((imm7 & 0x7) == 0); // must be a multiple of 8
imm7 >>= 3;
assert(fits_into_bits(imm7, 7));
const u32 V = (1 << 26); // V bit turns this into a floating-point/SIMD variant
const u32 L = (1 << 22); // L bit = load if 1, store otherwise
// TODO there's also a 'signed offset' variant that is denoted by op2 = 0b10
// I am not really sure what the difference is but using the signed offset variant
// in place of pre-index seems to crash basic programs on return :/
// There's three addressing modes available:
// signed offset (0b10): calculates address by adding together Rn and imm7
// pre-index (0b11): calculates address by adding together Rn and imm7, then stores the new address in Rn
// post-index (0b11): calculates address as the value currently in Rn, then adds Rn and imm7 together and stores the new address in Rn
// The latter two effectively let you implement a 2-register push-pop using pre-index stp followed up by a post-index ldp.
u32 op2 = LOAD_STORE_OP2(0b11);
if (post_index)
op2 = LOAD_STORE_OP2(0b01);
dataptr->append<u32>(OP0_LOAD_STORE | (load ? L : 0) | LOAD_STORE_OP0(0b1010) | op2 | LSPPI_Rt(Rt) | LSPPI_Rt2(Rt2) | LSPPI_Rn(Rn) | LSPPI_IMM7(imm7));
}
static
void stp(Data_Buffer *dataptr, u8 Rt, u8 Rt2, u8 Rn, s32 imm7, bool post_index = false) {
_load_store_pair_impl(dataptr, Rt, Rt2, Rn, imm7, false, post_index);
}
static
void ldp(Data_Buffer *dataptr, u8 Rt, u8 Rt2, u8 Rn, s32 imm7, bool post_index = false) {
_load_store_pair_impl(dataptr, Rt, Rt2, Rn, imm7, true, post_index);
}
static
Register *get_free_register(AArch64_Emitter *emitter) {
for (auto ® : emitter->register_usage) {
if (reg.is_free) {
reg.is_free = false;
return ®
}
}
return nullptr;
}
/*
Register *get_free_xmm_register(AArch64_Emitter *emitter) {
for (auto ® : emitter->xmm_usage) {
if (reg.is_free) {
reg.is_free = false;
return ®
}
}
return nullptr;
}
*/
void maybe_spill_register(AArch64_Emitter *emitter, Register *reg) {
if (reg->currently_holding_result_of_instruction) {
auto inst = reg->currently_holding_result_of_instruction;
inst->result_stored_in = nullptr;
if (inst->result_spilled_onto_stack == 0 && inst->uses) {
emitter->stack_size += 8; // @TargetInfo
inst->result_spilled_onto_stack = -emitter->stack_size;
// TODO
// move_register_value_to_memory(&emitter->function_buffer, reg->machine_reg, addr_register_disp(RBP, inst->result_spilled_onto_stack), inst->value_type);
}
reg->currently_holding_result_of_instruction = nullptr;
}
reg->is_free = true;
}
Register *claim_register(AArch64_Emitter *emitter, Register *reg, Value *claimer) {
maybe_spill_register(emitter, reg);
if (claimer) {
reg->currently_holding_result_of_instruction = claimer;
claimer->result_stored_in = reg;
}
reg->is_free = false;
reg->used = true;
return reg;
}
static
void free_register(Register *reg) {
reg->currently_holding_result_of_instruction = nullptr;
reg->is_free = true;
}
Register *get_free_or_suggested_register(AArch64_Emitter *emitter, u8 suggested_register, bool force_use_suggested, Value *inst) {
Register *reg = nullptr;
if (!force_use_suggested) {
reg = get_free_register(emitter);
if (!reg) {
u32 uses = U32_MAX;
Register *regi;
for (auto ® : emitter->register_usage) {
if (reg.machine_reg == SP) continue;
if (reg.currently_holding_result_of_instruction) {
auto inst = reg.currently_holding_result_of_instruction;
if (inst->uses < uses) {
uses = inst->uses;
regi = ®
}
}
}
reg = regi;
}
}
if (!reg) reg = &emitter->register_usage[suggested_register];
maybe_spill_register(emitter, reg);
if (inst) return claim_register(emitter, reg, inst);
return reg;
}
/*
u8 load_instruction_result(AArch64_Emitter *emitter, Value *inst, u8 suggested_register, bool force_use_suggested) {
if (auto reg = inst->result_stored_in) {
assert(reg->currently_holding_result_of_instruction == inst);
return reg->machine_reg;
} else {
assert(!inst->result_stored_in);
reg = get_free_or_suggested_register(emitter, suggested_register, force_use_suggested, inst);
assert(inst->result_spilled_onto_stack != 0);
move_memory_value_to_register(&emitter->function_buffer, reg->machine_reg, addr_register_disp(RBP, inst->result_spilled_onto_stack), inst->value_type);
return reg->machine_reg;
}
}
*/
static
void load_symbol_address(AArch64_Emitter *emitter, Section *code_section, u32 symbol_index, u32 offset, u8 machine_reg) {
adrp(&emitter->function_buffer, 0, machine_reg);
{
Relocation reloc;
reloc.type = Relocation::RIP_DATA;
reloc.offset = emitter->function_buffer.size() - 4;
reloc.symbol_index = symbol_index;
reloc.size = 4;
code_section->relocations.push_back(reloc);
}
// TODO since we only have 12 bits to work with, we can only address 1
// page into the data section. We can remedy this by introducing another
// add with the shift bit set, which shifts up the imm12 by 12 bits, allowing
// us to address offets up to 0x1000000 (16MB). The long term solution is likely
// to create temporary symbols for most items in the data section :/
// ... or maybe we can add an addend to the adrp relocation ? which would
// give us +- 4GB
add_imm12_to_reg64(&emitter->function_buffer, machine_reg, machine_reg, 0);
{
Relocation reloc;
reloc.type = Relocation::PAGEOFFSET;
reloc.offset = emitter->function_buffer.size() - 4;
reloc.symbol_index = symbol_index;
reloc.size = 4;
reloc.addend = offset;
code_section->relocations.push_back(reloc);
}
}
u8 emit_load_of_value(AArch64_Emitter *emitter, Linker_Object *object, Section *code_section, Value *value, u8 suggested_register = GP_R0, bool force_use_suggested = false) {
if (value->type == VALUE_CONSTANT) {
auto constant = static_cast<Constant *>(value);
Register *reg = get_free_or_suggested_register(emitter, suggested_register, force_use_suggested, nullptr);
reg->is_free = false;
Section *data_section = emitter->data_section;
if (constant->constant_type == Constant::STRING) {
u32 data_sec_offset = data_section->data.size();
// copy the string characters into the data section
assert(constant->string_value.length() <= U32_MAX);
// TODO can we avoid a string copy by copying the string table into the data section later on and then fixing up all the offsets ?
if (auto str_id = emitter->string_table.intern(constant->string_value)) {
auto &entry = emitter->string_table.lookup(str_id);
if (entry.data_sec_offset == U32_MAX) { // New entry
size_t length = static_cast<u32>(constant->string_value.length());
void *data_target = data_section->data.allocate_bytes_unaligned(length);
memcpy(data_target, constant->string_value.data(), length);
data_section->data.append_byte(0);
entry.data_sec_offset = data_sec_offset;
} else {
data_sec_offset = entry.data_sec_offset;
}
} else {
// Empty string, assume at data section offset 0.
data_sec_offset = 0;
}
load_symbol_address(emitter, code_section, data_section->symbol_index, data_sec_offset, reg->machine_reg);
} else if (constant->constant_type == Constant::INTEGER) {
// move_imm_to_reg_or_clear(&emitter->function_buffer, constant->integer_value, reg->machine_reg);
} else if (constant->constant_type == Constant::FLOAT) {
/*
Register *xmm = get_free_xmm_register(emitter);
if (!xmm) {
xmm = claim_register(emitter, &emitter->xmm_usage[XMM0], value);
} else {
xmm = claim_register(emitter, xmm, value);
}
// copy the float bytes into the data section
if (constant->value_type->size == 8) {
double *data_target = data_section->data.allocate<double>();
*data_target = constant->float_value;
} else if (constant->value_type->size == 4) {
float *data_target = data_section->data.allocate<float>();
*data_target = (float)constant->float_value;
} else {
assert(false);
}
u32 data_sec_offset = data_section->data.size() - constant->value_type->size;
assert(data_sec_offset >= 0);
if (object->use_absolute_addressing) {
move_imm64_to_reg64(&emitter->function_buffer, data_sec_offset, reg->machine_reg, 8);
Relocation reloc;
reloc.is_for_rip_call = false;
reloc.offset = emitter->function_buffer.size() - 8;
reloc.symbol_index = data_section->symbol_index;
reloc.size = 8;
reloc.addend = static_cast<u64>(data_sec_offset);
code_section->relocations.push_back(reloc);
move_memory_to_xmm(&emitter->function_buffer, xmm->machine_reg, addr_register_disp(reg->machine_reg), constant->value_type->size);
} else {
s32 *value = move_memory_to_xmm(&emitter->function_buffer, xmm->machine_reg, addr_register_disp(RBP), constant->value_type->size);
*value = static_cast<s32>(data_sec_offset);
Relocation reloc;
reloc.is_for_rip_call = false;
reloc.is_rip_relative = true;
reloc.offset = emitter->function_buffer.size() - 4;
reloc.symbol_index = data_section->symbol_index;
reloc.size = 4;
code_section->relocations.push_back(reloc);
}
free_register(reg);
return xmm->machine_reg;
*/
}
return reg->machine_reg;
} /*else if (value->type == VALUE_BASIC_BLOCK) {
Basic_Block *block = static_cast<Basic_Block *>(value);
Register *reg = get_free_or_suggested_register(emitter, suggested_register, force_use_suggested, nullptr);
reg->is_free = false;
s32 *value = lea_rip_relative_into_reg64(&emitter->function_buffer, reg->machine_reg);
auto offset = emitter->function_buffer.size() - 4;
block->text_locations_needing_addr_fixup.push_back(offset);
block->text_ptrs_for_fixup.push_back((u32 *)value);
return reg->machine_reg;
} else if (value->type == INSTRUCTION_ALLOCA) {
auto _alloca = static_cast<Instruction_Alloca *>(value);
if (_alloca->result_stored_in) return _alloca->result_stored_in->machine_reg;
if (_alloca->result_spilled_onto_stack != 0) return load_instruction_result(emitter, _alloca, suggested_register, force_use_suggested);
Register *reg = get_free_or_suggested_register(emitter, suggested_register, force_use_suggested, _alloca);
assert(_alloca->stack_offset != 0);
lea_into_reg64(&emitter->function_buffer, reg->machine_reg, addr_register_disp(RBP, _alloca->stack_offset));
return reg->machine_reg;
} else if (value->type == VALUE_ARGUMENT) {
auto arg = static_cast<Argument *>(value);
if (arg->copied_to_stack_offset) {
Address_Info info = addr_register_disp(RBP, arg->copied_to_stack_offset);
Register *reg = get_free_or_suggested_register(emitter, suggested_register, force_use_suggested, nullptr);
lea_into_reg64(&emitter->function_buffer, reg->machine_reg, info);
return reg->machine_reg;
}
return load_instruction_result(emitter, value, suggested_register, force_use_suggested);
} else if (value->type >= INSTRUCTION_FIRST && value->type <= INSTRUCTION_LAST) {
auto inst = static_cast<Instruction *>(value);
return load_instruction_result(emitter, inst, suggested_register, force_use_suggested);
}
assert(false);
*/
return 0;
}
/*
u8 maybe_get_instruction_register(Value *value) {
if (Instruction *inst = is_instruction(value)) {
if (inst->result_stored_in) return inst->result_stored_in->machine_reg;
}
return 0xFF;
}
*/
/*
Address_Info get_address_value_of_pointer(AArch64_Emitter *emitter, Linker_Object *object, Section *code_section, Value *value, u8 suggested_register = RAX) {
assert(value->value_type->type == Type::POINTER);
if (value->type == INSTRUCTION_ALLOCA) {
auto _alloca = static_cast<Instruction_Alloca *>(value);
return addr_register_disp(RBP, _alloca->stack_offset);
}
else if (value->type == VALUE_ARGUMENT) {
auto arg = static_cast<Argument *>(value);
if (arg->copied_to_stack_offset)
return addr_register_disp(RBP, arg->copied_to_stack_offset);
}
// We could theoretically do this and save some instructions
// but this ends up generating a large amount of bytes
// due to having to write the displacement bytes. I don't yet know
// if code in that form is faster due to fewer instructions or due
// to smaller code size. Note also that that emit_load_of_value of
// gep->index could also generate additional instructions...
#if 0
else if (value->type == INSTRUCTION_GEP) {
Instruction_GEP *gep = static_cast<Instruction_GEP *>(value);
u32 size = gep->pointer_value->value_type->pointer_to->size;
if (size > 8) {
// we cant claim ownership of the index register so the result of this calculation
// would be nontrivial, just get the stored instruction result
u8 machine_reg = emit_load_of_value(emitter, object, code_section, value, suggested_register);
return addr_register_disp(machine_reg);
}
u8 target = maybe_get_instruction_register(gep->index);
Address_Info source = get_address_value_of_pointer(emitter, object, code_section, gep->pointer_value, (target == RAX) ? RCX : RAX);
// gep->pointer_value->uses--;
if (target == 0xFF) target = emit_load_of_value(emitter, object, code_section, gep->index, (source.machine_reg == RAX) ? RCX : RAX);
// gep->index->uses--;
assert(source.machine_reg != target);
Address_Info info;
info.machine_reg = RSP; // SIB
info.disp = source.disp;
info.base_reg = source.machine_reg;
info.index_reg = target;
info.scale = (u8) size;
return info;
}
#endif
{
u8 machine_reg = emit_load_of_value(emitter, object, code_section, value, suggested_register);
return addr_register_disp(machine_reg);
}
}
*/
static
u8 emit_instruction(AArch64_Emitter *emitter, Linker_Object *object, Function *function, Basic_Block *current_block, Section *code_section, Instruction *inst) {
switch (inst->type) {
case INSTRUCTION_ALLOCA: {
auto _alloca = static_cast<Instruction_Alloca *>(inst);
// Register *reg = get_free_or_suggested_register(emitter, RAX, false, inst);
assert(_alloca->stack_offset != 0);
// lea_into_reg64(&emitter->function_buffer, reg->machine_reg, addr_register_disp(RBP, -_alloca->stack_offset));
return 0;
}
case INSTRUCTION_STORE: {
auto store = static_cast<Instruction_Store *>(inst);
// TODO
store->store_target->uses--;
store->source_value->uses--;
break;
}
case INSTRUCTION_LOAD: {
auto load = static_cast<Instruction_Load *>(inst);
// TODO
load->pointer_value->uses--;
return 0;
}
case INSTRUCTION_GEP: {
Instruction_GEP *gep = static_cast<Instruction_GEP *>(inst);
gep->pointer_value->uses--;
gep->index->uses--;
return 0;
}
case INSTRUCTION_DIV: {
auto div = static_cast<Instruction_Div *>(inst);
// TODO
div->lhs->uses--;
div->rhs->uses--;
return 0;
}
case INSTRUCTION_ADD:
case INSTRUCTION_SUB:
case INSTRUCTION_MUL: {
auto add = static_cast<Instruction_Add *>(inst);
// TODO
add->lhs->uses--;
add->rhs->uses--;
return 0;
}
case INSTRUCTION_CALL: {
auto call = static_cast<Instruction_Call *>(inst);
auto function_target = static_cast<Function *>(call->call_target);
auto func_type = static_cast<Function_Type *>(function_target->value_type);
assert(func_type->type == Type::FUNCTION);
if (function_target->intrinsic_id) {
switch (function_target->intrinsic_id) {
case Function::NOT_INTRINSIC:
assert(false);
break;
case Function::DEBUG_BREAK:
debugbreak(&emitter->function_buffer);
break;
}
return 0;
}
// TODO necessary on arm64?
if (object->target.is_win32()) {
// shadow space for the callee to spill registers...
emitter->largest_call_stack_adjustment += 32;
}
u8 integer_param_index = 0;
assert(call->parameters.size() <= emitter->parameter_registers.size()); // @Incomplete
for (u32 i = 0; i < call->parameters.size(); ++i) {
auto p = call->parameters[i];
u8 param_reg = emitter->parameter_registers[integer_param_index];
u8 int_param_reg = param_reg;
integer_param_index += 1;
u8 result = emit_load_of_value(emitter, object, code_section, p, int_param_reg, true);
p->uses--;
}
bool has_internal_definition = function_target->blocks.size() != 0;
if (object->use_absolute_addressing) {
const u8 INDIRECT_CALL_REG = GP_R9;
maybe_spill_register(emitter, &emitter->register_usage[INDIRECT_CALL_REG]);
load_symbol_address(emitter, code_section, get_symbol_index(object, function_target), 0, INDIRECT_CALL_REG);
blr(&emitter->function_buffer, INDIRECT_CALL_REG);
} else {
bl(&emitter->function_buffer, 0);
/*
emitter->function_buffer.append_byte(0xE8); // callq rip-relative
// emitter->function_buffer.append_byte(ModRM(0b00, 0b000, 0b101));
s32 *addr = emitter->function_buffer.allocate_unaligned<s32>();
*addr = 0;
if (has_internal_definition) {
emitter->rip_call_fixup_targets.emplace_back(emitter->function_buffer.size() - 4, function_target);
} else {
*/
Relocation reloc;
reloc.type = Relocation::RIP_CALL;
reloc.offset = emitter->function_buffer.size() - 4;
reloc.symbol_index = get_symbol_index(object, function_target);
reloc.size = 4;
reloc.addend = 0; // @TODO
code_section->relocations.push_back(reloc);
// }
}
return 0;
}
case INSTRUCTION_RETURN: {
Instruction_Return *ret = static_cast<Instruction_Return *>(inst);
/*
if (ret->return_value) {
u8 lhs_reg = maybe_get_instruction_register(ret->return_value);
if (lhs_reg == 0xFF) lhs_reg = emit_load_of_value(emitter, object, code_section, ret->return_value, RAX, true);
ret->return_value->uses--;
if (lhs_reg != RAX) move_reg64_to_reg64(&emitter->function_buffer, lhs_reg, RAX);
}
if (!emitter->emitting_last_block) { // otherwise fallthrough to epilogue
emitter->function_buffer.append_byte(0xE9);
auto offset = emitter->function_buffer.size();
emitter->epilogue_jump_target_fixups.push_back(offset);
s32 *value = emitter->function_buffer.allocate_unaligned<s32>();
emitter->epilogue_jump_target_fixup_pointers.push_back(value);
}
*/
break;
}
case INSTRUCTION_BRANCH: {
Instruction_Branch *branch = static_cast<Instruction_Branch *>(inst);
/*
// Spill all scratch registers at branches in case that we branch
// to much earlier code that expects all registers to be free.
// This may not totally be correct, but works for now. -josh 7 August 2020
for (auto ® : emitter->register_usage) {
if (reg.machine_reg == RSP || reg.machine_reg == RBP) continue;
maybe_spill_register(emitter, ®);
}
if (branch->condition) {
u8 cond = emit_load_of_value(emitter, object, code_section, branch->condition);
sub_imm32_from_reg64(&emitter->function_buffer, cond, 0, branch->condition->value_type->size);
maybe_spill_register(emitter, &emitter->register_usage[RAX]);
emitter->function_buffer.append_byte(0x0F);
emitter->function_buffer.append_byte(0x85); // jne if cond if true goto true block
u32 *jne_disp = emitter->function_buffer.allocate_unaligned<u32>();
auto failure_target = branch->failure_target;
if (failure_target->type == VALUE_BASIC_BLOCK) {
*jne_disp = 5; // skip the next jmp instruction
Basic_Block *block = static_cast<Basic_Block *>(failure_target);
emitter->function_buffer.append_byte(0xE9);
// @Cutnpaste from emit_load_of_value
auto offset = emitter->function_buffer.size();
block->text_locations_needing_addr_fixup.push_back(offset);
u32 *value = emitter->function_buffer.allocate_unaligned<u32>();
block->text_ptrs_for_fixup.push_back(value);
} else {
*jne_disp = 2; // skip the next jmp instruction
u8 fail_target = emit_load_of_value(emitter, object, code_section, branch->failure_target);
if (BIT3(fail_target)) {
*jne_disp += 1;
emitter->function_buffer.append_byte(REX(1, 0, 0, BIT3(fail_target)));
}
emitter->function_buffer.append_byte(0xFF); // jmp reg
emitter->function_buffer.append_byte(ModRM(0b11, 4, LOW3(fail_target)));
}
}
Basic_Block *next_block = nullptr;
// FIXME blocks should just know their insertion position
// TODO maybe reoder blocks to optimize this
for (u64 i = 0; i < function->blocks.size()-1; ++i) {
if (function->blocks[i] == current_block) {
next_block = function->blocks[i+1];
break;
}
}
if (branch->true_target != next_block) {
auto true_target = branch->true_target;
if (true_target->type == VALUE_BASIC_BLOCK) {
Basic_Block *block = static_cast<Basic_Block *>(true_target);
emitter->function_buffer.append_byte(0xE9);
// @Cutnpaste from emit_load_of_value
auto offset = emitter->function_buffer.size();
block->text_locations_needing_addr_fixup.push_back(offset);
u32 *value = emitter->function_buffer.allocate_unaligned<u32>();
block->text_ptrs_for_fixup.push_back(value);
} else {
u8 target = emit_load_of_value(emitter, object, code_section, branch->true_target);
if (BIT3(target))
emitter->function_buffer.append_byte(REX(1, 0, 0, BIT3(target)));
emitter->function_buffer.append_byte(0xFF); // jmp reg
emitter->function_buffer.append_byte(ModRM(0b11, 4, LOW3(target)));
}
}
*/
branch->true_target->uses--;
if (branch->condition) branch->condition->uses--;
if (branch->failure_target) branch->failure_target->uses--;
break;
}
default: assert(false);
}
return 0;
}
static
Register make_reg(u8 machine_reg, bool is_free = true) {
Register reg = {};
reg.machine_reg = machine_reg;
reg.is_free = is_free;
return reg;
}
/*
static
bool is_callee_saved(const Target &target, u8 reg) {
if (target.is_win32())
return (reg >= RBX && reg <= RDI) || (reg >= R12 && reg <= R15);
else
return reg == RBX || reg == RSP || reg == RBP || (reg >= R12 && reg <= R15);
}
*/
namespace josh {
void AArch64_emit_function(AArch64_Emitter *emitter, Linker_Object *object, Function *function) {
if (function->intrinsic_id) return;
if (function->uses == 0 && (function->blocks.size() == 0)) {
// Function isn't used and is externally defined so we don't need
// to emit anything, or even add this to the symbol table.
return;
}
Section *code_section = emitter->code_section;
emitter->function_buffer.clear();
emitter->register_usage.clear();
emitter->xmm_usage.clear();
emitter->parameter_registers.clear();
emitter->stack_size = 0;
emitter->largest_call_stack_adjustment = 0;
emitter->emitting_last_block = false;
bool is_externally_defined = (function->blocks.size() == 0);
if (is_externally_defined)
assert(function->linkage == Function::Linkage::EXTERNAL);
if (function->linkage == Function::Linkage::EXTERNAL) {
u32 symbol_index = get_symbol_index(object, function);
Symbol *sym = &object->symbol_table[symbol_index];
sym->is_function = true;
sym->is_externally_defined = is_externally_defined;
if (!sym->is_externally_defined) {
sym->section_number = code_section->section_number;
sym->section_offset = emitter->code_section->data.size();
}
}
if (is_externally_defined) return;
emitter->function_text_locations[function] = emitter->code_section->data.size();
for (u8 i = 0; i < GP_MAX; ++i)
emitter->register_usage.push_back(make_reg(GP_R0 + i));
emitter->register_usage.push_back(make_reg(SP, false));
for (u8 i = 0; i <= GP_R7; ++i)
emitter->parameter_registers.push_back(i);
// TODO floating point registers
size_t relocations_start = code_section->relocations.size();
size_t rip_fixups_start = emitter->rip_call_fixup_targets.size();
size_t abs_fixups_start = emitter->absolute_call_fixup_targets.size();
/*
u32 reg_index = 0;
for (u32 i = 0; i < function->arguments.size(); ++i) {
Argument *arg = function->arguments[i];
// TODO this is just a hacky way of handling small structs on System V, it is not totally correct
if (auto str = arg->value_type->as<Struct_Type>(); str && str->size <= 16 && object->target.is_system_v()) {
emitter->stack_size += str->size;
Address_Info info = addr_register_disp(RBP, -emitter->stack_size);
move_reg_to_memory(&emitter->function_buffer, emitter->parameter_registers[reg_index], info, str->size > 8 ? 8 : str->size);
reg_index += 1;
if (str->size > 8) {
info.disp += 8;
move_reg_to_memory(&emitter->function_buffer, emitter->parameter_registers[reg_index], info, str->size - 8);
reg_index += 1;
}
arg->copied_to_stack_offset = -emitter->stack_size;
continue;
}
claim_register(emitter, &emitter->register_usage[emitter->parameter_registers[reg_index]], arg);
reg_index += 1;
}
*/
for (auto block : function->blocks) {
for (auto inst : block->instructions) {
if (inst->type == INSTRUCTION_ALLOCA) {
auto _alloca = static_cast<Instruction_Alloca *>(inst);
emitter->stack_size += (_alloca->alloca_type->size * _alloca->array_size);
if ((emitter->stack_size % 8)) emitter->stack_size += 8 - (emitter->stack_size % 8);
_alloca->stack_offset = -emitter->stack_size;
}
}
}
for (size_t i = 0; i < function->blocks.size(); ++i) {
auto block = function->blocks[i];
assert(block->has_terminator());
block->text_location = emitter->function_buffer.size();
emitter->emitting_last_block = (i == function->blocks.size()-1);
for (auto inst : block->instructions) {
emit_instruction(emitter, object, function, block, code_section, inst);
}
}
// block text locations need to be offset by the end of the function prologue
// relocation offsets need to be offset by end of the function prologue
stp(&emitter->code_section->data, GP_R29, GP_R30, SP, -16);
add_imm12_to_reg64(&emitter->code_section->data, GP_R29, SP, 0);
emitter->stack_size += emitter->largest_call_stack_adjustment;
// Ensure stack is 16-byte aligned.
emitter->stack_size = ensure_aligned(emitter->stack_size, 16);
assert((emitter->stack_size & (0xF)) == 0);
/*
size_t num_push_pops = 0;
bool pushed_rbp = false;
if (emitter->stack_size != 0) {
push(&emitter->code_section->data, RBP);
num_push_pops += 1;
pushed_rbp = true;
}
for (size_t i = 0; i < emitter->register_usage.size(); ++i) {
auto reg = &emitter->register_usage[i];
if (reg->used && is_callee_saved(object->target, reg->machine_reg)) {
push(&emitter->code_section->data, reg->machine_reg);
num_push_pops += 1;
}
}
bool offset_push = false;
if (num_push_pops % 2 == 0) {
if (emitter->stack_size)
emitter->stack_size += 8;
else {
offset_push = true;
push(&emitter->code_section->data, RAX); // push a reg so we align stack properly without needing RBP pushed and RSP modified
}
}
*/
if (emitter->stack_size != 0)
sub_imm12_from_reg64(&emitter->code_section->data, SP, SP, emitter->stack_size);
/*
// Touch stack pages from top to bottom
// to release stack pages from the page guard system.
// TODO we can probably simplify this by removing the loop
// and emitting one mov instruction per stack page now that
// we know the stack size post-function-body-generation
// TODO do we need this for windows on arm ?
if (object->target.is_win32()) {
s32 *move_stack_size_to_rax = (s32 *)move_imm64_to_reg64(&emitter->code_section->data, emitter->stack_size, RAX, 4); // 4-byte immediate
auto loop_start = emitter->code_section->data.size();
sub_imm32_from_reg64(&emitter->code_section->data, RAX, 4096, 8);
// @Cutnpaste from move_reg_to_memory
auto dataptr = &emitter->code_section->data;
dataptr->append_byte(REX(1, BIT3(RAX), 0, BIT3(RSP)));
dataptr->append_byte(0x89);
dataptr->append_byte(ModRM(MOD_INDIRECT_NO_DISP, LOW3(RAX), LOW3(RSP)));
dataptr->append_byte(SIB(0, RAX, RSP));
emitter->code_section->data.append_byte(0x0F);
emitter->code_section->data.append_byte(0x8C); // jl if RAX < 0 break
u32 *disp = emitter->code_section->data.allocate_unaligned<u32>();
*disp = 5; // skip the next jmp instruction
emitter->code_section->data.append_byte(0xE9); // jmp loop start
disp = emitter->code_section->data.allocate_unaligned<u32>();
*disp = (loop_start - emitter->code_section->data.size());
}
*/
size_t text_offset = emitter->code_section->data.size();
/*
for (auto block : function->blocks) {
for (u64 i = 0; i < block->text_locations_needing_addr_fixup.size(); ++i) {
u64 location = block->text_locations_needing_addr_fixup[i];
u32 *addr = block->text_ptrs_for_fixup[i];
*addr = static_cast<u32>((block->text_location - (location+4)));
}
}
*/
emitter->code_section->data.append(&emitter->function_buffer);
if (emitter->stack_size != 0)
add_imm12_to_reg64(&emitter->code_section->data, SP, SP, emitter->stack_size);
/*
size_t epilogue_start_offset = emitter->code_section->data.size();
for (size_t i = 0; i < emitter->epilogue_jump_target_fixups.size(); ++i) {
size_t location = text_offset + emitter->epilogue_jump_target_fixups[i];
s32 *addr = emitter->epilogue_jump_target_fixup_pointers[i];
*addr = static_cast<s32>(epilogue_start_offset - (location + 4));
}
if (offset_push) {
pop(&emitter->code_section->data, RCX); // pop the stack alignment value into a caller-saved register
}
// reverse order pop
for (size_t i = emitter->register_usage.size(); i > 0; --i) {
auto reg = &emitter->register_usage[i-1];
if (reg->used && is_callee_saved(object->target, reg->machine_reg))
pop(&emitter->code_section->data, reg->machine_reg);
}
if (pushed_rbp)
pop(&emitter->code_section->data, RBP);
*/
ldp(&emitter->code_section->data, GP_R29, GP_R30, SP, 16, /*post_index*/true);
ret(&emitter->code_section->data);
for (size_t i = relocations_start; i < code_section->relocations.size(); ++i) {
code_section->relocations[i].offset += text_offset;
}
for (size_t i = rip_fixups_start; i < emitter->rip_call_fixup_targets.size(); ++i) {
emitter->rip_call_fixup_targets[i].first += text_offset;
}
for (size_t i = abs_fixups_start; i < emitter->absolute_call_fixup_targets.size(); ++i) {
emitter->absolute_call_fixup_targets[i].first += text_offset;
}
}
} | [
"joshuahuelsman@gmail.com"
] | joshuahuelsman@gmail.com |
0a9a505004db2c589709bcefc264f3f655f77784 | 1f22b1bf55a3eb75d1a99fb05f3daefe8520f564 | /Source/States/KeyToString.hpp | 7942b3c5d4a82b57183a47ceaf98c7a27d59bd49 | [] | no_license | s4weng/At-War | f7cacb153d6aff028d849e6422a50027cc5f30eb | 2aab23b0d8f38b1ea8f161fb20b741115b90fd19 | refs/heads/master | 2021-01-01T19:38:47.073010 | 2015-07-04T02:16:14 | 2015-07-04T02:16:14 | 35,546,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 166 | hpp | #ifndef _KEYTOSTRING_HPP__
#define _KEYTOSTRING_HPP__
#include <SFML/Window/Keyboard.hpp>
#include <string>
std::string keyToString(sf::Keyboard::Key key);
#endif | [
"steve_weng@hotmail.ca"
] | steve_weng@hotmail.ca |
36fce381bd0b6fe636b826fda721addb4c28a94b | d87d77154b6d41e4d05c5ebfe0c47a2c342a59f4 | /BC-W4/Statistic/statistic/statistic/TextHandler.h | e3bd1a0f86c3af33121248b404601fbd9c41d5cd | [] | no_license | ivolchkov/DevClub-Bootcamp | 182f08202c44d34c0518705be376038f19d95629 | 4ba1cd20c1c741b4a4b5f1ee599499fe21784c73 | refs/heads/master | 2021-06-02T10:33:24.374133 | 2020-04-09T09:33:29 | 2020-04-09T09:33:29 | 254,324,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,796 | h | #ifndef TEXT_HANDLER_H
#define TEXT_HANDLER_H
#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include "templates.cpp"
class TextHandler {
private:
const char* filename;
std::set<char>* characters;
std::map<char, int>* charactersStatistics;
std::set<char>* numbers;
std::map<char, int>* numbersStatistics;
std::set<char>* specialSymbols;
std::map<char, int>* specialSymbolsStatistics;
std::set<std::string>* words;
std::map<std::string, int>* wordsStatistics;
long long quantity;
long long wordsQuantity;
void insert(char symbol, std::set<char>* lst);
void insert(char symbol, std::map<char, int>* lst);
void insert(std::string str, std::set<std::string>* lst);
void insert(std::string str, std::map<std::string, int>* lst);
bool isLetter(char symbol);
bool isNumber(char symbol);
bool isSpecial(char symbol);
bool isWord(char symbol);
public:
TextHandler(const char* filename);
~TextHandler();
const std::set<char>& getCharacters() const;
const std::map<char, int>& getCharactersStatistics() const;
const std::set<char>& getNumbers() const;
const std::map<char, int>& getNumbersStatistics() const;
const std::set<char>& getSpecialSymbols() const;
const std::map<char, int>& getSpecialSymbolsStatistics() const;
const std::set<std::string>& getWords() const;
const std::map<std::string, int>& getWordsStatistics() const;
long long getQuantity() const;
long long getWordsQuantity() const;
void parseText();
};
std::ostream& operator<<(std::ostream& out, const TextHandler& handler);
#endif //TEXT_HANDLER_H | [
"ihor.volchkov@gmail.com"
] | ihor.volchkov@gmail.com |
ee7e59f460e486eb09db448d787914a070ddcffd | dae85bfd82fbe94486c4bff6566e11876e75934c | /src/bank_trie.cpp | 2a76bc3c194909df0fbb9ded714cdc994874993c | [] | no_license | liu115/dsa15_final | 23fa835986e3879ed3e66df2324291789a410cc8 | 47fec854850da9a3a1a738c13cd154d9762151dc | refs/heads/master | 2021-01-10T18:25:27.829797 | 2015-07-01T03:57:39 | 2015-07-01T03:57:39 | 38,735,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,270 | cpp | // bank_trie.cpp
// Copyright 2015-06 dsa_final15
#include "bank_trie.h"
Account *BankTrie::getAccount(const string &id) {
Node *node = tree.find(tree.root, id, 0, id.length() - 1);
if (node == NULL || node->element == NULL) return NULL;
return node->element;
}
void BankTrie::addAccount(const string &id, Account *ac) {
string *newid = new string(id);
tree.insert(tree.root, *newid, 0, (*newid).length() - 1, ac);
}
void BankTrie::loginAccount(const string &id, const string &passwd) {
Account *ac = getAccount(id);
if (ac == NULL) {
cout << "ID " << id << " not found\n";
}
else {
if (ac->verifyPassword(passwd)) {
current_login_user = id;
cout << "success\n";
}
else {
cout << "wrong password\n";
}
}
}
void BankTrie::createAccount(const string& id, const string& passwd) {
Account *ac = getAccount(id);
if (ac == NULL) {
Account *new_ac = new Account(id, passwd);
addAccount(id, new_ac); //insert new element
cout << "success\n";
} else {
cout << "ID " << id << " exists, ";
RecommendId best10;
getRecommend(id, best10);
cout << best10[0];
for (int i = 1; i < 10; i++) cout << "," << best10[i];
cout << "\n";
// recommend 10 best account
}
}
void BankTrie::deleteAccount(const string& id, const string& passwd) {
Account *ac = getAccount(id);
if (ac == NULL) {
cout << "ID " << id << " not found\n";
} else {
if (ac->verifyPassword(passwd)) {
tree.remove(tree.root, id, 0, id.length() - 1); //remove element
cout << "success\n";
} else {
cout << "wrong password\n";
}
}
}
void BankTrie::mergeAccount(const string& id1, const string& passwd1, const string& id2, const string& passwd2) {
Account *ac1 = getAccount(id1);
Account *ac2 = getAccount(id2);
if (ac1 == NULL) {
cout << "ID " << id1 << " not found\n";
return;
}
if (ac2 == NULL) {
cout << "ID " << id2 << " not found\n";
return;
}
if (!ac1->verifyPassword(passwd1)) {
cout << "wrong password1\n";
return;
}
if (!ac2->verifyPassword(passwd2)) {
cout << "wrong password2\n";
return;
}
ac1->mergeAccount(*ac2);
tree.remove(tree.root, id2, 0, id2.length() - 1);
}
void BankTrie::accountDeposit(const int& money) {
Account *ac = getAccount(current_login_user);
ac->depositMoney(money);
}
void BankTrie::accountWithdraw(const int& money) {
Account *ac = getAccount(current_login_user);
ac->withdrawMoney(money);
}
void BankTrie::transfer(const string& id, const int& money) {
Account *ac2 = getAccount(id); //find
if (ac2 == NULL) {
cout << "ID " << id << " not found, ";
// recommend 10 best exist id
RecommendId rid;
existRecommend(id, rid);
if (rid.size() > 0)
cout << rid[0];
for (int i = 1; i < rid.size(); ++i)
cout << "," << rid[i];
cout << "\n";
} else {
Account *ac1 = getAccount(current_login_user);
ac1->transferOut(*ac2, money, lg);
}
}
void BankTrie::findAccount(const string& reg_exp) {
RegString rs;
regexFind(reg_exp, rs);
if (rs.size() > 0) {
sort(rs.begin(), rs.end());
cout << rs[0];
for (int i = 1; i < rs.size(); i++) {
cout << "," << rs[i];
}
}
cout << "\n";
}
void BankTrie::searchHistory(const string& id) {
Account *ac = getAccount(current_login_user);
ac->searchHistory(id);
}
//following is for recommending accounts
int BankTrie::max_num(const int a, const int b) { return (a < b)?b:a;}
int BankTrie::min_num(const int a, const int b) { return (a < b)?a:b;}
int BankTrie::abs_num(const int a) { return (a < 0)?-a:a;}
char BankTrie::next_char(const char c) {
char next_c = c + 1;
if (next_c == 123) // if next_c is exceeding z
next_c = 48;
else if (next_c == 91) // if next_c is exceeding Z
next_c = 97;
else if (next_c == 58) // if next_c is exceeding 9
next_c = 65;
return next_c;
}
char BankTrie::prev_char(const char c) {
char next_c = c - 1;
if (next_c == 47) // if next_c is exceeding 0
next_c = 122;
else if (next_c == 96) // if next_c is exceeding z
next_c = 90;
else if (next_c == 64) // if next_c is exceeding 9
next_c = 57;
return next_c;
}
int BankTrie::computeScoring(const string& str1, const string& str2) {
int score = 0, min_len = min_num(str1.length(), str2.length());
for (int i = 0; i < min_len; i++) {
if(str1[i] != str2[i]) score += (min_len - i);
}
int delta = abs_num((int)(str1.length() - str2.length()));
score += delta * (delta + 1) / 2;
return score;
}
void BankTrie::getRecommend(const string& oid, RecommendId& rid) {
rid.clear();
int degree = 1, new_size = 0;
while (rid.size() < RECOMMEND_SIZE) {
for (int i = 0; i <= degree; i++) {
runRecommend(oid, oid, 0, rid, i, degree - i);
}
sort(rid.begin() + new_size, rid.end());
new_size = rid.size();
if (rid.size() >= RECOMMEND_SIZE) break;
degree++;
}
}
void BankTrie::runRecommend(string id, string oid, int len, RecommendId& rid, int degree_c, int degree_a) {
if (degree_c == 0 && degree_a == 0) {
Account *ac = getAccount(id);
if (ac == NULL) {
// it means that the id isn't exist in the bank
rid.push_back(id);
return;
}
}
string tmpid;
int delta = abs_num((int)oid.length() - (int)id.length());
if (degree_a > delta) {
if (id.length() >= oid.length() && id.length() < MAX_STRING_SIZE) {
for (char c = '0'; ; c = next_char(c)) {
runRecommend(id + c, oid, id.length() + 1, rid, degree_c, degree_a - delta - 1);
if (c == 'z') break;
}
}
if (id.length() <= oid.length() && id.length() > len && id.length() > 1) {
tmpid = id;
tmpid.pop_back();
runRecommend(tmpid, oid, len, rid, degree_c, degree_a - delta - 1);
}
}
if (degree_c > 0) {
for (int i = max_num(min_num(id.length(), oid.length()) - degree_c, len); i < min_num(oid.length(), id.length()); i++) {
if (degree_c >= min_num(oid.length(), id.length()) - i) {
for (char c = '0'; c <= 'z'; c = next_char(c)) {
if (c != oid[i]) {
tmpid = id;
tmpid[i] = c;
runRecommend(tmpid, oid, i + 1, rid, degree_c - (min_num(oid.length(), id.length()) - i), degree_a);
}
if (c == 'z') break;
}
}
}
}
}
void BankTrie::existRecommend(const string& oid, RecommendId& id_container) {
id_container.clear();
id_container.reserve(10);
vector< pair<int, string> > score_id;
score_id.reserve(tree.getSize() + 1);
int score;
string id;
computeAllScore(tree.root, score_id, oid);
int i = 0, j, selected_index;
while (i < 10 && i < score_id.size()) {
score = score_id[i].first;
id = score_id[i].second;
selected_index = i;
for (j = i; j < score_id.size(); ++j) {
if (score_id[j].first < score) {
score = score_id[j].first;
id = score_id[j].second;
selected_index = j;
} else if (score_id[j].first == score && id.compare(score_id[j].second) > 0) {
score = score_id[j].first;
id = score_id[j].second;
selected_index = j;
}
}
std::swap(score_id[i], score_id[selected_index]);
id_container.push_back(score_id[i].second);
i++;
}
}
| [
"jimmydiablo@gmail.com"
] | jimmydiablo@gmail.com |
e82ac70f14276ce9e6b99d39710e931905cd7a7b | c1939b1c65cbb83bb133f375cf543d0594f8ef87 | /Engine/System/Code/TimerManager.cpp | 7ad46ddef9aad4f63367872b09cafc536628dfc6 | [] | no_license | kots666/D3DProject | 58477681e3e904e2fba57e4da4f587239fdf5e0b | 80901995cc495d176923e1b9ad04e12407e71225 | refs/heads/master | 2023-03-03T23:08:47.007042 | 2021-02-19T05:18:08 | 2021-02-19T05:18:08 | 313,847,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | cpp | #include "TimerManager.h"
USING(Engine)
IMPLEMENT_SINGLETON(CTimerManager)
CTimerManager::CTimerManager()
{
}
CTimerManager::~CTimerManager()
{
Free();
}
_float CTimerManager::GetDeltaTime(const _tchar* timerTag)
{
CTimer* timer = Find(timerTag);
if (nullptr == timer)
return 0.f;
return timer->GetDeltaTime();
}
void CTimerManager::Update(const _tchar* timerTag)
{
CTimer* timer = Find(timerTag);
if (nullptr == timer)
return;
timer->Update();
}
HRESULT CTimerManager::Ready(const _tchar* timerTag)
{
CTimer* timer = Find(timerTag);
if (nullptr != timer)
return E_FAIL;
timer = CTimer::Create();
NULL_CHECK_RETURN(timer, E_FAIL);
m_timerMap.emplace(timerTag, timer);
return S_OK;
}
CTimer* CTimerManager::Find(const _tchar* timerTag)
{
auto iter = find_if(m_timerMap.begin(), m_timerMap.end(), CTagFinder(timerTag));
if (m_timerMap.end() == iter)
return nullptr;
return iter->second;
}
void CTimerManager::Free()
{
for_each(m_timerMap.begin(), m_timerMap.end(), CDeleteMap());
m_timerMap.clear();
} | [
"kots666@kpu.ac.kr"
] | kots666@kpu.ac.kr |
c4a5a95e5a386e76af0009b6616b2ce6e80961bf | 6bc87ae9bb38ef580689345b4c4603bf53c8e1c2 | /src/util.h | 0930797f99b84e7326c0fe6eb40cfc284a55a3ba | [
"MIT"
] | permissive | martexcoin/martexcoin | 54a5056d71d0f380481eca5ff347ae16d8562812 | 45c37bea83c06849c66f9fe3fbc31d4b4dbebb0e | refs/heads/master | 2022-04-29T10:53:08.218996 | 2022-04-06T16:45:35 | 2022-04-06T16:45:35 | 30,538,655 | 40 | 36 | MIT | 2021-01-19T15:40:46 | 2015-02-09T14:06:49 | C++ | UTF-8 | C++ | false | false | 7,712 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/**
* Server/client environment: argument handling, config file parsing,
* logging, thread wrappers
*/
#ifndef BITCOIN_UTIL_H
#define BITCOIN_UTIL_H
#if defined(HAVE_CONFIG_H)
#include "config/martex-config.h"
#endif
#include "compat.h"
#include "tinyformat.h"
#include "utiltime.h"
#include "util/threadnames.h"
#include <exception>
#include <map>
#include <stdint.h>
#include <string>
#include <vector>
#include <boost/filesystem/path.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted
// Debugging macros
// Uncomment the following line to enable debugging messages
// or enable on a per file basis prior to inclusion of util.h
//#define ENABLE_MARTEX_DEBUG
#ifdef ENABLE_MARTEX_DEBUG
#define DBG( x ) x
#else
#define DBG( x )
#endif
// MARTEX only features
extern bool fMasterNode;
extern bool fLiteMode;
extern bool fEnableFastTX;
extern int nFastTXDepth;
extern int64_t enforceMasternodePaymentsTime;
extern std::string strMasterNodeAddr;
extern int keysLoaded;
extern bool fSucessfullyLoaded;
extern std::vector<int64_t> anonSendDenominations;
extern std::string strBudgetMode;
extern std::map<std::string, std::string> mapArgs;
extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
extern bool fDebug;
extern bool fPrintToConsole;
extern bool fPrintToDebugLog;
extern std::string strMiscWarning;
extern bool fLogTimestamps;
extern bool fLogIPs;
extern volatile bool fReopenDebugLog;
void SetupEnvironment();
bool SetupNetworking();
/** Return true if log accepts specified category */
bool LogAcceptCategory(const char* category);
/** Send a string to the log output */
int LogPrintStr(const std::string& str);
/** Get format string from VA_ARGS for error reporting */
template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
#define LogPrintf(...) do { \
std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
try { \
_log_msg_ = tfm::format(__VA_ARGS__); \
} catch (tinyformat::format_error &e) { \
/* Original format string will have newline so don't add one here */ \
_log_msg_ = "Error \"" + std::string(e.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
} \
LogPrintStr(_log_msg_); \
} while(0)
#define LogPrint(category, ...) do { \
if (LogAcceptCategory((category))) { \
LogPrintf(__VA_ARGS__); \
} \
} while(0)
template<typename... Args>
bool error(const char* fmt, const Args&... args)
{
LogPrintStr("ERROR: " + tfm::format(fmt, args...) + "\n");
return false;
}
double double_safe_addition(double fValue, double fIncrement);
double double_safe_multiplication(double fValue, double fmultiplicator);
void PrintExceptionContinue(const std::exception* pex, const char* pszThread);
void ParseParameters(int argc, const char* const argv[]);
void FileCommit(FILE* fileout);
bool TruncateFile(FILE* file, unsigned int length);
int RaiseFileDescriptorLimit(int nMinFD);
void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length);
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest);
bool TryCreateDirectory(const boost::filesystem::path& p);
boost::filesystem::path GetDefaultDataDir();
bool CheckIfWalletDatExists(bool fNetSpecific = true);
const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
void ClearDatadirCache();
boost::filesystem::path GetConfigFile();
boost::filesystem::path GetMasternodeConfigFile();
#ifndef WIN32
boost::filesystem::path GetPidFile();
void CreatePidFile(const boost::filesystem::path& path, pid_t pid);
#endif
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
#endif
boost::filesystem::path GetTempPath();
void ShrinkDebugFile();
void runCommand(std::string strCommand);
inline bool IsSwitchChar(char c)
{
#ifdef WIN32
return c == '-' || c == '/';
#else
return c == '-';
#endif
}
/**
* Return string argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. "1")
* @return command-line argument or default value
*/
std::string GetArg(const std::string& strArg, const std::string& strDefault);
/**
* Return integer argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. 1)
* @return command-line argument (0 if invalid number) or default value
*/
int64_t GetArg(const std::string& strArg, int64_t nDefault);
/**
* Return boolean argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (true or false)
* @return command-line argument or default value
*/
bool GetBoolArg(const std::string& strArg, bool fDefault);
/**
* Set an argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param strValue Value (e.g. "1")
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetArg(const std::string& strArg, const std::string& strValue);
/**
* Set a boolean argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param fValue Value (e.g. false)
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetBoolArg(const std::string& strArg, bool fValue);
/**
* Format a string to be used as group of options in help messages
*
* @param message Group name (e.g. "RPC server options:")
* @return the formatted string
*/
std::string HelpMessageGroup(const std::string& message);
/**
* Format a string to be used as option description in help messages
*
* @param option Option message (e.g. "-rpcuser=<user>")
* @param message Option description (e.g. "Username for JSON-RPC connections")
* @return the formatted string
*/
std::string HelpMessageOpt(const std::string& option, const std::string& message);
void SetThreadPriority(int nPriority);
/**
* .. and a wrapper that just calls func once
*/
template <typename Callable>
void TraceThread(const char* name, Callable func)
{
std::string s = strprintf("martex-%s", name);
util::ThreadRename(s.c_str());
try {
LogPrintf("%s thread start\n", name);
func();
LogPrintf("%s thread exit\n", name);
} catch (boost::thread_interrupted) {
LogPrintf("%s thread interrupt\n", name);
throw;
} catch (std::exception& e) {
PrintExceptionContinue(&e, name);
throw;
} catch (...) {
PrintExceptionContinue(NULL, name);
throw;
}
}
long hex2long(const char* hexString);
#endif // BITCOIN_UTIL_H
| [
"marcianovc@gmail.com"
] | marcianovc@gmail.com |
60be3a71585d907bc0b1e589b85746ca879d44cc | 114d183f85e91502b4f87581521dcfa41a8152a0 | /implement/eagine/ssl_api.inl | 6bfaab4ad092718432324a87bbc4efde3f3faa13 | [
"BSL-1.0",
"GPL-3.0-only",
"GPL-1.0-or-later"
] | permissive | ford442/oglplu2 | 5544c888a11b9b2f92c3dd658c914403a6372604 | abf1e28d9bcd0d2348121e8640d9611a94112a83 | refs/heads/develop | 2023-07-28T03:56:59.431213 | 2021-09-01T05:40:48 | 2021-09-01T05:40:48 | 403,495,160 | 0 | 0 | BSL-1.0 | 2021-09-06T05:23:50 | 2021-09-06T05:21:38 | null | UTF-8 | C++ | false | false | 5,708 | inl | /// @file
///
/// Copyright Matus Chochlik.
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
///
namespace eagine::sslp {
//------------------------------------------------------------------------------
template <typename ApiTraits>
inline auto basic_ssl_api<ApiTraits>::data_digest(
memory::const_block data,
memory::block dst,
message_digest_type mdtype) const noexcept -> memory::block {
if(mdtype) {
const auto req_size = extract_or(this->message_digest_size(mdtype), 0);
if(dst.size() >= span_size(req_size)) {
if(ok mdctx{this->new_message_digest()}) {
auto cleanup{this->delete_message_digest.raii(mdctx)};
this->message_digest_init(mdctx, mdtype);
this->message_digest_update(mdctx, data);
return extract_or(
this->message_digest_final(mdctx, dst), memory::block{});
}
}
}
return {};
}
//------------------------------------------------------------------------------
template <typename ApiTraits>
inline auto basic_ssl_api<ApiTraits>::sign_data_digest(
memory::const_block data,
memory::block dst,
message_digest_type mdtype,
pkey pky) const noexcept -> memory::block {
if(mdtype && pky) {
if(ok mdctx{this->new_message_digest()}) {
auto cleanup{this->delete_message_digest.raii(mdctx)};
if(this->message_digest_sign_init(mdctx, mdtype, pky)) {
if(this->message_digest_sign_update(mdctx, data)) {
return extract_or(
this->message_digest_sign_final(mdctx, dst),
memory::block{});
}
}
}
}
return {};
}
//------------------------------------------------------------------------------
template <typename ApiTraits>
inline auto basic_ssl_api<ApiTraits>::verify_data_digest(
memory::const_block data,
memory::const_block sig,
message_digest_type mdtype,
pkey pky) const noexcept -> bool {
if(mdtype && pky) {
if(ok mdctx{this->new_message_digest()}) {
auto cleanup{this->delete_message_digest.raii(mdctx)};
if(this->message_digest_verify_init(mdctx, mdtype, pky)) {
if(this->message_digest_verify_update(mdctx, data)) {
return extract_or(
this->message_digest_verify_final(mdctx, sig), false);
}
}
}
}
return false;
}
//------------------------------------------------------------------------------
template <typename ApiTraits>
auto basic_ssl_api<ApiTraits>::parse_private_key(
memory::const_block blk,
password_callback get_passwd) const noexcept -> combined_result<owned_pkey> {
if(ok mbio{this->new_block_basic_io(blk)}) {
auto del_bio{this->delete_basic_io.raii(mbio)};
return this->read_bio_private_key(mbio, get_passwd);
}
return {owned_pkey{}};
}
//------------------------------------------------------------------------------
template <typename ApiTraits>
auto basic_ssl_api<ApiTraits>::parse_public_key(
memory::const_block blk,
password_callback get_passwd) const noexcept -> combined_result<owned_pkey> {
if(ok mbio{this->new_block_basic_io(blk)}) {
auto del_bio{this->delete_basic_io.raii(mbio)};
return this->read_bio_public_key(mbio, get_passwd);
}
return {owned_pkey{}};
}
//------------------------------------------------------------------------------
template <typename ApiTraits>
auto basic_ssl_api<ApiTraits>::parse_x509(
memory::const_block blk,
password_callback get_passwd) const noexcept -> combined_result<owned_x509> {
if(ok mbio{this->new_block_basic_io(blk)}) {
auto del_bio{this->delete_basic_io.raii(mbio)};
return this->read_bio_x509(mbio, get_passwd);
}
return {owned_x509{}};
}
//------------------------------------------------------------------------------
template <typename ApiTraits>
auto basic_ssl_api<ApiTraits>::ca_verify_certificate(
string_view ca_file_path,
x509 cert) const noexcept -> bool {
if(ok store{this->new_x509_store()}) {
auto del_store{this->delete_x509_store.raii(store)};
if(this->load_into_x509_store(store, ca_file_path)) {
if(ok vrfy_ctx{this->new_x509_store_ctx()}) {
auto del_vrfy{this->delete_x509_store_ctx.raii(vrfy_ctx)};
if(this->init_x509_store_ctx(vrfy_ctx, store, cert)) {
if(ok verify_res{this->x509_verify_certificate(vrfy_ctx)}) {
return true;
}
}
}
}
}
return false;
}
//------------------------------------------------------------------------------
template <typename ApiTraits>
auto basic_ssl_api<ApiTraits>::ca_verify_certificate(x509 ca_cert, x509 cert)
const noexcept -> bool {
if(ok store{this->new_x509_store()}) {
auto del_store{this->delete_x509_store.raii(store)};
if(this->add_cert_into_x509_store(store, ca_cert)) {
if(ok vrfy_ctx{this->new_x509_store_ctx()}) {
auto del_vrfy{this->delete_x509_store_ctx.raii(vrfy_ctx)};
if(this->init_x509_store_ctx(vrfy_ctx, store, cert)) {
if(ok verify_res{this->x509_verify_certificate(vrfy_ctx)}) {
return true;
}
}
}
}
}
return false;
}
//------------------------------------------------------------------------------
} // namespace eagine::sslp
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
c108fb371c1b8352a7f9a738be85d9dd88e4bc48 | c1a22a1759f5ca0ff76a99bbf69bc8995a21f540 | /search.cpp | cd670f3bdeba9ce569cc33f62ad03bc4532c74ee | [] | no_license | Savvas-Pol/Project_p3 | 794673374c8fb2757aa853e3c91b28bda0cae29d | 618f42735553cd5d639d5627cde51ba2332ffd85 | refs/heads/main | 2023-03-04T00:33:35.329072 | 2021-01-26T13:41:15 | 2021-01-26T13:41:15 | 333,096,491 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,870 | cpp | #include "help_functions.h"
#include "calculations.h"
#include "calculations_lsh.h"
#define w 40000
#define N 1
// #define m 107 //a_max < m < M/2
#define NForTable 16
using namespace std;
int main(int argc, char** argv) {
string iFile, iFile2, qFile, qFile2, oFile;
int i, k, L;
int magic_number = 0, number_of_images = 0;
int n_rows = 0, n_cols = 0, n_rows2 = 0, n_cols2 = 0;
int d, d2, M, m, h, pos;
unsigned int g, rDist;
int hTableSize, probes;
long long lshSum = 0, trueSum = 0, redSum = 0;
double approximationLsh, approximationReduced;
vector< vector<unsigned char> > pVec, qVec;
vector<unsigned char> tempVec;
vector< vector<unsigned short> > pVec2, qVec2;
vector<unsigned short> tempVec2;
vector< vector<int> > sVec;
vector<int> aVec, tempIntVec;
vector<distanceNode> distLsh, distTrue, distTrue2;
read_inputLSH(&argc, argv, &iFile, &iFile2, &qFile, &qFile2, &k, &L, &oFile);
M = pow(2, floor(32 / k));
m = (M / 2) - 1;
ifstream file(iFile);
ifstream file2(iFile2);
if (file.is_open() && file2.is_open()) {
read_data(file, &magic_number, &number_of_images, &n_rows, &n_cols, pVec, tempVec);
d = n_rows * n_cols; // dimension
read_data2(file2, &magic_number, &number_of_images, &n_rows2, &n_cols2, pVec2, tempVec2);
d2 = n_rows2 * n_cols2; // dimension
hTableSize = number_of_images / NForTable;
vector < vector< vector <hTableNode> > > lHashTables; // vector with L hash tables
vector< vector <hTableNode> > hashTable; // hash table
create_hashtables_LSH(lHashTables, hashTable, pVec, L, hTableSize, k, d, number_of_images, w, m, M);
ifstream qfile(qFile);
ifstream qfile2(qFile2);
if (qfile.is_open() && qfile2.is_open()) {
read_data(qfile, &magic_number, &number_of_images, &n_rows, &n_cols, qVec, tempVec);
read_data2(qfile2, &magic_number, &number_of_images, &n_rows2, &n_cols2, qVec2, tempVec2);
ofstream ofile(oFile);
if (ofile.is_open()) {
for (int i = 0; i < k; i++) {
tempIntVec = get_s(w, d); //s_i uniform random generator
sVec.push_back(tempIntVec);
tempIntVec.erase(tempIntVec.begin(), tempIntVec.end());
}
int countLsh = 0;
for (int i = 0; i < number_of_images; i++) {
for (int j = 0; j < k; j++) {
aVec = calculate_a(qVec[i], sVec[j], w, d); // calculate a for every image
h = calculate_h(aVec, m, M, d); // calculate h for every image
tempIntVec.push_back(h);
}
g = calculate_g(tempIntVec, k); // calculate g for every image
pos = g % hTableSize; // find the position to insert the image in the hash table
tempIntVec.erase(tempIntVec.begin(), tempIntVec.end());
auto t5 = chrono::high_resolution_clock::now();
distTrue2 = actual_nearest_neighbor2(qVec2[i], pVec2, d2, N);
auto t6 = chrono::high_resolution_clock::now();
auto durationTrue2 = chrono::duration_cast<chrono::microseconds>(t6 - t5).count();
auto t1 = chrono::high_resolution_clock::now();
distLsh = approximate_nearest_neighbor(qVec[i], lHashTables, L, pos, d, N, g);
auto t2 = chrono::high_resolution_clock::now();
auto durationLsh = chrono::duration_cast<chrono::microseconds>(t2 - t1).count();
auto t3 = chrono::high_resolution_clock::now();
distTrue = actual_nearest_neighbor(qVec[i], pVec, d, N);
auto t4 = chrono::high_resolution_clock::now();
auto durationTrue = chrono::duration_cast<chrono::microseconds>(t4 - t3).count();
ofile << "Query: " << i << endl; // write to file
for (int j = 0; j < N; j++) {
rDist = manhattan_dist(qVec[i], pVec[distTrue2[j].pPos], d);
ofile << "Nearest neighbor Reduced: " << distTrue2[j].pPos << endl;
ofile << "Nearest neighbor LSH: " << distLsh[j].pPos << endl;
ofile << "Nearest neighbor True: " << distTrue[j].pPos << endl;
ofile << "distanceReduced: " << rDist << endl;
ofile << "distanceLSH: " << distLsh[j].dist << endl;
ofile << "distanceTrue: " << distTrue[j].dist << endl;
if (distLsh[j].pPos != -1) {
lshSum += distLsh[j].dist;
countLsh++;
}
trueSum += distTrue[j].dist;
redSum += rDist;
}
ofile << "tReduced: " << durationTrue2 << endl;
ofile << "tLSH: " << durationLsh << endl;
ofile << "tTrue: " << durationTrue << endl;
}
cout << countLsh << endl;
approximationLsh = (double) (lshSum / countLsh) / (double) (trueSum / number_of_images);
approximationReduced = (double) (redSum / number_of_images) / (double) (trueSum / number_of_images);
ofile << "Approximation Factor LSH: " << approximationLsh << endl;
ofile << "Approximation Factor Reduced: " << approximationReduced << endl;
}
} else {
cout << "Could not open query file." << endl;
return 0;
}
} else {
cout << "Could not open input file." << endl;
return 0;
}
return 0;
}
| [
"sdi1200150@di.uoa.gr"
] | sdi1200150@di.uoa.gr |
d0c922ba50540a1d0d96c9b4a65c38d0830a6a21 | 08d17ddeb5713d8e7a4ee01054fcce78ed7f5191 | /tensorflow/compiler/xla/service/layout_assignment.cc | e90bdb640d71296243e35ce19b412e3fcd83c78f | [
"Apache-2.0"
] | permissive | Godsinred/tensorflow | 9cd67e1088ad8893265651ad4a5c45a6640b6c96 | 45100d5f55d7cba15bffcd91bf521ed37daf7bca | refs/heads/master | 2020-04-25T19:44:53.669366 | 2019-02-28T01:54:55 | 2019-02-28T02:59:15 | 173,030,955 | 2 | 0 | Apache-2.0 | 2019-02-28T03:03:41 | 2019-02-28T03:03:41 | null | UTF-8 | C++ | false | false | 92,181 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/layout_assignment.h"
#include <algorithm>
#include <deque>
#include <functional>
#include <map>
#include <memory>
#include <numeric>
#include <ostream>
#include <set>
#include <string>
#include <tuple>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/service/computation_layout.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_dce.h"
#include "tensorflow/compiler/xla/service/hlo_graph_dumper.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/logical_buffer.h"
#include "tensorflow/compiler/xla/service/tuple_simplifier.h"
#include "tensorflow/compiler/xla/shape_layout.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
namespace xla {
std::ostream& operator<<(std::ostream& out,
const LayoutConstraint& constraint) {
out << constraint.ToString();
return out;
}
BufferLayoutConstraint::BufferLayoutConstraint(const Layout& layout,
const LogicalBuffer& buffer,
bool mandatory, bool dfs)
: LayoutConstraint(mandatory, dfs), layout_(layout), buffer_(&buffer) {
CHECK(LayoutUtil::ValidateLayoutForShape(layout, buffer.shape()).ok());
}
string BufferLayoutConstraint::ToString() const {
return absl::StrFormat("BufferLayoutConstraint %s: %s", buffer_->ToString(),
LayoutUtil::HumanString(layout_));
}
OperandLayoutConstraint::OperandLayoutConstraint(
const ShapeLayout& shape_layout, const HloInstruction* instruction,
int64 operand_no, bool mandatory, bool dfs)
: LayoutConstraint(mandatory, dfs),
shape_layout_(shape_layout),
instruction_(instruction),
operand_no_(operand_no) {
CHECK(shape_layout_.LayoutIsSet());
CHECK(ShapeUtil::Compatible(shape_layout.shape(),
instruction->operand(operand_no)->shape()))
<< shape_layout.shape() << " is not compatible with "
<< instruction->operand(operand_no)->shape() << " (for operand "
<< operand_no << " of instruction " << instruction->ToString() << ")";
}
string OperandLayoutConstraint::ToString() const {
return absl::StrFormat("OperandLayoutConstraint %s, operand %d: %s",
instruction_->name(), operand_no_,
shape_layout_.ToString());
}
string ResultLayoutConstraint::ToString() const {
return absl::StrFormat("ResultLayoutConstraint: %s",
shape_layout_.ToString());
}
LayoutConstraints::LayoutConstraints(
const TuplePointsToAnalysis& points_to_analysis,
HloComputation* computation)
: points_to_analysis_(points_to_analysis), computation_(computation) {
// Gather all array-shaped logical buffers into unconstrained_buffer_ids.
for (HloInstruction* inst : computation_->instructions()) {
points_to_analysis_.GetPointsToSet(inst).ForEachElement(
[&](const ShapeIndex&, const PointsToSet::BufferList& buffers) {
for (const LogicalBuffer* buffer : buffers) {
// The points to analysis is computed per module, restrict
// constraints to array buffers in this computation.
if (buffer->IsArray() &&
buffer->instruction()->parent() == computation) {
unconstrained_buffer_ids_.insert(buffer->id());
}
}
});
}
}
PointsToSet::BufferSet* LayoutConstraints::GetBufferSet(
const HloInstruction* instruction) const {
auto it = buffer_sets_cache_.find(instruction);
if (it != buffer_sets_cache_.end()) {
return it->second.get();
}
auto& buffer_set =
buffer_sets_cache_
.emplace(instruction, absl::make_unique<PointsToSet::BufferSet>())
.first->second;
const auto& points_to_set = points_to_analysis_.GetPointsToSet(instruction);
points_to_set.ForEachElement(
[&buffer_set](const ShapeIndex& /*index*/,
const PointsToSet::BufferList& buffers) {
buffer_set->insert(buffers.begin(), buffers.end());
});
return buffer_set.get();
}
bool LayoutConstraints::OperandBufferForwarded(
const HloInstruction* instruction, int64 operand_no) const {
// The operand is potentially forwarded if the intersection of points-to sets
// of the operand and the instruction is non-empty.
PointsToSet::BufferSet* output_buffers = GetBufferSet(instruction);
PointsToSet::BufferSet* operand_buffers =
GetBufferSet(instruction->operand(operand_no));
return absl::c_any_of(*output_buffers, [&](const LogicalBuffer* b) {
return operand_buffers->count(b) > 0;
});
}
Status LayoutConstraints::SetBufferLayout(const Layout& layout,
const LogicalBuffer& buffer,
bool mandatory, bool dfs) {
VLOG(3) << "SetBufferLayout : " << buffer << " : "
<< LayoutUtil::HumanString(layout);
TF_RETURN_IF_ERROR(points_to_analysis_.VerifyBuffer(buffer));
if (!buffer.IsArray()) {
return FailedPrecondition(
"Layout of buffer %s cannot be constrained because buffer is not "
"array-shaped, has shape: %s",
buffer.ToString(), ShapeUtil::HumanString(buffer.shape()));
}
TF_RETURN_IF_ERROR(
LayoutUtil::ValidateLayoutForShape(layout, buffer.shape()));
auto iter = buffer_constraints_.find(&buffer);
if (iter != buffer_constraints_.end()) {
const BufferLayoutConstraint& curr_constraint = iter->second;
if (LayoutUtil::Equal(curr_constraint.layout(), layout)) {
// New constraint matches existing constraint. Nothing to do.
return Status::OK();
}
if (curr_constraint.mandatory()) {
return FailedPrecondition(
"Buffer %s already has the layout constraint %s, cannot add "
"incompatible constraint %s",
buffer.ToString(), LayoutUtil::HumanString(curr_constraint.layout()),
LayoutUtil::HumanString(layout));
}
iter->second = BufferLayoutConstraint(layout, buffer, mandatory, dfs);
} else {
TF_RET_CHECK(unconstrained_buffer_ids_.erase(buffer.id()) == 1)
<< buffer.ToString();
iter = buffer_constraints_
.insert(std::make_pair(
&buffer,
BufferLayoutConstraint(layout, buffer, mandatory, dfs)))
.first;
}
added_constraints_.push_back(&iter->second);
return Status::OK();
}
Status LayoutConstraints::SetOperandLayout(const Shape& shape_with_layout,
const HloInstruction* instruction,
int64 operand_no, bool mandatory,
bool dfs) {
VLOG(3) << "SetOperandLayout : " << instruction->name() << ", operand "
<< operand_no << " : "
<< ShapeUtil::HumanStringWithLayout(shape_with_layout);
const OperandLayoutConstraint* curr_shape_layout =
GetOperandLayoutConstraint(instruction, operand_no);
if (curr_shape_layout != nullptr) {
if (curr_shape_layout->shape_layout().MatchesLayoutInShape(
shape_with_layout)) {
// New constraint matches existing constraint. Nothing to do.
return Status::OK();
}
if (curr_shape_layout->mandatory()) {
return FailedPrecondition(
"Operand %d of instruction %s already has a layout constraint "
"%s, cannot add incompatible constraint %s",
operand_no, instruction->name(),
curr_shape_layout->shape_layout().ToString(),
ShapeUtil::HumanStringWithLayout(shape_with_layout));
}
}
// If any buffers in the operand occur in the output of the instruction, then
// return an error. This case is not handled because such a constraint changes
// layouts beyond this immediate use and is complicated to handle.
if (OperandBufferForwarded(instruction, operand_no)) {
return FailedPrecondition(
"Cannot constraint layout of operand %d of instruction %s "
"because instruction forwards operand's LogicalBuffer(s)",
operand_no, instruction->name());
}
auto key = std::make_pair(instruction, operand_no);
auto iter = operand_constraints_.find(key);
if (iter == operand_constraints_.end()) {
auto pair = std::make_pair(
key, OperandLayoutConstraint(ShapeLayout(shape_with_layout),
instruction, operand_no, mandatory, dfs));
iter = operand_constraints_.insert(pair).first;
} else {
iter->second =
OperandLayoutConstraint(ShapeLayout(shape_with_layout), instruction,
operand_no, mandatory, dfs);
}
added_constraints_.push_back(&iter->second);
return Status::OK();
}
Status LayoutConstraints::SetArrayOperandLayout(
const Layout& layout, const HloInstruction* instruction, int64 operand_no,
bool mandatory, bool dfs) {
const HloInstruction* operand = instruction->operand(operand_no);
TF_RET_CHECK(operand->shape().IsArray());
Shape shape(operand->shape());
*shape.mutable_layout() = layout;
TF_RETURN_IF_ERROR(LayoutUtil::ValidateLayoutInShape(shape));
return SetOperandLayout(shape, instruction, operand_no, mandatory, dfs);
}
Status LayoutConstraints::SetResultLayout(const Shape& shape_with_layout,
bool dfs) {
VLOG(3) << "SetResultLayout : "
<< ShapeUtil::HumanStringWithLayout(shape_with_layout);
const ShapeLayout* curr_shape_layout = ResultLayout();
if (curr_shape_layout != nullptr) {
if (!curr_shape_layout->MatchesLayoutInShape(shape_with_layout)) {
return FailedPrecondition(
"Result of computation %s already has the layout constraint %s, "
"cannot add incompatible constraint %s",
computation_->name(), curr_shape_layout->ToString(),
ShapeUtil::HumanStringWithLayout(shape_with_layout));
}
// New constraint matches existing constraint. Nothing to do.
return Status::OK();
}
result_constraint_.reset(
new ResultLayoutConstraint(ShapeLayout(shape_with_layout), dfs));
added_constraints_.push_back(result_constraint_.get());
return Status::OK();
}
Status LayoutConstraints::SetInstructionLayout(
const Shape& shape_with_layout, const HloInstruction* instruction,
bool mandatory, bool dfs) {
VLOG(3) << "SetInstructionLayout : " << instruction->name() << ", "
<< ShapeUtil::HumanStringWithLayout(shape_with_layout);
if (!ShapeUtil::Compatible(shape_with_layout, instruction->shape())) {
return FailedPrecondition(
"Instruction %s of shape %s cannot be assigned incompatible layout %s",
instruction->name(), ShapeUtil::HumanString(instruction->shape()),
ShapeUtil::HumanStringWithLayout(shape_with_layout));
}
// Create a BufferLayoutConstraint for each array shape in the output of the
// instruction.
return ShapeUtil::ForEachSubshapeWithStatus(
shape_with_layout,
[this, instruction, mandatory](const Shape& subshape,
const ShapeIndex& index) -> Status {
// The precondition for this method is that the instruction defines all
// buffers in its output.
auto buffers =
points_to_analysis_.GetPointsToSet(instruction).element(index);
CHECK_EQ(1, buffers.size());
CHECK_EQ(buffers[0]->instruction(), instruction);
if (subshape.IsArray()) {
return SetBufferLayout(subshape.layout(), *buffers[0], mandatory);
} else {
return Status::OK();
}
});
}
const Layout* LayoutConstraints::BufferLayout(
const LogicalBuffer& buffer) const {
if (const auto* constraint = GetBufferLayoutConstraint(buffer)) {
return &constraint->layout();
}
return nullptr;
}
const BufferLayoutConstraint* LayoutConstraints::GetBufferLayoutConstraint(
const LogicalBuffer& buffer) const {
auto it = buffer_constraints_.find(&buffer);
return it == buffer_constraints_.end() ? nullptr : &it->second;
}
const ShapeLayout* LayoutConstraints::OperandLayout(
const HloInstruction* instruction, int64 operand_no) const {
if (const auto* constraint =
GetOperandLayoutConstraint(instruction, operand_no)) {
return &constraint->shape_layout();
}
return nullptr;
}
const OperandLayoutConstraint* LayoutConstraints::GetOperandLayoutConstraint(
const HloInstruction* instruction, int64 operand_no) const {
auto it = operand_constraints_.find(std::make_pair(instruction, operand_no));
return it == operand_constraints_.end() ? nullptr : &it->second;
}
const ShapeLayout* LayoutConstraints::ResultLayout() const {
return result_constraint_ ? &result_constraint_->shape_layout() : nullptr;
}
string LayoutConstraints::ToString() const {
string output;
absl::StrAppend(&output, "LayoutConstraints for computation ",
computation_->name(), ":\n");
for (auto* instruction : computation_->MakeInstructionPostOrder()) {
absl::StrAppend(&output, " ", instruction->ToShortString(), "\n");
for (int64 i = 0; i < instruction->operand_count(); ++i) {
if (OperandLayout(instruction, i) != nullptr) {
absl::StrAppend(&output, " operand (", i,
"): ", OperandLayout(instruction, i)->ToString(), "\n");
}
}
for (const LogicalBuffer* buffer :
points_to_analysis_.GetBuffersDefinedByInstruction(instruction)) {
if (BufferLayout(*buffer) != nullptr) {
absl::StrAppend(&output, " ", buffer->ToString(), " : ",
LayoutUtil::HumanString(*BufferLayout(*buffer)), "\n");
}
}
}
if (ResultLayout() != nullptr) {
absl::StrAppend(&output, " => ", ResultLayout()->ToString(), "\n");
}
return output;
}
namespace {
bool IsHostSendRecv(const HloInstruction* instruction) {
const HloSendRecvInstruction* send_recv_instr =
DynCast<HloSendRecvInstruction>(instruction);
return send_recv_instr != nullptr && send_recv_instr->is_host_transfer();
}
} // namespace
Status LayoutAssignment::BuildHostChannelConstraints(
HloComputation* computation) {
for (auto* instruction : computation->instructions()) {
const HloSendRecvInstruction* send_recv_instr =
DynCast<HloSendRecvInstruction>(instruction);
if (send_recv_instr == nullptr || !send_recv_instr->is_host_transfer()) {
continue;
}
// For host transfers the Send and Recv instruction carry the layout.
if (instruction->opcode() == HloOpcode::kSend ||
instruction->opcode() == HloOpcode::kRecv) {
const Shape& data_shape =
ShapeUtil::GetTupleElementShape(send_recv_instr->shape(), 0);
TF_RET_CHECK(data_shape.IsArray());
TF_RET_CHECK(LayoutUtil::HasLayout(data_shape));
const Layout* prev_layout = host_channel_constraints_.ConstrainChannel(
send_recv_instr->channel_id(), data_shape.layout());
TF_RET_CHECK(prev_layout == nullptr)
<< "Cannot constrain host transfer layout as it was set to "
<< LayoutUtil::HumanString(*prev_layout) << ": "
<< send_recv_instr->ToString();
}
}
return Status::OK();
}
namespace {
bool IsLayoutConstrainedCustomCall(HloInstruction* instruction) {
const HloCustomCallInstruction* custom_call =
DynCast<HloCustomCallInstruction>(instruction);
return custom_call != nullptr && custom_call->layout_constrained();
}
} // namespace
Status LayoutAssignment::AddMandatoryConstraints(
const ComputationLayout* computation_layout,
ChannelLayoutConstraints* channel_constraints, HloComputation* computation,
LayoutConstraints* constraints) {
VLOG(3) << "Adding mandatory layout constraints to computation "
<< computation->name();
auto get_channel_constraints = [&](const HloInstruction* instruction) {
return IsHostSendRecv(instruction) ? &host_channel_constraints_
: channel_constraints;
};
// Constrain layouts of instructions which define values with pre-existing
// layouts.
for (auto* instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kInfeed) {
// Infeed layouts must match the layout of the original inserted
// instruction.
// TODO(b/31425034): Change infeeds to be more like parameters, with
// shapes in the ComputationLayout.
TF_RETURN_IF_ERROR(
constraints->SetInstructionLayout(instruction->shape(), instruction));
} else if (instruction->opcode() == HloOpcode::kOutfeed) {
// Constrain the input to the Outfeed instruction to be the expected
// layout of the Outfeed.
TF_RETURN_IF_ERROR(constraints->SetOperandLayout(
instruction->outfeed_shape(), instruction, 0));
} else if (instruction->opcode() == HloOpcode::kParameter) {
if (computation_layout != nullptr) {
const ShapeLayout& parameter_layout =
computation_layout->parameter_layout(
instruction->parameter_number());
if (parameter_layout.LayoutIsSet()) {
// Parameter layouts must match the respective layout in
// ComputationLayout, if there is one.
TF_RETURN_IF_ERROR(constraints->SetInstructionLayout(
parameter_layout.shape(), instruction));
}
}
} else if (IsLayoutConstrainedCustomCall(instruction)) {
const HloCustomCallInstruction* custom_call =
DynCast<HloCustomCallInstruction>(instruction);
TF_RETURN_IF_ERROR(
constraints->SetInstructionLayout(custom_call->shape(), custom_call));
for (int64 i = 0; i < custom_call->operand_count(); ++i) {
TF_RETURN_IF_ERROR(constraints->SetOperandLayout(
custom_call->operand_shapes_with_layout()[i], custom_call, i));
}
} else if (instruction->opcode() == HloOpcode::kSend ||
instruction->opcode() == HloOpcode::kRecv) {
CHECK(get_channel_constraints(instruction))
<< "Multi-module layout assignment requires ChannelLayoutConstraints";
int64 channel_id = instruction->channel_id();
if (!get_channel_constraints(instruction)
->IsChannelConstrained(channel_id)) {
continue;
}
if (instruction->opcode() == HloOpcode::kSend) {
// TODO(b/68493863): Change to use SetOperandLayout().
const Shape send_buffer_shape = instruction->operand(0)->shape();
TF_RET_CHECK(send_buffer_shape.IsArray());
Shape new_buffer_shape =
get_channel_constraints(instruction)
->LayoutShapeForChannel(send_buffer_shape,
instruction->channel_id());
TF_RETURN_IF_ERROR(constraints->SetInstructionLayout(
new_buffer_shape, instruction->operand(0)));
} else {
const Shape recv_buffer_shape =
ShapeUtil::GetTupleElementShape(instruction->shape(), 0);
TF_RET_CHECK(recv_buffer_shape.IsArray());
TF_ASSIGN_OR_RETURN(
const LogicalBuffer* buffer,
constraints->points_to_analysis().GetBufferDefinedAt(instruction,
{0}));
Shape new_shape = get_channel_constraints(instruction)
->LayoutShapeForChannel(
recv_buffer_shape, instruction->channel_id());
TF_RETURN_IF_ERROR(
constraints->SetBufferLayout(new_shape.layout(), *buffer));
}
} else if (instruction->IsCrossModuleAllReduce()) {
CHECK(get_channel_constraints(instruction))
<< "Multi-module layout assignment requires ChannelLayoutConstraints";
int64 all_reduce_id = instruction->all_reduce_id().value();
if (!get_channel_constraints(instruction)
->IsChannelConstrained(all_reduce_id)) {
continue;
}
// TODO(b/68493863): Change to use SetOperandLayout().
const Shape& buffer_shape = instruction->operand(0)->shape();
TF_RET_CHECK(buffer_shape.IsArray());
Shape new_buffer_shape =
get_channel_constraints(instruction)
->LayoutShapeForChannel(buffer_shape, all_reduce_id);
TF_RETURN_IF_ERROR(
constraints->SetInstructionLayout(new_buffer_shape, instruction));
}
}
// Constrain layouts of instructions which call computations which have
// already been assigned layouts. Instructions which call computations in a
// parallel element-wise context (eg, map or reduce) do not need layout
// constraints because they operate on scalars.
for (auto* instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kCall) {
// kCall instruction operands and output must match the ComputationLayout
// of the called computation.
const ComputationLayout& called_computation_layout =
FindOrDie(computation_layouts_, instruction->to_apply());
TF_RETURN_IF_ERROR(constraints->SetInstructionLayout(
called_computation_layout.result_layout().shape(), instruction));
TF_RET_CHECK(instruction->operand_count() ==
called_computation_layout.parameter_count());
for (int64 i = 0; i < instruction->operand_count(); ++i) {
TF_RETURN_IF_ERROR(constraints->SetOperandLayout(
called_computation_layout.parameter_layout(i).shape(), instruction,
i));
}
} else if (instruction->opcode() == HloOpcode::kWhile) {
// Layout of input and output of kWhile instruction must be equal and must
// match both input and output of body computation. Also, the input of
// condition computation must match kWhile layout.
HloComputation* body = instruction->while_body();
HloComputation* condition = instruction->while_condition();
const HloInstruction* init = instruction->operand(0);
ComputationLayout& body_layout = FindOrDie(computation_layouts_, body);
ComputationLayout& condition_layout =
FindOrDie(computation_layouts_, condition);
// Check a few invariants irrespective of layout.
CHECK_EQ(1, instruction->operand_count());
CHECK_EQ(1, body->num_parameters());
CHECK_EQ(1, condition->num_parameters());
DCHECK(ShapeUtil::Compatible(body_layout.result_shape(),
body_layout.parameter_shape(0)));
DCHECK(ShapeUtil::Compatible(body_layout.result_shape(),
condition_layout.parameter_shape(0)));
DCHECK(ShapeUtil::Compatible(body_layout.result_shape(), init->shape()));
if (body_layout.result_layout() != body_layout.parameter_layout(0)) {
VLOG(2) << "Reset %while body parameter layout: body=" << body->name()
<< " while=" << instruction->name()
<< " shape=" << body_layout.result_layout().ToString();
*body_layout.mutable_parameter_layout(0) = body_layout.result_layout();
}
if (condition_layout.parameter_layout(0) !=
body_layout.parameter_layout(0)) {
VLOG(2) << "Reset %while condition parameter layout: cond="
<< condition->name() << " while=" << instruction->name()
<< " shape=" << body_layout.parameter_layout(0).ToString();
*condition_layout.mutable_parameter_layout(0) =
body_layout.parameter_layout(0);
}
// Constrain the output and the operand of the while instruction to match
// the computations.
TF_RETURN_IF_ERROR(constraints->SetInstructionLayout(
body_layout.result_shape(), instruction));
TF_RETURN_IF_ERROR(constraints->SetOperandLayout(
body_layout.result_shape(), instruction, 0));
} else if (instruction->opcode() == HloOpcode::kConditional) {
// The layout of the branch computations must match, and must
// be the layout of the kConditional instruction.
ComputationLayout& branch0_computation_layout =
FindOrDie(computation_layouts_, instruction->branch_computation(0));
for (int j = 0; j < instruction->branch_count(); ++j) {
TF_RET_CHECK(instruction->branch_computation(j)->num_parameters() == 1);
ComputationLayout& branch_computation_layout =
FindOrDie(computation_layouts_, instruction->branch_computation(j));
DCHECK(ShapeUtil::Compatible(
instruction->operand(j + 1)->shape(),
branch_computation_layout.parameter_shape(0)));
if (branch0_computation_layout.result_layout() !=
branch_computation_layout.result_layout()) {
// We assign layouts in DFS fashion, so the br_0 and br_j
// computations might have negotiated a different layout. But for the
// case instruction POV the layout must match, so we run again
// on the br_j computation, this time with proper computation layout.
VLOG(2) << "Reset %conditional branch " << j
<< " computation result layout: branch_computation="
<< instruction->branch_computation(j)->name()
<< " case=" << instruction->name() << " shape="
<< branch0_computation_layout.result_layout().ToString();
*branch_computation_layout.mutable_result_layout() =
branch0_computation_layout.result_layout();
}
if (j == 0) {
TF_RETURN_IF_ERROR(constraints->SetInstructionLayout(
branch0_computation_layout.result_shape(), instruction));
}
TF_RETURN_IF_ERROR(constraints->SetOperandLayout(
branch_computation_layout.parameter_shape(0), instruction, j + 1,
/*mandatory=*/true));
}
}
}
// Finally set the result layout to match ComputationLayout, if there is one.
if (computation_layout != nullptr) {
const ShapeLayout& result_layout = computation_layout->result_layout();
if (result_layout.LayoutIsSet()) {
TF_RETURN_IF_ERROR(constraints->SetResultLayout(result_layout.shape()));
}
}
return Status::OK();
}
namespace {
// The operands of a call must match the layouts of parameters in the
// ComputationLayout, and the call instruction itself must match the result
// layout in the ComputationLayout.
Status CheckCallLayout(HloInstruction* call,
const ComputationLayout& computation_layout) {
HloComputation* computation = call->to_apply();
TF_RET_CHECK(computation->num_parameters() == call->operand_count());
for (int64 i = 0; i < computation->num_parameters(); ++i) {
TF_RET_CHECK(computation_layout.parameter_layout(i).MatchesLayoutInShape(
call->operand(i)->shape()));
}
TF_RET_CHECK(
computation_layout.result_layout().MatchesLayoutInShape(call->shape()));
return Status::OK();
}
// Operands of layout-constrained custom calls must match the expected
// constrained layouts.
Status CheckCustomCallLayout(HloInstruction* instruction) {
if (IsLayoutConstrainedCustomCall(instruction)) {
const HloCustomCallInstruction* custom_call =
DynCast<HloCustomCallInstruction>(instruction);
for (int64 i = 0; i < custom_call->operand_count(); ++i) {
TF_RET_CHECK(LayoutUtil::LayoutsInShapesEqual(
custom_call->operand(i)->shape(),
custom_call->operand_shapes_with_layout()[i]));
}
}
return Status::OK();
}
// For a while instruction, all the following layouts must be the same:
// (1) init operand
// (2) condition computation parameter
// (3) body computation parameter
// (4) body computation result
// (5) while instruction result
Status CheckWhileLayout(HloInstruction* while_inst,
const ComputationLayout& condition_computation_layout,
const ComputationLayout& body_computation_layout) {
auto init_shape = while_inst->operand(0)->shape();
TF_RET_CHECK(
condition_computation_layout.parameter_layout(0).MatchesLayoutInShape(
init_shape));
TF_RET_CHECK(body_computation_layout.parameter_layout(0).MatchesLayoutInShape(
init_shape));
TF_RET_CHECK(
body_computation_layout.result_layout().MatchesLayoutInShape(init_shape));
TF_RET_CHECK(
LayoutUtil::LayoutsInShapesEqual(init_shape, while_inst->shape()));
return Status::OK();
}
Status CheckConditionalLayout(
HloInstruction* instruction,
absl::Span<const ComputationLayout> branch_computation_layouts) {
for (int j = 0; j < instruction->branch_count(); ++j) {
const HloInstruction* branch_operand = instruction->operand(j + 1);
TF_RET_CHECK(branch_computation_layouts[0].result_layout() ==
branch_computation_layouts[j].result_layout());
TF_RET_CHECK(
branch_computation_layouts[j].result_layout().MatchesLayoutInShape(
instruction->shape()));
TF_RET_CHECK(
branch_computation_layouts[j].result_layout().MatchesLayoutInShape(
instruction->branch_computation(j)->root_instruction()->shape()));
TF_RET_CHECK(
branch_computation_layouts[j].parameter_layout(0).MatchesLayoutInShape(
branch_operand->shape()));
}
return Status::OK();
}
// Fusion parameters must match the layout of the fusion instructions operands,
// and the root of the fusion expression must match the layout of the fusion
// instruction.
Status CheckFusionLayout(HloInstruction* fusion) {
TF_RET_CHECK(HloOpcode::kFusion == fusion->opcode());
TF_RET_CHECK(LayoutUtil::LayoutsInShapesEqual(
fusion->shape(), fusion->fused_expression_root()->shape()));
for (int64 i = 0; i < fusion->operand_count(); ++i) {
TF_RET_CHECK(LayoutUtil::LayoutsInShapesEqual(
fusion->fused_parameter(i)->shape(), fusion->operand(i)->shape()));
}
return Status::OK();
}
// The layout of a parameter must match the respective layout in the
// computation's ComputationLayout.
Status CheckParameterLayout(HloInstruction* parameter,
const ComputationLayout& computation_layout) {
const ShapeLayout& parameter_layout =
computation_layout.parameter_layout(parameter->parameter_number());
if (parameter_layout.LayoutIsSet() &&
!parameter_layout.MatchesLayoutInShape(parameter->shape())) {
return InternalError(
"parameter instruction %s does not match layout of computation "
"shape: %s",
parameter->ToString(), parameter_layout.ToString());
}
return Status::OK();
}
// The layout of a constant instruction must match the layout of its literal.
Status CheckConstantLayout(HloInstruction* constant) {
if (!LayoutUtil::LayoutsInShapesEqual(constant->literal().shape(),
constant->shape())) {
return InternalError(
"constant instruction %s does not match the layout of its literal %s",
constant->ToString(),
ShapeUtil::HumanStringWithLayout(constant->literal().shape()));
}
return Status::OK();
}
} // namespace
StatusOr<HloInstruction*> LayoutAssignment::CreateCopyWithNewLayout(
const Shape& shape_with_layout, HloInstruction* instruction) {
TF_RET_CHECK(LayoutUtil::HasLayout(shape_with_layout));
DCHECK(ShapeUtil::Compatible(shape_with_layout, instruction->shape()))
<< ShapeUtil::HumanString(shape_with_layout) << " "
<< ShapeUtil::HumanString(instruction->shape())
<< " instruction: " << instruction->ToString();
if (instruction->shape().IsTuple()) {
// Copy tuple elements which have differing layouts.
std::vector<HloInstruction*> element_copies;
for (int64 i = 0; i < ShapeUtil::TupleElementCount(instruction->shape());
++i) {
const Shape& target_shape =
ShapeUtil::GetSubshape(shape_with_layout, {i});
const Shape& instr_shape =
ShapeUtil::GetSubshape(instruction->shape(), {i});
HloInstruction* gte = instruction->parent()->AddInstruction(
HloInstruction::CreateGetTupleElement(instr_shape, instruction, i));
if (ShapeUtil::Equal(target_shape, instr_shape)) {
// Shapes and layouts are equal, no need to copy.
element_copies.push_back(gte);
} else {
SetupCopiedInstruction(*instruction, gte, {i});
// Recurse to copy each element.
TF_ASSIGN_OR_RETURN(HloInstruction * element_copy,
CreateCopyWithNewLayout(target_shape, gte));
element_copies.push_back(element_copy);
}
}
// Gather element copies into a tuple with a new Tuple instruction.
HloInstruction* tuple_copy = instruction->parent()->AddInstruction(
HloInstruction::CreateTuple(element_copies));
SetupCopiedInstruction(*instruction, tuple_copy, {});
LayoutUtil::ClearLayout(tuple_copy->mutable_shape());
TF_RETURN_IF_ERROR(LayoutUtil::CopyLayoutBetweenShapes(
shape_with_layout, tuple_copy->mutable_shape()));
return tuple_copy;
} else if (instruction->shape().IsArray()) {
HloInstruction* copy =
instruction->parent()->AddInstruction(HloInstruction::CreateUnary(
instruction->shape(), HloOpcode::kCopy, instruction));
RegisterAddedCopy(copy);
SetupCopiedInstruction(*instruction, copy, {});
LayoutUtil::ClearLayout(copy->mutable_shape());
TF_RETURN_IF_ERROR(LayoutUtil::CopyLayoutBetweenShapes(
shape_with_layout, copy->mutable_shape()));
return copy;
} else {
return FailedPrecondition(
"Can only copy array and tuple shaped instructions");
}
}
// Creates a copy of the given operand if the operand's layout does not match
// the given layout. This copy replaces the use in the given instruction. Tuple
// operands will be deep-copied.
Status LayoutAssignment::CopyOperandIfLayoutsDiffer(
const ShapeLayout& operand_layout, HloInstruction* instruction,
int64 operand_no) {
HloInstruction* operand = instruction->mutable_operand(operand_no);
TF_RET_CHECK(operand_layout.LayoutIsSet());
TF_RET_CHECK(LayoutUtil::HasLayout(operand->shape()));
if (ShapeUtil::Equal(operand_layout.shape(), operand->shape())) {
VLOG(5) << "Operand " << operand->ToString() << " layout matches in "
<< instruction->ToString();
// Operand layout already matches our constraint. Nothing to do.
return Status::OK();
}
VLOG(4) << "Operand " << operand->ToString() << " layout does not match "
<< operand_layout.ToString() << " in " << instruction->ToString();
TF_ASSIGN_OR_RETURN(HloInstruction * operand_copy,
CreateCopyWithNewLayout(operand_layout.shape(), operand));
VLOG(4) << "New copy of " << operand->ToString() << " is "
<< operand_copy->ToString();
return instruction->ReplaceOperandWith(operand_no, operand_copy);
}
void LayoutAssignment::SetupCopiedInstruction(const HloInstruction& instruction,
HloInstruction* copy,
const ShapeIndex& index) {
if (instruction.has_sharding()) {
// If the index is empty, we want to copy the whole sharding, in case the
// sharding is a tuple sharding.
HloSharding sharding =
!index.empty() && instruction.sharding().IsTuple()
? instruction.sharding().GetSubSharding(instruction.shape(), index)
: instruction.sharding();
// We propagate the sharding to the copied instruction only if it is a
// special sharding, like tiled ones.
// Otherwise it is preferable to leave the new instruction without device,
// and let the automatic device placer to choose the best location.
auto device = sharding.UniqueDevice();
if (!device || HloSharding::IsReservedDevice(*device)) {
copy->set_sharding(sharding);
}
}
copy->set_metadata(instruction.metadata());
}
Status LayoutAssignment::CheckLayouts(HloModule* module) {
TF_ASSIGN_OR_RETURN(auto points_to_analysis,
TuplePointsToAnalysis::Run(module));
for (auto* computation : module->MakeNonfusionComputations()) {
for (auto* instruction : computation->instructions()) {
// Verify every instruction has a layout and the layout is valid for the
// shape.
TF_RET_CHECK(LayoutUtil::HasLayout(instruction->shape()));
TF_RETURN_IF_ERROR(ShapeUtil::ValidateShape(instruction->shape()));
// Use points-to analysis to verify that every subshape element in the
// output of the instruction matches the layout of the logical buffer
// which could be the source of the subshape value.
const PointsToSet& points_to_set =
points_to_analysis->GetPointsToSet(instruction);
TF_RETURN_IF_ERROR(points_to_set.ForEachElementWithStatus(
[&instruction](ShapeIndex index,
const PointsToSet::BufferList& buffers) -> Status {
if (ShapeUtil::IsLeafIndex(instruction->shape(), index)) {
const Shape& instruction_subshape =
ShapeUtil::GetSubshape(instruction->shape(), index);
for (const LogicalBuffer* buffer : buffers) {
if (!ShapeUtil::Equal(instruction_subshape, buffer->shape())) {
return InternalError(
"Layout of instruction %s at index {%s} does not match "
"source LogicalBuffer %s: %s vs %s",
instruction->name(), absl::StrJoin(index, ","),
buffer->ToString(),
ShapeUtil::HumanStringWithLayout(instruction_subshape),
ShapeUtil::HumanStringWithLayout(buffer->shape()));
}
}
}
return Status::OK();
}));
// Verify instructions that have special layout constraints.
switch (instruction->opcode()) {
case HloOpcode::kCall:
TF_RETURN_IF_ERROR(CheckCallLayout(
instruction,
FindOrDie(computation_layouts_, instruction->to_apply())));
break;
case HloOpcode::kCustomCall:
TF_RETURN_IF_ERROR(CheckCustomCallLayout(instruction));
break;
case HloOpcode::kFusion:
TF_RETURN_IF_ERROR(CheckFusionLayout(instruction));
break;
case HloOpcode::kParameter:
TF_RETURN_IF_ERROR(CheckParameterLayout(
instruction,
FindOrDie(computation_layouts_, instruction->parent())));
break;
case HloOpcode::kConstant:
TF_RETURN_IF_ERROR(CheckConstantLayout(instruction));
break;
case HloOpcode::kWhile:
TF_RETURN_IF_ERROR(CheckWhileLayout(
instruction,
FindOrDie(computation_layouts_, instruction->while_condition()),
FindOrDie(computation_layouts_, instruction->while_body())));
break;
case HloOpcode::kConditional: {
std::vector<ComputationLayout> branch_computation_layouts;
for (auto branch_computation : instruction->branch_computations()) {
branch_computation_layouts.emplace_back(
FindOrDie(computation_layouts_, branch_computation));
}
TF_RETURN_IF_ERROR(CheckConditionalLayout(
instruction, absl::MakeSpan(branch_computation_layouts)));
break;
}
default:
break;
}
}
}
// Finally verify the result layout, if set, matches the layout of the entry
// computation root.
const ShapeLayout& result_layout =
FindOrDie(computation_layouts_, module->entry_computation())
.result_layout();
if (result_layout.LayoutIsSet()) {
TF_RET_CHECK(
ShapeUtil::Equal(module->result_shape(), result_layout.shape()));
}
return Status::OK();
}
LayoutAssignment::LayoutAssignment(
ComputationLayout* entry_computation_layout,
std::function<bool(const HloInstruction*)>
instruction_can_change_layout_func,
ChannelLayoutConstraints* channel_constraints)
: entry_computation_layout_(entry_computation_layout),
saved_entry_computation_layout_(*entry_computation_layout),
channel_layout_constraints_(channel_constraints),
instruction_can_change_layout_func_(
std::move(instruction_can_change_layout_func)) {
if (channel_layout_constraints_ != nullptr) {
// Save a copy of the input ChannelLayoutConstraints so that we can reset it
// if we have to undo previous operations (ClearPreviousPassSideEffects()).
channel_constraints_ = *channel_layout_constraints_;
}
VLOG(1) << "Entry computation layout given to layout assignment: "
<< entry_computation_layout_->ToString();
}
std::unique_ptr<Layout> LayoutAssignment::ChooseOperandLayoutFromOutputLayout(
const Layout& output_layout, const HloInstruction* instruction,
int64 operand_no) {
const HloInstruction* operand = instruction->operand(operand_no);
CHECK(instruction->shape().IsArray());
CHECK(operand->shape().IsArray());
if (!ShapeUtil::IsScalar(operand->shape()) &&
operand->shape().rank() == instruction->shape().rank() &&
!instruction_can_change_layout_func_(instruction)) {
// Propagate the result layout to the operand layout if the instruction
// requires the same layout out for the result and the operand.
//
// For elementwise operations, using the same layout for the operands and
// the result also has the following benefits:
// 1) the elementwise operation can reuse its operand's buffer, and
// 2) the input and output elements can reuse the same linear index.
return absl::make_unique<Layout>(output_layout);
}
if (instruction->opcode() == HloOpcode::kReshape) {
// Prefer the operand layout that makes the reshape an bitcast. If any
// dimension bound is 1 in the operand shape, there may be several such
// layouts. So if 'output_layout' is the default layout, try if the
// reshape is a bitcast when using the same layout. This may avoid copy
// operations. For similar reasons, if the operand and output have the same
// rank, try to match the operand's layout to the output.
if (ShapeUtil::TrueRank(operand->shape()) == 1 &&
instruction->shape().rank() == 1) {
// Don't assign a layout in case of R1 -> effective R1 reshape.
return nullptr;
}
const Shape& output_shape = instruction->shape();
Shape output_shape_with_layout = ShapeUtil::MakeShapeWithLayout(
output_shape.element_type(), AsInt64Slice(output_shape.dimensions()),
LayoutUtil::MinorToMajor(output_layout));
Shape operand_shape = operand->shape();
*operand_shape.mutable_layout() =
LayoutUtil::GetDefaultLayoutForShape(operand_shape);
auto aligned_operand_shape =
ShapeUtil::AlignLayouts(output_shape_with_layout, operand_shape);
if (aligned_operand_shape) {
auto operand_layout = aligned_operand_shape.value().layout();
TF_CHECK_OK(
LayoutUtil::ValidateLayoutForShape(operand_layout, operand_shape));
return absl::make_unique<Layout>(operand_layout);
}
}
if (instruction->opcode() == HloOpcode::kTranspose) {
// Pick the operand layout that makes the transpose a bitcast.
int64 rank = instruction->shape().rank();
std::vector<int64> new_minor_to_major(rank);
for (int64 i = 0; i < rank; ++i) {
int64 output_dim = LayoutUtil::Minor(output_layout, i);
int64 operand_dim = instruction->dimensions(output_dim);
new_minor_to_major[i] = operand_dim;
}
Layout operand_layout = LayoutUtil::MakeLayout(new_minor_to_major);
TF_CHECK_OK(
LayoutUtil::ValidateLayoutForShape(operand_layout, operand->shape()));
return absl::make_unique<Layout>(operand_layout);
}
return nullptr;
}
std::unique_ptr<Layout> LayoutAssignment::ChooseOutputLayoutFromOperandLayout(
const Layout& operand_layout, const HloInstruction* user,
int64 operand_no) {
const HloInstruction* operand = user->operand(operand_no);
CHECK(user->shape().IsArray() && operand->shape().IsArray());
if (!ShapeUtil::IsScalar(operand->shape()) &&
operand->shape().rank() == user->shape().rank() &&
!instruction_can_change_layout_func_(user)) {
// Assign users the same layout as the operand.
return absl::make_unique<Layout>(operand_layout);
}
if (user->opcode() == HloOpcode::kReshape) {
// Prefer the user layout that makes the reshape an bitcast. If any
// dimension bound is 1 in the user shape, there may be several such
// layouts. So if 'operand_layout' is the default layout, try if the
// reshape is a bitcast when using the same layout. This may avoid copy
// operations. For similar reasons, if the operand and output have the same
// rank, try to match the outputs's layout to the operand.
if (operand->shape().rank() == 1 &&
ShapeUtil::TrueRank(user->shape()) == 1) {
// Don't assign a layout in case of R1 -> effective R1 reshape.
return nullptr;
}
Shape operand_shape_with_layout = ShapeUtil::MakeShapeWithLayout(
operand->shape().element_type(),
AsInt64Slice(operand->shape().dimensions()),
LayoutUtil::MinorToMajor(operand_layout));
Shape output_shape = user->shape();
*output_shape.mutable_layout() =
LayoutUtil::GetDefaultLayoutForShape(output_shape);
auto aligned_user_shape =
ShapeUtil::AlignLayouts(operand_shape_with_layout, output_shape);
if (aligned_user_shape) {
auto user_layout = aligned_user_shape.value().layout();
TF_CHECK_OK(
LayoutUtil::ValidateLayoutForShape(user_layout, output_shape));
return absl::make_unique<Layout>(user_layout);
}
}
if (user->opcode() == HloOpcode::kTranspose) {
// Pick the user layout that makes the transpose a bitcast.
int64 rank = user->shape().rank();
std::vector<int64> new_minor_to_major(rank);
auto inverse_dimensions = InversePermutation(user->dimensions());
for (int64 i = 0; i < rank; ++i) {
int64 operand_dim = LayoutUtil::Minor(operand_layout, i);
int64 user_dim = inverse_dimensions[operand_dim];
new_minor_to_major[i] = user_dim;
}
Layout user_layout = LayoutUtil::MakeLayout(new_minor_to_major);
TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(user_layout, user->shape()));
return absl::make_unique<Layout>(user_layout);
}
return nullptr;
}
Status LayoutAssignment::PropagateConstraints(LayoutConstraints* constraints) {
// Gathers all initial constraints in a worklist and propagates them in
// depth-first order. DFS order seems to be better than BFS because a
// constraint is propagated as far as possible before propagating unrelated
// constraints which makes it less likely that conflicting constraints will be
// propagated to instructions. However, we should experiment with other orders
// too.
std::deque<const LayoutConstraint*> worklist;
// Lambda for moving newly added constraints to the worklist.
auto add_new_constraints_to_worklist = [constraints, &worklist]() {
// Add constraints to the front of the deque for DFS ordering.
for (auto* constraint : constraints->ConsumeAddedConstraints()) {
if (constraint->dfs()) {
worklist.push_front(constraint);
} else {
worklist.push_back(constraint);
}
}
};
add_new_constraints_to_worklist();
while (!worklist.empty()) {
const LayoutConstraint* layout_constraint = worklist.front();
worklist.pop_front();
VLOG(2) << "Propagating " << layout_constraint->ToString()
<< " to its neighbors.";
if (auto* buffer_constraint =
dynamic_cast<const BufferLayoutConstraint*>(layout_constraint)) {
TF_RETURN_IF_ERROR(
PropagateBufferConstraint(*buffer_constraint, constraints));
} else if (auto* operand_constraint =
dynamic_cast<const OperandLayoutConstraint*>(
layout_constraint)) {
TF_RETURN_IF_ERROR(
PropagateOperandConstraint(*operand_constraint, constraints));
} else if (auto* result_constraint =
dynamic_cast<const ResultLayoutConstraint*>(
layout_constraint)) {
TF_RETURN_IF_ERROR(
PropagateResultConstraint(*result_constraint, constraints));
} else {
LOG(FATAL) << "Invalid constraint type: " << *layout_constraint;
}
add_new_constraints_to_worklist();
}
return Status::OK();
}
namespace {
// Returns a vector containing all array-shaped uses (instruction and operand
// number) of the given logical buffer or its aliases.
std::vector<std::pair<const HloInstruction*, int64>> GetArrayUsesOfBuffer(
const LogicalBuffer& buffer,
const TuplePointsToAnalysis& points_to_analysis) {
CHECK(buffer.IsArray());
std::vector<std::pair<const HloInstruction*, int64>> uses;
for (const auto& buffer_alias : points_to_analysis.GetBufferAliases(buffer)) {
if (!buffer_alias.instruction()->shape().IsArray()) {
continue;
}
// This alias must be the top-level (index == {}) of the instruction's
// result because the instruction produces an array.
CHECK(buffer_alias.index().empty());
// Add all uses of the instruction's output.
for (const HloInstruction* user : buffer_alias.instruction()->users()) {
for (int64 operand_no :
user->OperandIndices(buffer_alias.instruction())) {
uses.emplace_back(user, operand_no);
}
}
}
return uses;
}
} // namespace
Status LayoutAssignment::PropagateUseConstraintToDefs(
const ShapeLayout& shape_layout, const HloInstruction* instruction,
LayoutConstraints* constraints) {
// Try to set all logical buffers which may be sources of the given operand to
// match the given layout.
const PointsToSet& points_to_set =
constraints->points_to_analysis().GetPointsToSet(instruction);
return points_to_set.ForEachElementWithStatus(
[&shape_layout, constraints](
const ShapeIndex& index,
const PointsToSet::BufferList& buffers) -> Status {
if (ShapeUtil::IsLeafIndex(shape_layout.shape(), index)) {
for (const LogicalBuffer* buffer : buffers) {
if (constraints->BufferLayout(*buffer) == nullptr &&
buffer->shape().IsArray()) {
TF_RETURN_IF_ERROR(constraints->SetBufferLayout(
ShapeUtil::GetSubshape(shape_layout.shape(), index).layout(),
*buffer, /*mandatory=*/true));
}
}
}
return Status::OK();
});
}
namespace {
// A transpose or a reshape that only changes trivial dimensions have meaningful
// layouts that are valuable to propagate in a depthfirst manner to avoid
// unassigned layouts in the graph.
bool InstructionShouldPropagateDepthFirst(const HloInstruction& hlo) {
switch (hlo.opcode()) {
case HloOpcode::kReshape:
return std::get<0>(hlo.ReshapeMerelyInsertsOrDeletes1SizedDimensions());
case HloOpcode::kTranspose:
return true;
default:
return false;
}
}
} // namespace
Status LayoutAssignment::PropagateOperandConstraint(
const OperandLayoutConstraint& operand_constraint,
LayoutConstraints* constraints) {
// Try to set the layout of the logical buffers in the given operand to match
// the constrained layout. This avoids copies.
TF_RETURN_IF_ERROR(
PropagateUseConstraintToDefs(operand_constraint.shape_layout(),
operand_constraint.operand(), constraints));
// For array-shaped operands and user instructions try to pick a minimum cost
// layout. For example, if the operand of an elementwise instruction is
// constrained to a certain layout we want the output of the instruction to
// have the same layout.
//
// If the user is not array-shaped, we still want to propagate the layout
// to siblings if the instruction can't change layout. This is to represent
// the information that non-layout-changing instructions should have the same
// layout for the operands with the same ranks.
const HloInstruction* operand = operand_constraint.operand();
const HloInstruction* user = operand_constraint.instruction();
if (!operand->shape().IsArray()) {
return Status::OK();
}
if (instruction_can_change_layout_func_(user) && !user->shape().IsArray()) {
return Status::OK();
}
// Only try to choose a low cost layout if the instruction 'user' defines its
// output (ie, doesn't forward a buffer from elsewhere).
if (constraints->OperandBufferForwarded(user,
operand_constraint.operand_no())) {
return Status::OK();
}
int64 operand_rank = operand->shape().rank();
if (operand_rank <= 1) {
return Status::OK();
}
// Propagate layouts between operands of the same instruction. This is a
// constraint on non-layout-changing instructions.
if (!instruction_can_change_layout_func_(user)) {
// Make sure all siblings have the same layout as the operand.
for (int64 operand_no = 0; operand_no < user->operand_count();
++operand_no) {
if (user->operand(operand_no) == operand) {
continue;
}
const HloInstruction* sibling = user->operand(operand_no);
const int64 sibling_rank = sibling->shape().rank();
if (sibling_rank <= 1) {
continue;
}
if (operand_rank != sibling_rank) {
continue;
}
const OperandLayoutConstraint* constraint =
constraints->GetOperandLayoutConstraint(user, operand_no);
if (constraint != nullptr) {
// Due to the DFS of the propagation we can end up here when operand_no
// has a layout set that hasn't been propagated yet (is still on the
// stack of layouts to propagate).
// We can continue here and leave the operands with different layouts,
// as we will either:
// - overwrite the current operand when the DFS gets back to propagating
// operand(operand_no) to its siblings
// - overwrite operand(operand_no)'s layout with a mandatory layout if
// we continue to propagate our layout to the result, and then
// backwards into all operands (if the result is an array of rank > 1)
continue;
}
TF_RETURN_IF_ERROR(constraints->SetArrayOperandLayout(
operand_constraint.shape_layout().layout(), user, operand_no,
/*mandatory=*/false));
}
TF_RETURN_IF_ERROR(ShapeUtil::ForEachSubshapeWithStatus(
user->shape(),
[&](const Shape& subshape, const ShapeIndex& shape_index) {
if (subshape.IsTuple()) {
return Status::OK();
}
if (subshape.rank() <= 1) {
return Status::OK();
}
// Assign the right layout to input fusion of higher rank reduce
// operations.
if (subshape.rank() != operand->shape().rank()) {
return Status::OK();
}
// TODO(b/67641796): Are there cases except fusion that use this code
// path?
TF_ASSIGN_OR_RETURN(
const LogicalBuffer* buffer,
constraints->points_to_analysis().GetBufferDefinedAt(
user, shape_index));
// Make sure the output has the same layout as the operand.
const BufferLayoutConstraint* constraint =
constraints->GetBufferLayoutConstraint(*buffer);
// If we already have a constraint for the buffer it was assigned but
// hasn't propagated yet. This can happen with diamond-shaped graphs
// where one path is first evaluated in depth-first order (we're here)
// and the other path is propagated later. We don't set the layout
// here as it will always be overwritten later.
if (constraint == nullptr) {
TF_RETURN_IF_ERROR(constraints->SetBufferLayout(
operand_constraint.shape_layout().layout(), *buffer,
/*mandatory=*/false));
}
return Status::OK();
}));
return Status::OK();
}
TF_RETURN_IF_ERROR(ShapeUtil::ForEachSubshapeWithStatus(
user->shape(), [&](const Shape& subshape, const ShapeIndex& shape_index) {
if (subshape.IsTuple()) {
return Status::OK();
}
if (subshape.rank() <= 1) {
return Status::OK();
}
TF_ASSIGN_OR_RETURN(
const LogicalBuffer* buffer,
constraints->points_to_analysis().GetBufferDefinedAt(user,
shape_index));
if (constraints->BufferLayout(*buffer) == nullptr ||
!constraints->GetBufferLayoutConstraint(*buffer)->mandatory()) {
std::unique_ptr<Layout> layout = ChooseOutputLayoutFromOperandLayout(
operand_constraint.shape_layout().layout(), user,
operand_constraint.operand_no());
if (layout != nullptr) {
TF_RETURN_IF_ERROR(constraints->SetBufferLayout(
*layout, *buffer,
/*mandatory=*/user->opcode() == HloOpcode::kReduce,
/*dfs=*/InstructionShouldPropagateDepthFirst(*user)));
}
}
return Status::OK();
}));
return Status::OK();
}
Status LayoutAssignment::PropagateBufferConstraintToOperands(
const BufferLayoutConstraint& buffer_constraint,
LayoutConstraints* constraints) {
VLOG(5) << "PropagateBufferConstraintToOperands: "
<< buffer_constraint.ToString();
const LogicalBuffer& buffer = buffer_constraint.buffer();
const HloInstruction* instruction = buffer.instruction();
if (IsAtMostRank1(instruction->shape())) {
return Status::OK();
}
for (int64 operand_no = 0; operand_no < instruction->operand_count();
++operand_no) {
const HloInstruction* operand = instruction->operand(operand_no);
if (IsAtMostRank1(operand->shape())) {
continue;
}
if (!instruction_can_change_layout_func_(instruction)) {
// Copy the layout to the operand.
if (buffer.IsArray() && operand->shape().IsArray() &&
operand->shape().rank() ==
LayoutUtil::MinorToMajor(buffer_constraint.layout()).size()) {
TF_RETURN_IF_ERROR(constraints->SetArrayOperandLayout(
buffer_constraint.layout(), instruction, operand_no,
/*mandatory=*/true));
}
} else {
if (!buffer.IsTopLevel() ||
!instruction->operand(operand_no)->shape().IsArray()) {
continue; // Don't touch buffers that are internal to a tuple.
}
VLOG(6) << "Propagating constraint to operand " << operand_no << " of "
<< instruction->ToShortString();
// Assign a layout if there is no constraint already.
const OperandLayoutConstraint* constraint =
constraints->GetOperandLayoutConstraint(instruction, operand_no);
if (constraint == nullptr || !constraint->mandatory()) {
std::unique_ptr<Layout> operand_layout =
ChooseOperandLayoutFromOutputLayout(buffer_constraint.layout(),
instruction, operand_no);
if (operand_layout != nullptr) {
TF_RETURN_IF_ERROR(constraints->SetArrayOperandLayout(
*operand_layout, instruction, operand_no, /*mandatory=*/false,
/*dfs=*/InstructionShouldPropagateDepthFirst(*instruction)));
}
} else {
VLOG(6) << "Operand already has a constraint "
<< constraint->ToString();
}
}
}
return Status::OK();
}
Status LayoutAssignment::PropagateBufferConstraint(
const BufferLayoutConstraint& buffer_constraint,
LayoutConstraints* constraints) {
// Only propagate array layouts.
const LogicalBuffer& buffer = buffer_constraint.buffer();
if (!buffer.IsArray()) {
return Status::OK();
}
TF_RETURN_IF_ERROR(
PropagateBufferConstraintToUses(buffer_constraint, constraints));
return PropagateBufferConstraintToOperands(buffer_constraint, constraints);
}
Status LayoutAssignment::PropagateBufferConstraintToUses(
const BufferLayoutConstraint& buffer_constraint,
LayoutConstraints* constraints) {
const LogicalBuffer& buffer = buffer_constraint.buffer();
TF_RET_CHECK(buffer.IsArray());
// Propagate the layout to all array uses of the logical buffer. This skips
// uses of the buffer where the buffer is the element of a tuple.
for (const auto& user_operand_no :
GetArrayUsesOfBuffer(buffer, constraints->points_to_analysis())) {
const HloInstruction* user = user_operand_no.first;
int64 operand_no = user_operand_no.second;
// Only add an operand constraint if the user does not forward the buffer
// because this case is not handled is SetOperandLayout.
if (constraints->OperandLayout(user, operand_no) == nullptr &&
!constraints->OperandBufferForwarded(user, operand_no)) {
TF_RETURN_IF_ERROR(constraints->SetArrayOperandLayout(
buffer_constraint.layout(), user, operand_no, /*mandatory=*/false));
}
}
return Status::OK();
}
Status LayoutAssignment::PropagateResultConstraint(
const ResultLayoutConstraint& layout_constraint,
LayoutConstraints* constraints) {
// Propagate the use constraint of the root instruction up to the logical
// buffers which make up the result.
return PropagateUseConstraintToDefs(
layout_constraint.shape_layout(),
constraints->computation()->root_instruction(), constraints);
}
namespace {
// Infers the layout of the array at the given index in the given instruction's
// output using points-to analysis. Precondition: The given instruction must
// not produce this array value (that is, the array is forwarded from the
// instruction's operands).
StatusOr<Layout> InferArrayLayout(
const TuplePointsToAnalysis& points_to_analysis,
HloInstruction* instruction, const ShapeIndex& index) {
// This function should only be called for array shapes which don't yet have
// layouts.
const Shape& subshape = ShapeUtil::GetSubshape(instruction->shape(), index);
TF_RET_CHECK(subshape.IsArray());
TF_RET_CHECK(!subshape.has_layout());
// The instruction should not define the buffer at this index.
TF_RET_CHECK(
!points_to_analysis.InstructionDefinesBufferAtIndex(instruction, index))
<< instruction->ToString();
const auto& source_buffers =
points_to_analysis.GetPointsToSet(instruction).element(index);
TF_RET_CHECK(!source_buffers.empty());
// Verify the layout is the same for every LogicalBuffer which this location
// ('instruction' and 'index') points to.
const Layout* first_buffer_layout = nullptr;
for (const LogicalBuffer* source_buffer : source_buffers) {
if (!source_buffer->shape().has_layout()) {
// This should not happen because we've assigned layouts to all
// instructions preceding this one.
return InternalError("LogicalBuffer %s does not have a layout",
source_buffer->ToString());
}
if (first_buffer_layout == nullptr) {
first_buffer_layout = &source_buffer->shape().layout();
} else if (!LayoutUtil::Equal(source_buffer->shape().layout(),
*first_buffer_layout)) {
// The points-to set is ambiguous for this index and the different source
// buffers have different layouts. This case is possible in valid XLA
// computations because we do not propagate BufferLayoutConstraints to all
// LogicalBuffers which may alias the constrained LogicalBuffer at some
// point in the computation.
return FailedPrecondition(
"Array at index {%s} in instruction %s aliases buffers %s "
"and %s which have different layouts",
absl::StrJoin(index, ","), instruction->name(),
source_buffers[0]->ToString(), source_buffer->ToString());
}
}
return *first_buffer_layout;
}
// For fusion instructions, set the layout of each fused parameter instruction
// to match the layout of its corresponding fusion instruction operand. Also,
// set the layout of the fused root to match the layout of the fusion
// instruction itself.
Status SetFusionLayouts(HloInstruction* fusion) {
TF_RET_CHECK(fusion->opcode() == HloOpcode::kFusion);
for (auto* fused_instruction :
fusion->fused_instructions_computation()->MakeInstructionPostOrder()) {
if (fused_instruction->opcode() == HloOpcode::kParameter) {
const HloInstruction* fusion_operand =
fusion->operand(fused_instruction->parameter_number());
DCHECK(ShapeUtil::Compatible(fusion_operand->shape(),
fused_instruction->shape()));
TF_RETURN_IF_ERROR(LayoutUtil::CopyLayoutBetweenShapes(
fusion_operand->shape(), fused_instruction->mutable_shape()));
} else if (fused_instruction == fusion->fused_expression_root()) {
// The layout of the root of the fused expression must match the fusion
// instruction layout.
DCHECK(
ShapeUtil::Compatible(fusion->shape(), fused_instruction->shape()));
TF_RETURN_IF_ERROR(LayoutUtil::CopyLayoutBetweenShapes(
fusion->shape(), fused_instruction->mutable_shape()));
} else if (fused_instruction->opcode() == HloOpcode::kGetTupleElement) {
// A GTE inherits its layout from its operand (which should ultimately be
// a parameter).
TF_RETURN_IF_ERROR(LayoutUtil::CopyLayoutBetweenShapes(
fused_instruction->operand(0)->shape().tuple_shapes(
fused_instruction->tuple_index()),
fused_instruction->mutable_shape()));
} else if (fused_instruction->opcode() == HloOpcode::kConstant) {
// Give constants the layout of their literal.
TF_RETURN_IF_ERROR(LayoutUtil::CopyLayoutBetweenShapes(
fused_instruction->literal().shape(),
fused_instruction->mutable_shape()));
} else if (fused_instruction->opcode() == HloOpcode::kInfeed) {
// Nop; leave the infeed layout alone.
} else if (fusion->fusion_kind() != HloInstruction::FusionKind::kCustom) {
// Other instructions don't have layouts inside of fusion nodes.
// But do not clear layouts for other instructions in custom fusion nodes.
LayoutUtil::ClearLayout(fused_instruction->mutable_shape());
}
}
return Status::OK();
}
} // namespace
Status LayoutAssignment::AssignLayouts(const LayoutConstraints& constraints,
HloComputation* computation) {
VLOG(2) << "Assigning layouts to computation: " << computation->name();
XLA_VLOG_LINES(2, computation->ToString());
XLA_VLOG_LINES(2, constraints.ToString());
for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) {
LayoutUtil::ClearLayout(instruction->mutable_shape());
// Create a copy of an operand if the operand instruction's layout does not
// match the use constraint (OperandLayoutConstraint).
for (int64 operand_no = 0; operand_no < instruction->operand_count();
++operand_no) {
const ShapeLayout* operand_layout =
constraints.OperandLayout(instruction, operand_no);
if (operand_layout != nullptr) {
TF_RETURN_IF_ERROR(CopyOperandIfLayoutsDiffer(*operand_layout,
instruction, operand_no));
}
}
// Set the layouts of the array shapes this instruction defines as indicated
// by the respective BufferLayoutConstraints. Any array shapes in the output
// of the instruction which are not defined by the instruction (eg, array
// elements in a Tuple instruction) will be assigned below via inference.
for (const LogicalBuffer* buffer :
constraints.points_to_analysis().GetBuffersDefinedByInstruction(
instruction)) {
if (!buffer->shape().IsArray()) {
continue;
}
TF_RET_CHECK(buffer->instruction() == instruction);
const Layout* buffer_layout = constraints.BufferLayout(*buffer);
TF_RET_CHECK(buffer_layout != nullptr);
if (instruction->opcode() == HloOpcode::kConstant) {
// For constants, we also need to change the layout of the internal
// literal.
instruction->RelayoutConstant(*buffer_layout, buffer->index());
} else {
Shape* buffer_subshape = ShapeUtil::GetMutableSubshape(
instruction->mutable_shape(), buffer->index());
*buffer_subshape->mutable_layout() = *buffer_layout;
}
}
// Any remaining layouts in the output of the instruction must be
// inferrable using points-to analysis.
TF_RETURN_IF_ERROR(ShapeUtil::ForEachMutableSubshapeWithStatus(
instruction->mutable_shape(),
[instruction, &constraints](Shape* subshape, const ShapeIndex& index) {
if (subshape->has_layout() || !subshape->IsArray()) {
return Status::OK();
}
// Set Layout of subshape to match layout of LogicalBuffer which
// produces it.
TF_ASSIGN_OR_RETURN(*subshape->mutable_layout(),
InferArrayLayout(constraints.points_to_analysis(),
instruction, index));
return Status::OK();
}));
// Fusion instructions require some layouts to be set on fused instructions
// inside the fusion instruction.
if (instruction->opcode() == HloOpcode::kFusion) {
TF_RETURN_IF_ERROR(SetFusionLayouts(instruction));
}
// Execute extra verification step once the layout has been finalized.
TF_RETURN_IF_ERROR(Verify(instruction));
// Shape must be valid.
TF_RETURN_IF_ERROR(
ShapeUtil::ValidateShapeWithOptionalLayout(instruction->shape()));
// Verify all layouts in the shape have been set.
TF_RET_CHECK(LayoutUtil::HasLayout(instruction->shape()));
}
return Status::OK();
}
Status LayoutAssignment::CalculateComputationLayout(
HloComputation* computation) {
ComputationLayout computation_layout(computation->ComputeProgramShape(),
/*ignore_layouts=*/false);
InsertOrDie(&computation_layouts_, computation, computation_layout);
VLOG(2) << " Calculated ComputationLayout = "
<< computation_layout.ToString();
return Status::OK();
}
Status LayoutAssignment::ClearComputationLayouts(HloComputation* computation) {
// Clear existing layouts of the instructions. All layouts must be assigned
// by the LayoutAssignment pass, except for those on parameters, the
// computation result, and a couple special cases. The former two are
// specified in computation_layout. Clearing the layouts here avoids hiding
// potential bugs in the layout assignment pass that may accidentally use the
// existing layout.
for (HloInstruction* instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kBitcast) {
// bitcasts are inherently layout sensitive and so a bitcast instruction
// present in the IR before layout assignment is a bug.
return InternalError(
"Unexpected bitcast operation seen during layout assignment: %s.",
instruction->ToString());
}
// Some instructions carry mandatory layouts in their shape.
if (instruction->opcode() != HloOpcode::kInfeed &&
!IsLayoutConstrainedCustomCall(instruction)) {
LayoutUtil::ClearLayout(instruction->mutable_shape());
}
}
return Status::OK();
}
Status LayoutAssignment::RunOnComputation(
ComputationLayout* computation_layout,
const TuplePointsToAnalysis& points_to_analysis,
HloComputation* computation,
ChannelLayoutConstraints* channel_constraints) {
VLOG(2) << "LayoutAssignment::RunOnComputation(" << computation->name()
<< ")";
// Must be run before clearing layouts.
TF_RETURN_IF_ERROR(BuildHostChannelConstraints(computation));
TF_RETURN_IF_ERROR(ClearComputationLayouts(computation));
if (computation_layout != nullptr) {
auto it = computation_layouts_.find(computation);
if (it == computation_layouts_.end()) {
VLOG(2) << " New ComputationLayout = " << computation_layout->ToString();
computation_layouts_.emplace(computation, *computation_layout);
} else {
TF_RET_CHECK(computation_layout == &it->second ||
computation_layout == entry_computation_layout_);
VLOG(2) << " Existing ComputationLayout = "
<< computation_layout->ToString();
}
} else {
VLOG(2) << " No ComputationLayout specified (will be calculated)";
}
// Construct LayoutConstraints with all layout constraints of the computation.
LayoutConstraints constraints(points_to_analysis, computation);
// Add constraints required for correctness on all backends (eg, entry
// parameter layout constraints).
TF_RETURN_IF_ERROR(AddMandatoryConstraints(
computation_layout, channel_constraints, computation, &constraints));
// Add any backend-specific constraints.
TF_RETURN_IF_ERROR(AddBackendConstraints(&constraints));
// Propagates layouts from mandatory and backend constraints.
TF_RETURN_IF_ERROR(PropagateConstraints(&constraints));
// Prior to applying default layouts, we take note of all HLO instructions
// which lack a layout constraint.
for (LogicalBuffer::Id buffer_id : constraints.unconstrained_buffer_ids()) {
unconstrained_layout_instructions_.insert(
points_to_analysis.GetBuffer(buffer_id).instruction());
}
// While any unconstrained buffers remain, pick an arbitrary buffer, give it a
// layout and propagate the change.
while (!constraints.unconstrained_buffer_ids().empty()) {
int unconstrained_count = constraints.unconstrained_buffer_ids().size();
// Arbitrarily pick the first unconstrained buffer and give it the default
// layout (or the literal layout, in case of constants). By construction
// unconstrained_buffers() has a stable sort based on LogicalBuffer::Id.
const LogicalBuffer& buffer = points_to_analysis.GetBuffer(
*constraints.unconstrained_buffer_ids().begin());
const HloInstruction* instruction = buffer.instruction();
Layout new_layout =
instruction->opcode() == HloOpcode::kConstant
? ShapeUtil::GetSubshape(instruction->literal().shape(),
buffer.index())
.layout()
: LayoutUtil::GetDefaultLayoutForShape(buffer.shape());
TF_RETURN_IF_ERROR(constraints.SetBufferLayout(new_layout, buffer,
/*mandatory=*/false));
TF_RETURN_IF_ERROR(PropagateConstraints(&constraints));
// To verify progress has been made, check that the number of unconstrained
// buffers has been reduced.
CHECK_LT(constraints.unconstrained_buffer_ids().size(),
unconstrained_count);
}
// All logical buffers should have constraints at this point. All that
// remains is assign the constraints to the buffers and infer layouts for
// aliased buffers.
TF_RETURN_IF_ERROR(AssignLayouts(constraints, computation));
// If the computation layout wasn't specified, now it is the time to compute
// it according to the parameters and root instruction layouts.
// This allows the first pass through this API to record the best flowing
// layout to parameters and root instruction.
if (computation_layout == nullptr) {
TF_RETURN_IF_ERROR(CalculateComputationLayout(computation));
}
// Record the layouts assigned for any communication ops in
// channel_constraints so that they are constrained for future modules.
if (channel_constraints != nullptr) {
TF_RETURN_IF_ERROR(
ConstrainChannelLayouts(computation, channel_constraints));
}
// Copy the root instruction's result if its layout does not match the result
// layout constraint.
if (constraints.ResultLayout() != nullptr &&
!constraints.ResultLayout()->MatchesLayoutInShape(
computation->root_instruction()->shape())) {
TF_ASSIGN_OR_RETURN(
HloInstruction * new_root,
CreateCopyWithNewLayout(constraints.ResultLayout()->shape(),
computation->root_instruction()));
computation->set_root_instruction(new_root);
}
return Status::OK();
}
Status LayoutAssignment::ConstrainChannelLayouts(
HloComputation* computation,
ChannelLayoutConstraints* channel_constraints) {
auto get_channel_constraints = [&](const HloInstruction* instruction) {
return IsHostSendRecv(instruction) ? &host_channel_constraints_
: channel_constraints;
};
// We go through the kRecvDone before. These must either impose their layout,
// or find a matching one already existing (ConstrainChannel() returns
// nullptr).
for (HloInstruction* instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kRecvDone) {
const Layout* layout =
get_channel_constraints(instruction)
->ConstrainChannel(
instruction->channel_id(),
ShapeUtil::GetSubshape(instruction->shape(), {0}).layout());
TF_RET_CHECK(layout == nullptr)
<< instruction->ToString()
<< " cannot constrain layout as it was set to "
<< LayoutUtil::HumanString(*layout);
}
}
// After that we go through the kSend. These are likely going to have a kCopy
// as operand (otherwise we add it), so in case the constrained layout does
// not match, we can change the kCopy layout (and the kSend one as well).
for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) {
if (instruction->opcode() == HloOpcode::kSend) {
HloInstruction* operand = instruction->mutable_operand(0);
const Layout* layout = get_channel_constraints(instruction)
->ConstrainChannel(instruction->channel_id(),
operand->shape().layout());
if (layout != nullptr) {
// We found an already constrained layout which does not match the one
// the kSend wants to impose. Either add a new kCopy, or use the
// existing one to marshal the correct shape.
Shape shape = operand->shape();
*shape.mutable_layout() = *layout;
if (operand->opcode() != HloOpcode::kCopy) {
HloInstruction* copy = operand->parent()->AddInstruction(
HloInstruction::CreateUnary(shape, HloOpcode::kCopy, operand));
RegisterAddedCopy(copy);
SetupCopiedInstruction(*operand, copy, {});
TF_RETURN_IF_ERROR(instruction->ReplaceOperandWith(0, copy));
operand = copy;
} else {
*operand->mutable_shape() = shape;
}
Shape* send_shape =
ShapeUtil::GetMutableSubshape(instruction->mutable_shape(), {0});
*send_shape = shape;
}
} else if (instruction->IsCrossModuleAllReduce()) {
const Layout* layout =
get_channel_constraints(instruction)
->ConstrainChannel(instruction->all_reduce_id().value(),
instruction->shape().layout());
if (layout != nullptr) {
// We found an already constrained layout which does not match the one
// the channel wants to impose. Either add a new kCopy, or use the
// existing one to marshal the correct shape.
HloInstruction* operand = instruction->mutable_operand(0);
Shape shape = operand->shape();
*shape.mutable_layout() = *layout;
if (operand->opcode() != HloOpcode::kCopy) {
HloInstruction* copy = operand->parent()->AddInstruction(
HloInstruction::CreateUnary(shape, HloOpcode::kCopy, operand));
RegisterAddedCopy(copy);
SetupCopiedInstruction(*operand, copy, {});
TF_RETURN_IF_ERROR(instruction->ReplaceOperandWith(0, copy));
operand = copy;
} else {
*operand->mutable_shape() = shape;
}
*instruction->mutable_shape() = shape;
}
}
}
return Status::OK();
}
Status LayoutAssignment::PropagateComputationLayouts(
HloComputation* computation, ComputationLayout* computation_layout) {
ComputationLayout computed_computation_layout(
computation->ComputeProgramShape(),
/*ignore_layouts=*/false);
for (int64 i = 0; i < computed_computation_layout.parameter_count(); ++i) {
ShapeLayout* param_layout = computation_layout->mutable_parameter_layout(i);
if (!param_layout->LayoutIsSet()) {
VLOG(4) << "Assigning layout to parameter " << i << " of computation "
<< computation->name() << ": "
<< computed_computation_layout.parameter_layout(i).ToString();
*param_layout = computed_computation_layout.parameter_layout(i);
} else {
TF_RET_CHECK(computed_computation_layout.parameter_layout(i) ==
*param_layout);
}
}
ShapeLayout* result_layout = computation_layout->mutable_result_layout();
if (!result_layout->LayoutIsSet()) {
VLOG(4) << "Assigning result layout of computation " << computation->name()
<< ": " << computed_computation_layout.result_layout().ToString();
*result_layout = computed_computation_layout.result_layout();
} else {
TF_RET_CHECK(computed_computation_layout.result_layout() == *result_layout);
}
return Status::OK();
}
StatusOr<bool> LayoutAssignment::Run(HloModule* module) {
VLOG(2) << "Running layout assignment on module " << module->name();
XLA_VLOG_LINES(3, module->ToString());
if (VLOG_IS_ON(10)) {
hlo_graph_dumper::DumpGraph(*module->entry_computation(),
"before layout assignment",
module->config().debug_options());
}
TF_RETURN_IF_ERROR(Init());
// Verify computation layout is sane.
const HloComputation* entry = module->entry_computation();
TF_RET_CHECK(entry_computation_layout_->parameter_count() ==
entry->num_parameters());
for (int64 i = 0; i < entry->num_parameters(); ++i) {
TF_RET_CHECK(
ShapeUtil::Compatible(entry_computation_layout_->parameter_shape(i),
entry->parameter_instruction(i)->shape()));
}
TF_RET_CHECK(ShapeUtil::Compatible(entry_computation_layout_->result_shape(),
entry->root_instruction()->shape()));
// We do two passes. The first one we pass a nullptr ComputationLayout to
// the RunOnComputation() calls (for non entry computations), and we register
// the ComputationLayout which are naturally flowing in DFS fashion to the
// parameters and root instruction.
// Walking in DFS mode though, means that we can end up with incorrect layouts
// when seen from an outer instruction, which has across-computation
// constraints to impose.
// For example, the kWhile instruction needs to enforce the same layouts for
// the parameters and root of the body, as well as the condition parameters.
// Similarly, the kConditional instruction needs to enforce the same layouts
// for the root of the true and false computations.
// So in the first pass, while allowing the layouts to flow to parameters and
// root, we also fix up the eventually inconsistent ComputationLayout, which
// will be then made mandatory by the second pass.
for (int64 i = 0; i < 2; ++i) {
VLOG(5) << "Running " << (i == 0 ? "un" : "") << "constrained pass";
TF_RETURN_IF_ERROR(ClearPreviousPassSideEffects(module));
TF_ASSIGN_OR_RETURN(auto points_to_analysis,
TuplePointsToAnalysis::Run(module));
for (auto* computation : module->MakeComputationPostOrder()) {
if (computation->IsFusionComputation()) {
continue;
}
if (computation == module->entry_computation()) {
TF_RETURN_IF_ERROR(RunOnComputation(
entry_computation_layout_, *points_to_analysis,
module->entry_computation(), channel_layout_constraints_));
} else {
ComputationLayout* computation_layout =
(i == 0) ? nullptr : &FindOrDie(computation_layouts_, computation);
TF_RETURN_IF_ERROR(RunOnComputation(computation_layout,
*points_to_analysis, computation,
channel_layout_constraints_));
}
}
}
TF_RETURN_IF_ERROR(PropagateComputationLayouts(module->entry_computation(),
entry_computation_layout_));
TF_RETURN_IF_ERROR(CheckLayouts(module));
VLOG(3) << "After layout assignment:";
XLA_VLOG_LINES(3, module->ToString());
if (VLOG_IS_ON(10)) {
hlo_graph_dumper::DumpGraph(*module->entry_computation(),
"after layout assignment",
module->config().debug_options());
}
// All layouts are reset then reassigned by this pass.
return true;
}
/* static */
bool LayoutAssignment::InstructionCanChangeLayout(
const HloInstruction* instruction) {
switch (instruction->opcode()) {
case HloOpcode::kAbs:
case HloOpcode::kAdd:
case HloOpcode::kAddDependency:
case HloOpcode::kAnd:
case HloOpcode::kAtan2:
case HloOpcode::kBitcastConvert:
case HloOpcode::kCeil:
case HloOpcode::kClamp:
case HloOpcode::kClz:
case HloOpcode::kComplex:
case HloOpcode::kConcatenate:
case HloOpcode::kConditional:
case HloOpcode::kConvert:
case HloOpcode::kCos:
case HloOpcode::kAllReduce:
case HloOpcode::kAllToAll:
case HloOpcode::kCollectivePermute:
case HloOpcode::kDivide:
case HloOpcode::kDynamicSlice:
case HloOpcode::kDynamicUpdateSlice:
case HloOpcode::kEq:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kFft:
case HloOpcode::kFloor:
case HloOpcode::kGe:
case HloOpcode::kGt:
case HloOpcode::kImag:
case HloOpcode::kIsFinite:
case HloOpcode::kLe:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kLt:
case HloOpcode::kMap:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kMultiply:
case HloOpcode::kNe:
case HloOpcode::kNegate:
case HloOpcode::kNot:
case HloOpcode::kOr:
case HloOpcode::kXor:
case HloOpcode::kPad:
case HloOpcode::kPower:
case HloOpcode::kReal:
case HloOpcode::kReducePrecision:
case HloOpcode::kReduceWindow:
case HloOpcode::kRemainder:
case HloOpcode::kReverse:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kRsqrt:
case HloOpcode::kScatter:
case HloOpcode::kSelect:
case HloOpcode::kSelectAndScatter:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSlice:
case HloOpcode::kSort:
case HloOpcode::kSqrt:
case HloOpcode::kSubtract:
case HloOpcode::kTanh:
case HloOpcode::kTriangularSolve:
case HloOpcode::kCholesky:
case HloOpcode::kTupleSelect:
case HloOpcode::kWhile:
return false;
case HloOpcode::kBatchNormGrad:
case HloOpcode::kBatchNormInference:
case HloOpcode::kBatchNormTraining:
case HloOpcode::kBitcast:
case HloOpcode::kBroadcast:
case HloOpcode::kCall:
case HloOpcode::kConstant:
case HloOpcode::kConvolution:
case HloOpcode::kCopy:
case HloOpcode::kCustomCall:
case HloOpcode::kDomain:
case HloOpcode::kDot:
case HloOpcode::kFusion:
case HloOpcode::kGather:
case HloOpcode::kGetTupleElement:
case HloOpcode::kInfeed:
case HloOpcode::kIota:
case HloOpcode::kOutfeed:
case HloOpcode::kParameter:
case HloOpcode::kRecv:
case HloOpcode::kRecvDone:
case HloOpcode::kReduce:
case HloOpcode::kReplicaId:
case HloOpcode::kReshape:
case HloOpcode::kRng:
case HloOpcode::kSend:
case HloOpcode::kSendDone:
case HloOpcode::kAfterAll:
case HloOpcode::kTrace:
case HloOpcode::kTranspose:
case HloOpcode::kTuple:
case HloOpcode::kGetDimensionSize:
return true;
}
}
/* static */
bool LayoutAssignment::IsAtMostRank1(const Shape& shape) {
if (shape.IsArray()) {
return shape.rank() <= 1;
}
return absl::c_all_of(shape.tuple_shapes(), [](const Shape& subshape) {
return IsAtMostRank1(subshape);
});
}
Status LayoutAssignment::Init() {
computation_layouts_.clear();
*entry_computation_layout_ = saved_entry_computation_layout_;
return Status::OK();
}
Status LayoutAssignment::ClearPreviousPassSideEffects(HloModule* module) {
VLOG(5) << "Clearing previous side effects";
// Clear all the copies which have been added, and all the related
// instructions (like GTE and tuples).
int64 removed_copies = 0;
for (HloComputation* computation : module->computations()) {
for (HloInstruction* instruction :
computation->MakeInstructionPostOrder()) {
if (instruction->opcode() == HloOpcode::kCopy &&
added_copies_.contains(instruction)) {
VLOG(5) << "Removing added copy: " << instruction->ToString();
TF_RETURN_IF_ERROR(
instruction->ReplaceAllUsesWith(instruction->mutable_operand(0)));
TF_RETURN_IF_ERROR(computation->RemoveInstruction(instruction));
++removed_copies;
}
}
}
added_copies_.clear();
unconstrained_layout_instructions_.clear();
if (removed_copies > 0) {
TupleSimplifier tuple_simplifier;
HloDCE dce;
TF_RETURN_IF_ERROR(tuple_simplifier.Run(module).status());
TF_RETURN_IF_ERROR(dce.Run(module).status());
}
ResetChannelConstraints();
return Status::OK();
}
Status LayoutAssignment::AddCopyForOperand(HloInstruction* instruction,
int64 operand_number) {
HloInstruction* operand = instruction->mutable_operand(operand_number);
if (operand->opcode() != HloOpcode::kCopy || operand->user_count() > 1) {
HloInstruction* copy =
instruction->parent()->AddInstruction(HloInstruction::CreateUnary(
operand->shape(), HloOpcode::kCopy, operand));
SetupCopiedInstruction(*operand, copy, {});
LayoutUtil::ClearLayout(copy->mutable_shape());
TF_RETURN_IF_ERROR(instruction->ReplaceOperandWith(operand_number, copy));
}
return Status::OK();
}
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
30f1ff9f9e6b340a24902d811bc4b721c6bb05bf | a4673b42192da9e6d51a9084b3c531afc5f3d019 | /remote-client/vnc_server.h | 39f860753afac747af63139bfc7a3363c755626d | [
"Apache-2.0"
] | permissive | kimocoder/android-keyboard-gadget | 273efa67ac3e2d4c12a427ba8157a795176f1c1c | 224bbfb7c1892d860f88c9a077a82e5ed9d64003 | refs/heads/master | 2020-05-09T17:38:51.063128 | 2020-03-07T13:41:26 | 2020-03-07T13:41:26 | 181,317,808 | 0 | 2 | Apache-2.0 | 2020-03-07T13:41:28 | 2019-04-14T14:03:41 | C | UTF-8 | C++ | false | false | 244 | h | #ifndef __VNC_SERVER_H__
#define __VNC_SERVER_H__
#include <string>
void vncServerStart();
void vncServerStop();
bool vncServerRunning();
std::string vncServerGetIpAddress();
void vncServerDrawVideoBuffer(int x, int y, int w, int h);
#endif
| [
"x.pelya.x@gmail.com"
] | x.pelya.x@gmail.com |
79c4977aaa498e5689ba745558cd45974c4118cf | f5fd0e6c9200e3585627044f10d33fb17501d900 | /pileup.h | da99083687f43fef5573889a1df5e0f707759851 | [
"MIT"
] | permissive | SeqOne/vt | 34f6e932e6da0b837a057a7a0bd547bfb95cc25c | f1c49a74a33052d7bc84ba9a29b3a0ed1eeeb278 | refs/heads/master | 2020-06-09T18:15:00.810586 | 2020-03-31T13:29:54 | 2020-03-31T13:29:54 | 193,482,841 | 0 | 0 | MIT | 2020-03-31T13:29:55 | 2019-06-24T10:18:53 | C | UTF-8 | C++ | false | false | 9,676 | h | /* The MIT License
Copyright (c) 2015 Adrian Tan <atks@umich.edu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef PILEUP_H
#define PILEUP_H
#include "utils.h"
#include "hts_utils.h"
#include "variant.h"
/**
* Contains sufficient statistic for a position in the pileup.
*/
class SoftClipInfo
{
public:
uint32_t no;
std::vector<float> mean_quals;
std::vector<char> strands;
/**
* Constructor.
*/
SoftClipInfo() { clear();};
/**
* Clears the soft clipped information.
*/
void clear();
};
/**
* Contains sufficient statistic for a position in the pileup.
*/
class PileupPosition
{
public:
//reference base
char R;
//alternative bases
uint32_t X[16];
//for deletions and insertions with anchor R
std::map<std::string, uint32_t> D;
std::map<std::string, uint32_t> I;
std::map<std::string, SoftClipInfo> J;
std::map<std::string, SoftClipInfo> K;
//occurence of all observations for internal bases
uint32_t N;
//number of bases that fail quality cutoff
uint32_t F;
//occurence of all observations for bases on the ends of reads
//this is important as indels have to be contained within a read
//so if this is not distinguished, the relative proportion of
//the reads containing the indel out of reads that could contain
//that indel is will be underestimated.
uint32_t E;
//base qualities for reference allele
std::vector<uint32_t> REF_Q;
//base qualities for alternative allele
std::vector<uint32_t> ALT_Q;
//to count evidences
//SNPs - X[A] / (N+E)
//INDELs - #indel / N
//SCLIPS -
/**
* Constructor.
*/
PileupPosition();
/**
* Clears pileup position.
*/
void clear();
/**
* Returns true if pileup record is cleared.
*/
bool is_cleared();
/**
* Prints pileup position.
*/
void print();
/**
* Prints pileup position.
*/
void print(uint32_t gpos1);
};
/**
* A pileup for variant discovery.
* This only contains the pileup structure with
* methods to access and modify the pileup.
*
* This pileup only works for a single chromosome
* the user has to update the pileup and clear it
* if the chromosome is changed.
*
* Transferring the pileup information to a VCF
* file is delegated to a class that uses this
* structure.
*/
class Pileup
{
public:
uint32_t buffer_size;
uint32_t buffer_size_mask;
uint32_t window_size;
std::vector<PileupPosition> P;
int32_t tid;
uint32_t beg0, end0; // index of P for the start and end position in 0 base coordinates
// beg0 points to the beginning of the pileup
// end0 points to the position after the end of the pileup
//
// end0
// |
// V
// +--+--+--+--+--+--+--+--+--+--+--+--+
// | | | | | | | | | | | | |
// +--+--+--+--+--+--+--+--+--+--+--+--+
// ^
// |
// beg0
//
// when beg0==end0, pileup is empty
// gbeg1 - is the coordinate of the genome position that beg0 represents.
//
// invariance: pileup is always continuous
//
// how do we check if
//
//for use if we need to update the reference.
std::string chrom;
//where should we check if a read is from another chromosome?
//genome position at the beginning of the pileup
uint32_t gbeg1;
int32_t debug;
faidx_t *fai;
public:
/**
* Constructor.
*
* @k - size of pileup is 2^k
*/
Pileup(uint32_t k=10, uint32_t window_size=256);
/**
* Overloads subscript operator for accessing pileup positions.
*/
PileupPosition& operator[] (const int32_t i);
/**
* Returns the maximum size of the pileup.
*/
uint32_t max_size();
/**
* Returns the size of the pileup.
*/
uint32_t size();
/**
* Checks if buffer is empty
*/
bool is_empty();
/**
* Set reference fasta file.
*/
void set_reference(std::string& ref_fasta_file);
/**
* Set debug.
*/
void set_debug(int32_t debug);
/**
* Sets tid.
*/
void set_tid(uint32_t tid);
/**
* Gets tid.
*/
uint32_t get_tid();
/**
* Sets chrom.
*/
void set_chrom(std::string& chrom);
/**
* Gets chrom.
*/
std::string get_chrom();
/**
* Gets window_size.
*/
uint32_t get_window_size();
/**
* Sets gbeg1.
*/
void set_gbeg1(uint32_t gbeg1);
/**
* Gets gbeg1.
*/
uint32_t get_gbeg1();
/**
* Gets gend1.
*/
uint32_t get_gend1();
/**
* Sets beg0.
*/
void set_beg0(uint32_t beg0);
/**
* Sets end0.
*/
void set_end0(uint32_t end0);
/**
* Gets the index of the first element.
*/
uint32_t begin();
/**
* Gets the index of the last element.
*/
uint32_t end();
/**
* Increments i by 1 circularly.
*/
uint32_t inc(uint32_t i);
/**
* Increments beg0 by 1.
*/
void inc_beg0();
/**
* Increments end0 by 1.
*/
void inc_end0();
/**
* Increments index i by j cyclically.
*/
uint32_t inc(uint32_t i, uint32_t j);
/**
* Converts gpos1 to index in P.
*/
uint32_t g2i(uint32_t gpos1);
/**
* Returns the difference between 2 buffer positions
*/
uint32_t diff(uint32_t i, uint32_t j);
/**
* Updates a stretch of aligned bases identified by M in the cigar string.
*/
void add_M(uint32_t gpos1, uint32_t spos0, uint32_t len, uint8_t* seq, uint8_t* qual, uint32_t snp_baseq_cutoff);
/**
* Updates a stretch of deleted bases identified by D in the cigar string.
*/
void add_D(uint32_t gpos1, uint32_t len);
/**
* Updates an occurence of an insertion.
*/
void add_I(uint32_t gpos1, std::string& ins, uint32_t rpos1);
/**
* Updates the occurence of a left soft clip.
*/
void add_LSC(uint32_t gpos1, std::string& alt, float mean_qual, char strand);
/**
* Updates the occurence of a right soft clip.
*/
void add_RSC(uint32_t gpos1, std::string& alt, float mean_qual, char strand);
/**
* Inserts a stretch of reference padding bases at the 5' prime end of the buffer from gpos1 if gpos1 is behind the start of the pileup.
*
* @gpos1 - 1 based genome position
*/
void add_5prime_padding(uint32_t gpos1);
/**
* Inserts a stretch of reference padding bases at the 3' prime end of the buffer to gpos1 if gpos1 is ahead of end of pileup.
*
* @gpos1 - 1 based genome position
*/
void add_3prime_padding(uint32_t gpos1);
/**
* Updates a stretch of reference bases.
*/
void add_ref(uint32_t gpos1, uint32_t spos0, uint32_t len, uint8_t* seq);
/**
* Updates an occurence of a SNP.
*/
void add_snp(uint32_t gpos1, char ref, char alt, uint8_t qual, uint32_t baseq_cutoff);
/**
* Updates an occurence of a deletion.
*/
void add_del(uint32_t gpos1, std::string& del);
/**
* Updates an occurence of an insertion.
*/
void add_ins(uint32_t gpos1, std::string& ins, uint32_t rpos1);
/**
* Updates the occurence of a left soft clip.
*/
void add_lsclip(uint32_t gpos1, std::string& alt, float mean_qual, char strand);
/**
* Updates the occurence of a right soft clip.
*/
void add_rsclip(uint32_t gpos1, std::string& alt, float mean_qual, char strand);
/**
* Updates the last aligned base in a read.
*
* @gpos1 - starting genome position
*/
void update_read_end(uint32_t gpos1);
/**
* Checks if a variant is normalized.
*/
bool is_normalized(char ref, std::string& indel);
/**
* Normalize a biallelic variant.
*
* If N exists in either of the alleles, the normalization does not proceed.
*/
void normalize(std::string& chrom, uint32_t& pos1, std::string& ref, std::string& alt);
/**
* Converts base to bam encoding.
*/
uint32_t base2index(char base);
/**
* Get a base.
*/
char get_base(std::string& chrom, uint32_t& pos1);
/**
* Get a sequence. User have to free the char* returned.
*/
char* get_sequence(std::string& chrom, uint32_t pos1, uint32_t len);
/**
* Print pileup state.
*/
void print_state();
/**
* Print pileup state extent.
*/
void print_state_extent();
};
#endif | [
"atks@umich.edu"
] | atks@umich.edu |
2243b5912150e612c2d3c69192bb2cee0bd35f77 | 8101e76fd3e2bcfe6846ac41c54a1b4dbe217c39 | /string/3009 能和本大爷玩游戏的竟然只有你一个 大模拟+基础数据结构list.cpp | 6523e7d0887a7698f6a4d000f1e178cab83a61a1 | [] | no_license | Great-designer/BUAA-OJ-Project | c28c03ea1cf48d255a43ef8d6ae08697968d1c96 | fa74d757c084697634f67eb44967f22d81e4dd81 | refs/heads/master | 2023-08-03T04:45:06.582109 | 2023-07-26T16:34:46 | 2023-07-26T16:34:46 | 253,685,963 | 61 | 12 | null | 2021-08-19T04:46:07 | 2020-04-07T04:21:54 | Makefile | UTF-8 | C++ | false | false | 4,009 | cpp | #include<iostream>
#include<list>
#include<string>
using namespace std;
struct Card
{
enum color {Spade, Heart, Diamond, Club, Joker, JOKER};
color c;//花色
int num;//点数 Joker = 14 JOKER = 15
Card(color cc = Spade,int n = 0)
{
num = n, c = cc;
}
Card(const string& in)
{
if (in.size() <= 1) c = Spade, num = 0;
else
{
if (in[0] == 'j')c = Joker, num = 14;
else if (in[0] == 'J')c = JOKER, num = 15;
else
{
switch (in[0])
{
case 'H':
c = Heart;
break;
case 'D':
c = Diamond;
break;
case 'S':
c = Spade;
break;
case 'C':
c = Club;
break;
default:
break;
}
string n = in.substr(1, in.size() - 1);
if (n[0] == 'A')num = 1;
else if (n[0] == 'J')num = 11;
else if (n[0] == 'Q')num = 12;
else if (n[0] == 'K')num = 13;
else num = stoi(n);
}
}
}
void print(string& s)
{
if (c == Joker)s += "joker";
else if (c == JOKER)s += "JOKER";
else
{
switch (c)
{
case Heart:
s += "H";
break;
case Diamond:
s += "D";
break;
case Spade:
s += "S";
break;
case Club:
s += "C";
break;
default:
break;
}
if (num == 1)s += "A";
else if (num == 11)s += "J";
else if (num == 12)s += "Q";
else if (num == 13)s += "K";
else s += to_string(num);
}
}
};
char flag;
list<Card>Z, Kurisu, Public;
int counter[16];//点数记牌器
string tmp;
string res[10010];
int q;
int k;
void read()
{
for (int i = 0; i < 27; ++i)
cin >> tmp, Z.push_back(Card(tmp));
for (int i = 0; i < 27; ++i)
cin >> tmp, Kurisu.push_back(Card(tmp));
}
void print(int cnt)
{
for (list<Card>::iterator it = Z.begin(); it != Z.end(); ++it)
{
(*it).print(res[cnt]);
list<Card>::iterator tmp = it;
++tmp;
res[cnt] += (tmp == Z.end() ? "\n" : " ");
}
for (list<Card>::iterator it = Kurisu.begin(); it != Kurisu.end(); ++it)
{
(*it).print(res[cnt]);
list<Card>::iterator tmp = it;
++tmp;
res[cnt] += (tmp == Kurisu.end() ? "\n" : " ");
}
}
void parsePublic(int num, bool flag)
{
//检查点数num是否超标, 根据flag决定被谁收走
if (counter[num] >= 2)
{
while (counter[num])
{
Card tmp = Public.back();
Public.pop_back();
counter[tmp.num]--;
if (flag)Z.push_back(tmp);
else Kurisu.push_back(tmp);
}
}
}
bool getZtoKurisu(int cnt)
{
//Z要给Kurisu这么多牌,成功给牌返回true,空了返回false,并且确定结果
while (cnt--)
{
if (Z.empty())
{
flag = 2;
return false;
}
Card tmp = Z.front();
Z.pop_front();
Kurisu.push_back(tmp);
}
return true;
}
bool getKurisutoZ(int cnt)
{
while (cnt--)
{
if (Kurisu.empty())
{
flag = 1;
return false;
}
Card tmp = Kurisu.front();
Kurisu.pop_front();
Z.push_back(tmp);
}
return true;
}
bool getZtoPublic()
{
if(Z.empty())
{
flag = 2;
return false;
}
Card tmp = Z.front();
Public.push_back(tmp);
counter[tmp.num]++;
Z.pop_front();
if (tmp.c == Card::Joker)getKurisutoZ(3);
else if (tmp.c == Card::JOKER)getKurisutoZ(5);
else parsePublic(tmp.num, 1);
return true;
}
bool getKurisutoPublic()
{
if(Kurisu.empty())
{
flag = 1;
return false;
}
Card tmp = Kurisu.front();
Public.push_back(tmp);
counter[tmp.num]++;
Kurisu.pop_front();
if (tmp.c == Card::Joker)getZtoKurisu(3);
else if (tmp.c == Card::JOKER)getZtoKurisu(5);
else parsePublic(tmp.num, 0);
return true;
}
void simulate(bool flag)
{
if (flag)getZtoPublic();
else getKurisutoPublic();
}
int main()
{
read();
for (int i = 0; i < 10010; ++i)res[i] = "";
print(0);
flag = 0;
bool turn = true;//Z先手
for (int i = 1; i <= 10000; ++i)
{
if (flag != 0)
res[i] = (flag == 1 ? "Zwin\n" : "Kurisuwin\n");
else
{
simulate(turn);
turn = 1 - turn;
if (Z.empty())flag = 2;
else if (Kurisu.empty())flag = 1;
if (flag == 0)print(i);
else res[i] = (flag == 1 ? "Zwin\n" : "Kurisuwin\n");
}
}
cin >> q;
while (q--)
{
cin >> k;
cout << res[k];
}
} | [
"63183399+Great-designer@users.noreply.github.com"
] | 63183399+Great-designer@users.noreply.github.com |
16dcd9a0dd408ddc7c58ecc048bde94c2502bffb | cdea6386099926d40361b6ec7ac7f665f227cd0f | /src/Turbo/opencl/Turbo_pardec.cpp | 0a18fe89bd0e6e1fb1cd774526c1db37caee4e6f | [] | no_license | troore/ParWiBench | 1451dfc868a4e0eb1e1c95c0b39e4c1c82175b42 | a674dd2bd26c7c35353aee8fa96a179208aaf8bb | refs/heads/master | 2020-05-17T00:43:37.015065 | 2015-07-20T13:29:22 | 2015-07-20T13:29:22 | 19,258,868 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 29,353 | cpp |
#include <stdio.h>
#include <cstring>
#include <limits>
#include "ParTurbo.h"
#include <time.h>
#include "CL/cl.h"
#include "clutil.h"
#include "meas.h"
#define PROGRAM_FILE "./parturbo.ocl"
#define KERNEL_FUNC "par_log_decoder_kernel"
#define NUM_KERNELS 2
float recv_syst1[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float recv_syst2[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float recv_parity1[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float recv_parity2[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float Le12[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float Le12_int[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float Le21[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float Le21_int[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float L[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float old_alpha1[N_STATES * MAX_SUBBLOCKS_NUM];
float old_beta1[N_STATES * MAX_SUBBLOCKS_NUM];
float new_alpha1[N_STATES * MAX_SUBBLOCKS_NUM];
float new_beta1[N_STATES * MAX_SUBBLOCKS_NUM];
float old_alpha2[N_STATES * MAX_SUBBLOCKS_NUM];
float old_beta2[N_STATES * MAX_SUBBLOCKS_NUM];
float new_alpha2[N_STATES * MAX_SUBBLOCKS_NUM];
float new_beta2[N_STATES * MAX_SUBBLOCKS_NUM];
#define MAX_SUBBLOCK_ALPHA_LEN_NORMAL ((BLOCK_SIZE / NUM_SUBBLOCKS_PER_BLOCK) + 1)
#define MAX_SUBBLOCK_ALPHA_LEN_EXTRA ((BLOCK_SIZE / NUM_SUBBLOCKS_PER_BLOCK) + N_TAIL + 1)
// local memory for log_decoder_kernel
float l_alpha[N_STATES * MAX_SUBBLOCK_ALPHA_LEN_EXTRA];
float l_beta[N_STATES * MAX_SUBBLOCK_ALPHA_LEN_EXTRA];
float l_gamma[N_STATES * 2 * MAX_SUBBLOCK_ALPHA_LEN_EXTRA];
float l_denom[MAX_SUBBLOCK_ALPHA_LEN_EXTRA];
float l_apriori[MAX_SUBBLOCK_ALPHA_LEN_EXTRA - 1];
#define MAX_ALPHA_LEN ((BLOCK_SIZE / NUM_SUBBLOCKS_PER_BLOCK) + 1) * MAX_SUBBLOCKS_NUM + (MAX_SUBBLOCKS_NUM / NUM_SUBBLOCKS_PER_BLOCK) * N_TAIL
float alpha[];
void par_turbo_decoding(LTE_PHY_PARAMS *lte_phy_params, float *pInpData, int *pOutBits, int n_sfr, int n_iters)
{
int out_fr_len;
int blk_sz;
int n_blk;
int subblk_sz;
int n_subblk;
int n_subblk_per_blk;
int i, j, k;
int cur_blk_len;
int out_bit_offset;
int syst_block_offset, parity_block_offset;
/*
float recv_syst1[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float recv_syst2[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float recv_parity1[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float recv_parity2[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
*/
/*
* FIXME: number of sub-blocks is an important parameter for this parallel version
* */
n_subblk_per_blk = NUM_SUBBLOCKS_PER_BLOCK;
subblk_sz = BLOCK_SIZE / n_subblk_per_blk; // tailed bits shouldn't be ignored
out_fr_len = lte_phy_params->td_out_buf_sz; // output length of a codeword after turbo decoding
n_blk = n_sfr * ((out_fr_len + BLOCK_SIZE - 1) / BLOCK_SIZE);
blk_sz = BLOCK_SIZE;
n_subblk = n_sfr * ((out_fr_len + subblk_sz - 1) / subblk_sz); // number of subblocks
set_generator_polynomials(g_gens, N_GENS, CST_LEN);
out_bit_offset = 0;
syst_block_offset = 0;
parity_block_offset = 0;
for (i = 0; i < n_blk; i++)
{
/*
* FIXME: for simplicity, lengths of blocks are same with each other for now
* */
cur_blk_len = BLOCK_SIZE;
// data part
for (j = 0; j < cur_blk_len; j++)
{
recv_syst1[syst_block_offset + j] = pInpData[out_bit_offset++];
// printf("%.0f", recv_syst1[syst_block_offset + j]);
for (k = 0; k < N_GENS - 1; k++)
{
recv_parity1[parity_block_offset + j * (N_GENS - 1) + k] = pInpData[out_bit_offset++];
// printf("%.0f", recv_parity1[parity_block_offset + j * (N_GENS - 1) + k]);
}
for (k = 0; k < N_GENS - 1; k++)
{
recv_parity2[parity_block_offset + j * (N_GENS - 1) + k] = pInpData[out_bit_offset++];
// printf("%.0f", recv_parity2[parity_block_offset + j * (N_GENS - 1) + k]);
}
}
// printf("\n");
// first tail
for (j = 0; j < N_TAIL; j++)
{
recv_syst1[syst_block_offset + cur_blk_len + j] = pInpData[out_bit_offset++];
// printf("%.0f", recv_syst1[syst_block_offset + cur_blk_len + j]);
for (k = 0; k < N_GENS - 1; k++)
{
recv_parity1[parity_block_offset + (cur_blk_len + j) * (N_GENS - 1) + k] = pInpData[out_bit_offset++];
// printf("%.0f", recv_parity1[parity_block_offset + (cur_blk_len + j) * (N_GENS - 1) + k]);
}
}
// printf("\n");
// second tail
for (j = 0; j < N_TAIL; j++)
{
recv_syst2[syst_block_offset + cur_blk_len + j] = pInpData[out_bit_offset++];
// printf("%.0f", recv_syst2[syst_block_offset + cur_blk_len + j]);
for (k = 0; k < N_GENS - 1; k++)
{
recv_parity2[parity_block_offset + (cur_blk_len + j) * (N_GENS - 1) + k] = pInpData[out_bit_offset++];
// printf("%.0f", recv_parity2[parity_block_offset + (cur_blk_len + j) * (N_GENS - 1) + k]);
}
}
// printf("\n");
syst_block_offset += (cur_blk_len + N_TAIL);
parity_block_offset += (N_GENS - 1) * (cur_blk_len + N_TAIL);
}
#ifdef GOLD
gold_decode_all_subblocks(recv_syst1, recv_syst2, recv_parity1, recv_parity2,
subblk_sz, n_subblk, n_subblk_per_blk, pOutBits, n_iters);
#else
par_decode_all_subblocks(recv_syst1, recv_syst2, recv_parity1, recv_parity2,
subblk_sz, n_subblk, n_subblk_per_blk, pOutBits, n_iters);
#endif
}
template <typename T>
void par_interleaver(void (*pInterleaver)(T *, T *, int), T *in, T *out,
int n_subblk, int subblk_sz, int n_subblk_per_blk)
{
int stride;
int subblk_offset = 0;
int i;
for (i = 0; i < n_subblk; i++)
{
pInterleaver(in + subblk_offset, out + subblk_offset, subblk_sz);
if ((i % n_subblk_per_blk) == (n_subblk_per_blk - 1))
stride = subblk_sz + N_TAIL;
else
stride = subblk_sz;
subblk_offset += stride;
}
}
template <typename T>
void par_interleaver(void (*pInterleaver)(T *, T *, int), T *in, T *out, int n_blk, int blk_sz)
{
int subblk_offset = 0;
int i;
for (i = 0; i < n_blk; i++)
{
pInterleaver(in + i * (blk_sz + N_TAIL), out + i * (blk_sz + N_TAIL), blk_sz);
}
}
void gold_decode_all_subblocks(float *recv_syst1,
float *recv_syst2,
float *recv_parity1,
float *recv_parity2,
int subblk_sz,
int n_subblk,
int n_subblk_per_blk,
int *decoded_bits,
int n_iters)
{
int subblk_offset;
int output_bit_offset;
int n_blk;
int blk_sz;
int i, j, k, s;
int stride;
/*
float Le12[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float Le12_int[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float Le21[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float Le21_int[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
float L[MAX_SUBFRAME_BUFFER_SIZE * N_TURBO_IN_MAX];
*/
/*
float old_alpha1[N_STATES * MAX_SUBBLOCKS_NUM];
float old_beta1[N_STATES * MAX_SUBBLOCKS_NUM];
float new_alpha1[N_STATES * MAX_SUBBLOCKS_NUM];
float new_beta1[N_STATES * MAX_SUBBLOCKS_NUM];
float old_alpha2[N_STATES * MAX_SUBBLOCKS_NUM];
float old_beta2[N_STATES * MAX_SUBBLOCKS_NUM];
float new_alpha2[N_STATES * MAX_SUBBLOCKS_NUM];
float new_beta2[N_STATES * MAX_SUBBLOCKS_NUM];
*/
memset(Le21, 0, (n_subblk * subblk_sz + (n_subblk / n_subblk_per_blk) * N_TAIL) * sizeof(float));
memset(Le12_int, 0, (n_subblk * subblk_sz + (n_subblk / n_subblk_per_blk) * N_TAIL) * sizeof(float));
n_blk = n_subblk / n_subblk_per_blk;
blk_sz = subblk_sz * n_subblk_per_blk;
// par_interleaver(internal_interleaver, recv_syst1, recv_syst2, n_subblk, subblk_sz, n_subblk_per_blk);
par_interleaver(internal_interleaver, recv_syst1, recv_syst2, n_blk, blk_sz);
// do the first alpha initialization
for (i = 0; i < n_subblk; i++)
{
if (/*0 == i*/ 0 == (i % n_subblk_per_blk))
{
for (s = 0; s < N_STATES; s++)
{
if (0 == s)
{
old_alpha1[i * N_STATES + s] = 1.0;
old_alpha2[i * N_STATES + s] = 1.0;
}
else
{
old_alpha1[i * N_STATES + s] = 0.0;
old_alpha2[i * N_STATES + s] = 0.0;
}
}
}
else
{
for (s = 0; s < N_STATES; s++)
{
old_alpha1[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
old_alpha2[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
}
}
}
// do the first beta initialization
for (i = 0; i < n_subblk; i++)
{
if (/*(n_subblk - 1) == i*/ (n_subblk_per_blk - 1) == (i % n_subblk_per_blk))
{
for (s = 0; s < N_STATES; s++)
{
if (0 == s)
{
old_beta1[i * N_STATES + s] = 1.0;
old_beta2[i * N_STATES + s] = 1.0;
}
else
{
old_beta1[i * N_STATES + s] = 0.0;
old_beta2[i * N_STATES + s] = 0.0;
}
}
}
else
{
for (s = 0; s < N_STATES; s++)
{
old_beta1[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
old_beta2[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
}
}
}
// do the iterative decoding, kernel part
for (k = 0; k < /*MAX_ITERATIONS*/ n_iters; k++)
{
// printf("%d:\n", n_iters);
gold_log_decoder_kernel(recv_syst1, recv_parity1, Le21, Le12, n_subblk, subblk_sz, n_subblk_per_blk, old_alpha1, old_beta1, new_alpha1, new_beta1);
#ifdef DEBUG
printf("Le12:\n");
for (i = 0; i < subblk_sz; i++)
printf("%.0f", Le12[i]);
printf("\n");
for (i = subblk_sz; i < 2 * subblk_sz + 3; i++)
printf("%.0f", Le12[i]);
printf("\n");
#endif
for (i = 0; i < n_subblk; i++)
{
if (i % n_subblk_per_blk != 0)
{
for (s = 0; s < N_STATES; s++)
{
old_alpha1[i * N_STATES + s] = new_alpha1[i * N_STATES + s];
// old_beta1[i * N_STATES + s] = new_beta1[i * N_STATES + s];
}
}
}
for (i = 0; i < n_subblk; i++)
{
if (i % n_subblk_per_blk != (n_subblk_per_blk - 1))
{
for (s = 0; s < N_STATES; s++)
{
// old_alpha1[i * N_STATES + s] = new_alpha1[i * N_STATES + s];
old_beta1[i * N_STATES + s] = new_beta1[i * N_STATES + s];
}
}
}
// par_interleaver(internal_interleaver, Le12, Le12_int, n_subblk, subblk_sz, n_subblk_per_blk);
par_interleaver(internal_interleaver, Le12, Le12_int, n_blk, blk_sz);
gold_log_decoder_kernel(recv_syst2, recv_parity2, Le12_int, Le21_int, n_subblk, subblk_sz, n_subblk_per_blk, old_alpha2, old_beta2, new_alpha2, new_beta2);
#ifdef DEBUG
printf("Le21_int:\n");
for (i = 0; i < subblk_sz; i++)
printf("%.0f", Le21_int[i]);
printf("\n");
for (i = subblk_sz; i < 2 * subblk_sz + 3; i++)
printf("%.0f", Le21_int[i]);
printf("\n");
#endif
for (i = 0; i < n_subblk; i++)
{
if (i % n_subblk_per_blk != 0)
{
for (s = 0; s < N_STATES; s++)
{
old_alpha2[i * N_STATES + s] = new_alpha2[i * N_STATES + s];
// old_beta2[i * N_STATES + s] = new_beta2[i * N_STATES + s];
}
}
}
for (i = 0; i < n_subblk; i++)
{
if (i % n_subblk_per_blk != (n_subblk_per_blk - 1))
{
for (s = 0; s < N_STATES; s++)
{
// old_alpha2[i * N_STATES + s] = new_alpha2[i * N_STATES + s];
old_beta2[i * N_STATES + s] = new_beta2[i * N_STATES + s];
}
}
}
// par_interleaver(internal_deinterleaver, Le21_int, Le21, n_subblk, subblk_sz, n_subblk_per_blk);
par_interleaver(internal_deinterleaver, Le21_int, Le21, n_blk, blk_sz);
#ifdef DEBUG
printf("Le21:\n");
for (i = 0; i < subblk_sz; i++)
printf("%.0f", Le21[i]);
printf("\n");
for (i = subblk_sz; i < 2 * subblk_sz + 3; i++)
printf("%.0f", Le21[i]);
printf("\n");
#endif
}
subblk_offset = 0;
output_bit_offset = 0;
for (i = 0; i < n_subblk; i++)
{
if ((i % n_subblk_per_blk) == (n_subblk_per_blk - 1))
stride = subblk_sz + N_TAIL;
else
stride = subblk_sz;
for (j = subblk_offset; j < subblk_offset + subblk_sz; j++)
{
L[output_bit_offset] = recv_syst1[j] + Le21[j] + Le12[j];
decoded_bits[output_bit_offset] = (L[output_bit_offset] > 0.0) ? 1 : -1;
output_bit_offset++;
}
subblk_offset += stride;
}
}
void gold_log_decoder_kernel(float *recv_syst,
float *recv_parity,
float *apriori,
float *extrinsic,
int n_subblk,
int subblk_sz,
int n_subblk_per_blk,
float *old_alpha,
float *old_beta,
float *new_alpha,
float *new_beta)
{
float nom, den, temp0, temp1, exp_temp0, exp_temp1, rp;
int i, j, s0, s1, k, kk, l, s, s_prim, s_prim0, s_prim1;
int alpha_len;
int subblk_offset;
int stride;
Lc = 1.0;
// gold_log_decoder_kernel(recv_syst, recv_parity, apriori, extrinsic, alpha, beta, n_subblk, subblk_sz, n_subblk_per_blk);
com_log = max_log;
/**
* tid = get_thread_id();
* i = tid / N_STATES;
* s_prim = tid % N_STATES;
*/
for (i = 0; i < n_subblk; i++)
{
subblk_offset = (i / n_subblk_per_blk) * (BLOCK_SIZE + N_TAIL) + (i % n_subblk_per_blk) * subblk_sz;
if ((i % n_subblk_per_blk) == (n_subblk_per_blk - 1))
stride = subblk_sz + N_TAIL;
else
stride = subblk_sz;
// Initiate alpha and beta
for (s = 0; s < N_STATES; s++)
{
l_alpha[s * (stride + 1) + 0] = old_alpha[i * N_STATES + s];
l_beta[s * (stride + 1) + stride] = old_beta[i * N_STATES + s];
}
// Synchronize
for (k = 0; k <= stride; k++)
{
l_denom[k] = -LOG_INFINITY;
}
for (k = 0; k < stride; k++)
{
l_apriori[k] = apriori[subblk_offset + k];
}
// Calculate gamma
for (k = 1; k <= stride; k++)
{
kk = k - 1;
for (s_prim = 0; s_prim < N_STATES; s_prim++)
{
exp_temp0 = 0.0;
exp_temp1 = 0.0;
for (j = 0; j < (N_GENS - 1); j++)
{
rp = recv_parity[subblk_offset * (N_GENS - 1) + kk * (N_GENS - 1) + j];
if (0 == g_output_parity[s_prim * (N_GENS - 1) * 2 + j * 2 + 0])
{
exp_temp0 += rp;
}
else
{
exp_temp0 -= rp;
}
if (0 == g_output_parity[s_prim * (N_GENS - 1) * 2 + j * 2 + 1])
{
exp_temp1 += rp;
}
else
{
exp_temp1 -= rp;
}
}
l_gamma[(2 * s_prim + 0) * (stride + 1) + k] = 0.5 * ((l_apriori[kk] + recv_syst[subblk_offset + kk]) + exp_temp0);
// printf("%f\t", l_gamma[(2 * s_prim + 0) * (stride + 1) + k]);
l_gamma[(2 * s_prim + 1) * (stride + 1) + k] = -0.5 * ((l_apriori[kk] + recv_syst[subblk_offset + kk]) - exp_temp1);
// printf("%f\n", l_gamma[(2 * s_prim + 1) * (stride + 1) + k]);
}
}
// Calculate alpha, going forward through the trellis
for (k = 1; k <= stride; k++)
{
for (s = 0; s < N_STATES; s++)
{
s_prim0 = g_rev_state_trans[s * 2 + 0];
s_prim1 = g_rev_state_trans[s * 2 + 1];
temp0 = l_alpha[s_prim0 * (stride + 1) + k - 1] + l_gamma[(2 * s_prim0 + 0) * (stride + 1) + k];
temp1 = l_alpha[s_prim1 * (stride + 1) + k - 1] + l_gamma[(2 * s_prim1 + 1) * (stride + 1) + k];
l_alpha[s * (stride + 1) + k] = com_log(temp0, temp1);
l_denom[k] = com_log(l_alpha[s * (stride + 1) + k], l_denom[k]);
}
// Normalization of alpha
for (s = 0; s < N_STATES; s++)
{
l_alpha[s * (stride + 1) + k] -= l_denom[k];
}
}
// Calculate beta going backward in the trellis
for (k = stride; k >= /*2*/ 1; k--)
{
for (s_prim = 0; s_prim < N_STATES; s_prim++)
{
s0 = g_state_trans[s_prim * 2 + 0];
s1 = g_state_trans[s_prim * 2 + 1];
temp0 = l_beta[s0 * (stride + 1) + k] + l_gamma[(2 * s_prim + 0) * (stride + 1) + k];
temp1 = l_beta[s1 * (stride + 1) + k] + l_gamma[(2 * s_prim + 1) * (stride + 1) + k];
l_beta[s_prim * (stride + 1) + k - 1] = com_log(temp0, temp1);
}
// Normalization of beta
for (s = 0; s < N_STATES; s++)
{
l_beta[s * (stride + 1) + k - 1] -= l_denom[k];
}
}
// Calculate extrinsic output for each bit
for (k = 1; k <= stride; k++)
{
kk = k - 1;
nom = -LOG_INFINITY;
den = -LOG_INFINITY;
for (s_prim = 0; s_prim < N_STATES; s_prim++)
{
s0 = g_state_trans[s_prim * 2 + 0];
s1 = g_state_trans[s_prim * 2 + 1];
exp_temp0 = 0.0;
exp_temp1 = 0.0;
for (j = 0; j < (N_GENS - 1); j++)
{
rp = recv_parity[subblk_offset * (N_GENS - 1) + kk * (N_GENS - 1) + j];
if (0 == g_output_parity[s_prim * (N_GENS - 1) * 2 + j * 2 + 0])
{
exp_temp0 += rp;
}
else
{
exp_temp0 -= rp;
}
if (0 == g_output_parity[s_prim * (N_GENS - 1) * 2 + j * 2 + 1])
{
exp_temp1 += rp;
}
else
{
exp_temp1 -= rp;
}
}
nom = com_log(nom, l_alpha[s_prim * (stride + 1) + kk] + 0.5 * exp_temp0 + l_beta[s0 * (stride + 1) + k]);
den = com_log(den, l_alpha[s_prim * (stride + 1) + kk] + 0.5 * exp_temp1 + l_beta[s1 * (stride + 1) + k]);
}
extrinsic[subblk_offset + kk] = nom - den;
/* Use new alpha and beta to avoid global synchronization */
if (/*i != (n_subblk - 1)*/ (i % n_subblk_per_blk) != (n_subblk_per_blk - 1))
{
for (s = 0; s < N_STATES; s++)
{
new_alpha[(i + 1) * N_STATES + s] = l_alpha[s * (stride + 1) + stride];
}
}
if (/*i != 0*/ (i % n_subblk_per_blk) != 0)
{
for (s = 0; s < N_STATES; s++)
{
new_beta[(i - 1) * N_STATES + s] = l_beta[s * (stride + 1) + /*1*/ 0];
}
}
}
}
}
void par_decode_all_subblocks(float *recv_syst1,
float *recv_syst2,
float *recv_parity1,
float *recv_parity2,
int subblk_sz,
int n_subblk,
int n_subblk_per_blk,
int *decoded_bits,
int n_iters)
{
cl_int _err;
cl_device_id device;
cl_context context;
cl_command_queue queue;
cl_program program;
cl_kernel par_log_decoder_kernel;
cl_mem recv_syst_buffer, recv_parity_buffer;
// cl_mem recv_syst2_buffer, recv_parity2_buffer;
cl_mem Le12_buffer, Le12_int_buffer, Le21_buffer, Le21_int_buffer, L_buffer;
// cl_mem old_alpha1_buffer, old_beta1_buffer, new_alpha1_buffer, new_beta1_buffer;
// cl_mem old_alpha2_buffer, old_beta2_buffer, new_alpha2_buffer, new_beta2_buffer;
cl_mem old_alpha_buffer, old_beta_buffer, new_alpha_buffer, new_beta_buffer;
cl_mem g_output_parity_buffer, g_state_trans_buffer, g_rev_state_trans_buffer;
size_t global_size, local_size;
int n_blk, blk_sz;
int syst_len, alpha_len;
int local_syst_len, local_alpha_len;
int n_subblks_per_work_group;
int i, s, k;
device_query();
syst_len = n_subblk * subblk_sz + (n_subblk / n_subblk_per_blk) * N_TAIL;
alpha_len = syst_len + n_subblk * 1;
/*
* FIXME: n_subblks_per_work_group should be a parameter to this function
*/
n_subblks_per_work_group = n_subblk_per_blk;
global_size = N_STATES * n_subblk;
local_size = N_STATES * n_subblks_per_work_group;
local_syst_len = (BLOCK_SIZE / n_subblk_per_blk) * n_subblks_per_work_group + (n_subblks_per_work_group / n_subblk_per_blk) * N_TAIL;
local_alpha_len = local_syst_len + 1 * n_subblks_per_work_group;
memset(Le21, 0, (n_subblk * subblk_sz + (n_subblk / n_subblk_per_blk) * N_TAIL) * sizeof(float));
memset(Le12_int, 0, (n_subblk * subblk_sz + (n_subblk / n_subblk_per_blk) * N_TAIL) * sizeof(float));
n_blk = n_subblk / n_subblk_per_blk;
blk_sz = subblk_sz * n_subblk_per_blk;
/* Initiate kernel arguments */
// par_interleaver(internal_interleaver, recv_syst1, recv_syst2, n_subblk, subblk_sz, n_subblk_per_blk);
par_interleaver(internal_interleaver, recv_syst1, recv_syst2, n_blk, blk_sz);
// do the first alpha initialization
for (i = 0; i < n_subblk; i++)
{
if (/*0 == i*/ 0 == (i % n_subblk_per_blk))
{
for (s = 0; s < N_STATES; s++)
{
if (0 == s)
{
old_alpha1[i * N_STATES + s] = 1.0;
old_alpha2[i * N_STATES + s] = 1.0;
}
else
{
old_alpha1[i * N_STATES + s] = 0.0;
old_alpha2[i * N_STATES + s] = 0.0;
}
}
}
else
{
for (s = 0; s < N_STATES; s++)
{
old_alpha1[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
old_alpha2[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
}
}
}
// do the first beta initialization
for (i = 0; i < n_subblk; i++)
{
if ((n_subblk - 1) == i /*(n_subblk_per_blk - 1) == (i % n_subblk_per_blk)*/)
{
for (s = 0; s < N_STATES; s++)
{
if (0 == s)
{
old_beta1[i * N_STATES + s] = 1.0;
old_beta2[i * N_STATES + s] = 1.0;
}
else
{
old_beta1[i * N_STATES + s] = 0.0;
old_beta2[i * N_STATES + s] = 0.0;
}
}
}
else
{
for (s = 0; s < N_STATES; s++)
{
old_beta1[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
old_beta2[i * N_STATES + s] = 1.0 / (N_STATES * 1.0);
}
}
}
// Create device, context, program, kernel, queue
// cl_params_init(PROGRAM_FILE, KERNEL_FUNC);
/* Create a device and context */
device = create_device();
context = clCreateContext(NULL, 1, &device, NULL, NULL, &_err);
/* Build the program */
program = build_program(context, device, PROGRAM_FILE);
/* Create kernel */
for (i = 0; i < NUM_KERNELS; i++)
par_log_decoder_kernel[i] = clCreateKernel(program, KERNEL_FUNC, &_err);
/* Create a command queue */
queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &_err);
// Create buffer(s)
recv_syst_buffer[0] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, syst_len * sizeof(float), recv_syst1, &_err));
recv_parity_buffer[0] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, syst_len * sizeof(float), recv_parity1, &_err));
recv_syst_buffer[1] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, syst_len * sizeof(float), recv_syst2, &_err));
recv_parity_buffer[1] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, syst_len * sizeof(float), recv_parity2, &_err));
Le12_buffer = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, syst_len * sizeof(float), NULL, &_err));
Le12_int_buffer = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, syst_len * sizeof(float), NULL, &_err));
Le21_buffer = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, syst_len * sizeof(float), NULL, &_err));
Le21_int_buffer = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, syst_len * sizeof(float), NULL, &_err));
L_buffer = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, syst_len * sizeof(float), NULL, &_err));
for (i = 0; i < NUM_KERNELS; i++)
{
old_alpha_buffer[i] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY, N_STATES * n_subblk * sizeof(float), NULL, &_err));
old_beta_buffer[i] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY, N_STATES * n_subblk * sizeof(float), NULL, &_err));
new_alpha_buffer[i] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY, N_STATES * n_subblk * sizeof(float), NULL, &_err));
new_beta_buffer[i] = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_ONLY, N_STATES * n_subblk * sizeof(float), NULL, &_err));
}
g_output_parity_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, N_STATES * (N_GENS - 1) * 2 * sizeof(int), g_output_parity, &_err);
g_state_trans_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, N_STATES * 2 * sizeof(int), g_state_trans, &_err);
g_rev_state_trans_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, N_STATES * 2 * sizeof(int), g_rev_state_trans, &_err);
/* Set kernel arguments */
for (i = 0; i < NUM_KERNELS; i++)
{
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 0, sizeof(cl_mem), &recv_syst_buffer[i]));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 1, sizeof(cl_mem), &recv_parity_buffer[i]));
if (0 == i)
{
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 2, sizeof(cl_mem), &Le21_buffer));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 3, sizeof(cl_mem), &Le12_buffer));
}
else
{
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 2, sizeof(cl_mem), &Le12_int_buffer));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 3, sizeof(cl_mem), &Le21_int_buffer));
}
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 4, sizeof(int), &n_subblk));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 5, sizeof(int), &subblk_sz));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 6, sizeof(int), &n_subblk_per_blk));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 7, sizeof(cl_mem), &old_alpha_buffer[i]));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 8, sizeof(cl_mem), &old_beta_buffer[i]));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 9, sizeof(cl_mem), &new_alpha_buffer[i]));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 10, sizeof(cl_mem), &new_beta_buffer[i]));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 11, sizeof(cl_mem), &g_output_parity_buffer));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 12, sizeof(cl_mem), &g_state_trans_buffer));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 13, sizeof(cl_mem), &g_rev_state_trans_buffer));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 14, N_STATES * local_alpha_len * sizeof(float), NULL));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 15, N_STATES * local_alpha_len * sizeof(float), NULL));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 16, N_STATES * 2 * local_alpha_len * sizeof(float), NULL));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 17, N_STATES * local_alpha_len * sizeof(float), NULL));
CL_CHECK(clSetKernelArg(par_log_decoder_kernel[i], 18, N_STATES * local_syst_len * sizeof(float), NULL));
}
double elapsed_time = 0.0;
cl_event prof_event;
for (k = 0; k < n_iters; k++)
{
// Input(s) for the first Log-MAP kernel
CL_CHECK(clEnqueueWriteBuffer(queue, Le21_buffer, CL_TRUE, 0, syst_len * sizeof(float), Le21, 0, NULL, NULL));
CL_CHECK(clEnqueueWriteBuffer(queue, old_alpha_buffer[0], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), old_alpha1, 0, NULL, NULL));
CL_CHECK(clEnqueueWriteBuffer(queue, old_beta_buffer[0], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), old_beta1, 0, NULL, NULL));
// Launch the first Log-MAP kernel
printf("%d\n", CL_INVALID_PROGRAM_EXECUTABLE);
printf("%d\n", CL_INVALID_COMMAND_QUEUE);
printf("%d\n", CL_INVALID_KERNEL);
printf("%d\n", CL_INVALID_CONTEXT);
printf("%d\n", CL_INVALID_KERNEL_ARGS);
printf("%d\n", CL_INVALID_WORK_DIMENSION);
printf("%d\n", CL_OUT_OF_RESOURCES);
printf("%d\n", CL_INVALID_EVENT_WAIT_LIST);
printf("%d\n", CL_MEM_OBJECT_ALLOCATION_FAILURE);
printf("%d\n", CL_OUT_OF_HOST_MEMORY);
CL_CHECK(clEnqueueNDRangeKernel(queue, par_log_decoder_kernel[0], 1, NULL, &global_size, &local_size, 0, NULL, &prof_event));
// Get output(s) of the first log-MAP kernel
CL_CHECK(clEnqueueReadBuffer(queue, Le12_buffer, CL_TRUE, 0, syst_len * sizeof(float), Le12, 0, NULL, NULL));
CL_CHECK(clEnqueueReadBuffer(queue, new_alpha_buffer[0], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), new_alpha1, 0, NULL, NULL));
CL_CHECK(clEnqueueWriteBuffer(queue, new_beta_buffer[0], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), new_beta1, 0, NULL, NULL));
// Update boundary alpha and beta for the next iteration
for (i = 0; i < n_subblk; i++)
{
if (i % n_subblk_per_blk != 0)
{
for (s = 0; s < N_STATES; s++)
{
old_alpha1[i * N_STATES + s] = new_alpha1[i * N_STATES + s];
// old_beta1[i * N_STATES + s] = new_beta1[i * N_STATES + s];
}
}
}
for (i = 0; i < n_subblk - 1; i++)
{
for (s = 0; s < N_STATES; s++)
{
// old_alpha1[i * N_STATES + s] = new_alpha1[i * N_STATES + s];
old_beta1[i * N_STATES + s] = new_beta1[i * N_STATES + s];
}
}
par_interleaver(internal_interleaver, Le12, Le12_int, n_blk, blk_sz);
// Input(s) for the second Log-MAP kernel
CL_CHECK(clEnqueueWriteBuffer(queue, Le12_int_buffer, CL_TRUE, 0, syst_len * sizeof(float), Le12_int, 0, NULL, NULL));
CL_CHECK(clEnqueueWriteBuffer(queue, old_alpha_buffer[1], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), old_alpha2, 0, NULL, NULL));
CL_CHECK(clEnqueueWriteBuffer(queue, old_beta_buffer[1], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), old_beta2, 0, NULL, NULL));
// Launch the second Log-MAP kernel
CL_CHECK(clEnqueueNDRangeKernel(queue, par_log_decoder_kernel[1], 1, NULL, &global_size, &local_size, 0, NULL, &prof_event));
// Get output(s) of the second Log-MAP kernel
CL_CHECK(clEnqueueReadBuffer(queue, Le12_int_buffer, CL_TRUE, 0, syst_len * sizeof(float), Le12_int, 0, NULL, NULL));
CL_CHECK(clEnqueueReadBuffer(queue, new_alpha_buffer[1], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), new_alpha2, 0, NULL, NULL));
CL_CHECK(clEnqueueWriteBuffer(queue, new_beta_buffer[1], CL_TRUE, 0, N_STATES * n_subblk * sizeof(float), new_beta2, 0, NULL, NULL));
for (i = 1; i < n_subblk; i++)
{
for (s = 0; s < N_STATES; s++)
{
old_alpha2[i * N_STATES + s] = new_alpha2[i * N_STATES + s];
// old_beta2[i * N_STATES + s] = new_beta2[i * N_STATES + s];
}
}
for (i = 0; i < n_subblk - 1; i++)
{
for (s = 0; s < N_STATES; s++)
{
// old_alpha2[i * N_STATES + s] = new_alpha2[i * N_STATES + s];
old_beta2[i * N_STATES + s] = new_beta2[i * N_STATES + s];
}
}
par_interleaver(internal_deinterleaver, Le21_int, Le21, n_blk, blk_sz);
}
// cl_params_release();
for (i = 0; i < NUM_KERNELS; i++)
{
clReleaseKernel(par_log_decoder_kernel[i]);
}
clReleaseProgram(program);
clReleaseCommandQueue(queue);
clReleaseContext(context);
for (i = 0; i < NUM_KERNELS; i++)
{
clReleaseMemObject(recv_syst_buffer[i]);
clReleaseMemObject(recv_parity_buffer[i]);
}
clReleaseMemObject(g_output_parity_buffer);
clReleaseMemObject(g_state_trans_buffer);
clReleaseMemObject(g_rev_state_trans_buffer);
clReleaseMemObject(Le12_buffer);
clReleaseMemObject(Le12_int_buffer);
clReleaseMemObject(Le21_buffer);
clReleaseMemObject(Le21_int_buffer);
clReleaseMemObject(L_buffer);
}
| [
"troore@gmail.com"
] | troore@gmail.com |
0d32044d900ac44c691832e06c1ca56eadb2fb19 | 00ededc414949ba7d5f9ab596b2bd4922afc5b7c | /Client/UIContainer.cpp | 26df5fe8595df0f608aaac021a8e86f2c136df2a | [] | no_license | bkuker/DiceNet | b41863f67f3305e35835e06b318c68d22cacd529 | 267d5b500b97300737cbf07eaa2a90f7ac23a757 | refs/heads/master | 2016-08-11T20:35:41.873400 | 2016-01-10T20:26:46 | 2016-01-10T20:26:46 | 49,384,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | cpp | // UIContainer.cpp: implementation of the UIContainer class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "UIContainer.h"
#include "Context.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
UIContainer::UIContainer(DXSystem* dxs):
UIElement(dxs),
focusE(NULL),
bg(NULL)
{
}
UIContainer::~UIContainer()
{
}
void UIContainer::add(UIElement* e)
{
children.insert(e);
}
void UIContainer::remove(UIElement* e)
{
std::set<UIElement*>::iterator i = children.begin();
for(;i != children.end(); i++ ){
if ((*i) == e){
children.erase(i);
return;
}
}
}
void UIContainer::setBG(UIElement* _bg)
{
bg = _bg;
}
UIElement* UIContainer::getBG()
{
return bg;
}
void UIContainer::render(Context *c){
c->m_mspWorld->Push();
c->m_mspWorld->MultMatrixLocal( transform() );
pd3dDevice->SetTransform( D3DTS_WORLD, c->m_mspWorld->GetTop() );
if ( bg != NULL )
bg->render(c);
draw();
std::set<UIElement*>::iterator i = children.begin();
for(;i != children.end(); i++ ){
(*i)->render(c);
}
c->m_mspWorld->Pop();
}
void UIContainer::getFocus( D3DXVECTOR3 pos )
{
D3DXMATRIX m;
D3DXMatrixInverse( &m, NULL, transform() );
D3DXVec3TransformCoord( &pos, &pos, &m );
std::set<UIElement*>::iterator i = children.begin();
for(;i != children.end(); i++ ){
UIElement* e = (*i);
if ( e->checkPos(pos) ){
if ( e != focusE ){
if (focusE != NULL )
focusE->looseFocus();
e->getFocus(pos);
focusE = e;
}
} else if ( e == focusE ) {
e->looseFocus();
focusE = NULL;
}
}
}
void UIContainer::looseFocus()
{
}
void UIContainer::mouseEvent(UIMouseButton b, UIMouseEvent e)
{
if ( focusE != NULL ){
focusE->mouseEvent(b, e);
}
}
void UIContainer::keyEvent(WPARAM k, UI_KEY_EVENT e)
{
if ( focusE != NULL ){
focusE->keyEvent(k, e);
}
}
void UIContainer::character(char c)
{
if ( focusE != NULL ){
focusE->character(c);
}
}
| [
"bkuker@martellotech.com"
] | bkuker@martellotech.com |
fd920e9880fa191ef4c5d86e44974b15ffbfe9af | 19a163edf035161158173b376cc29d9e4d74e31d | /code/calculator/source/calculator/main.cpp | 519914baa6ffeaf6e6153ec130b9e185d7b63ebd | [] | no_license | czeslavo/fibers-case-study | 2d42cdcd471c894a55ecbfef200bffb7d5494689 | e834faca41249e8ab5cc4f0fcda7bdff45011314 | refs/heads/master | 2021-03-27T10:47:38.651195 | 2018-01-02T20:09:15 | 2018-01-02T20:09:15 | 105,758,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #include <iostream>
int main(int argc, char* argv[])
{
std::cout << "2 + 2 = 4\n";
}
| [
"czeslavo@gmail.com"
] | czeslavo@gmail.com |
24ca3fbc2cf51539d6378f2ec73f595c4b40cec8 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /extensions/common/features/json_feature_provider_source.h | 11a4fef884e6017b71eae15cb873e2f36f5011de | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 1,196 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_COMMON_FEATURES_JSON_FEATURE_PROVIDER_SOURCE_H_
#define EXTENSIONS_COMMON_FEATURES_JSON_FEATURE_PROVIDER_SOURCE_H_
#include <string>
#include "base/macros.h"
#include "base/values.h"
namespace extensions {
// A JSONFeatureProviderSource loads JSON dictionary files that
// define features.
class JSONFeatureProviderSource {
public:
explicit JSONFeatureProviderSource(const std::string& name);
~JSONFeatureProviderSource();
// Adds the JSON dictionary file to this provider, merging its values with
// the current dictionary. Key collisions are treated as errors.
void LoadJSON(int resource_id);
// Returns the parsed dictionary.
const base::DictionaryValue& dictionary() { return dictionary_; }
private:
// The name of this feature type; only used for debugging.
const std::string name_;
base::DictionaryValue dictionary_;
DISALLOW_COPY_AND_ASSIGN(JSONFeatureProviderSource);
};
} // namespace extensions
#endif // EXTENSIONS_COMMON_FEATURES_JSON_FEATURE_PROVIDER_SOURCE_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
4d0b0d5af27564688de5106f6a11da0e2611484b | db5ee97954f57ea53ead2de8e256b20528537a1c | /Bridge-DesignPattern/src/IDBIPaymentSystem.cpp | a2e6094fd56900032d4d12d1ea098f2db5d42e5e | [] | no_license | vasudsun/CppDesignPattern | 671530f7b0541f1fa653a00375aa6e67c8343a0d | 6e20ddab47ad138aec71d6bebbe595e02a81a2d2 | refs/heads/master | 2023-08-04T17:46:20.350744 | 2021-09-28T08:26:27 | 2021-09-28T08:26:27 | 411,174,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | /*
* IDBIPaymentSystem.cpp
*
* Created on: 30-Aug-2021
* Author: in0suv
*/
#include "IDBIPaymentSystem.h"
void IDBIPaymentSystem::ProcessPayment(string arg) {
cout<<"IDBIBankGateway for "<<arg <<endl;
}
| [
"sunilvasudevan@hotmail.com"
] | sunilvasudevan@hotmail.com |
f981c2a1ba9868c2b32cf1d97a582ddab9973aa4 | 476af59c3267d2c865fef50a84a256dcf6dbe191 | /competition/First Half 2021/Mar 20. 2021/Solution5693.cpp | 588c24725b60a446a26ee03fcab7a03d5c4271ff | [] | no_license | yogurt-shadow/leetcode | fb3c2f47e77c3b40b06fa65cffe63095bd6542e7 | c824fa13237421afa69d05bb48026e7a2e407d02 | refs/heads/master | 2023-08-29T04:09:43.859492 | 2021-11-11T15:16:15 | 2021-11-11T15:16:15 | 325,449,621 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | cpp | #include<iostream>
#include<unordered_set>
#include<algorithm>
using namespace std;
class Solution5693 {
public:
int secondHighest(string s) {
unordered_set<int> st;
for(auto ele: s){
if(ele >= '0' && ele <= '9'){
int x = ele - '0';
if(st.count(x) == 0){
st.insert(x);
}
}
}
if(st.size() < 2){
return -1;
}
vector<int> vec;
for(auto ele: st){
vec.push_back(ele);
}
sort(vec.begin(), vec.end());
return vec[vec.size() - 2];
}
}; | [
"1711143@mail.nankai.edu.cn"
] | 1711143@mail.nankai.edu.cn |
5b859ab6fd897e9ea428e9f7581c11693566ad5a | 26386ee5977f8a0d89a2e88e69c55fbeef0dbdc5 | /src/LEACH-MAC/cUtility.h | 0ed8993e08f0dc8dfae850adddcaceb222c812b5 | [] | no_license | rshmtud/pvt-leach | 9bef601d908d853b0139137e70397f222dde8ed3 | 520e3f377f697c69bd582c1de4ccc6ea8154b035 | refs/heads/master | 2020-03-21T21:23:27.292287 | 2018-01-29T06:24:54 | 2018-01-29T06:24:54 | 139,060,780 | 2 | 1 | null | 2018-06-28T19:35:29 | 2018-06-28T19:35:29 | null | UTF-8 | C++ | false | false | 1,027 | h | //
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef CUTILITY_H_
#define CUTILITY_H_
#include <vector>
#include <string>
class cUtility {
public:
cUtility();
virtual ~cUtility();
std::string getTestMsg();
std::vector<std::string> split(const std::string& str, const char& ch);
std::vector<int> convertToInt( std::vector < std::string > vStr);
};
#endif /* CUTILITY_H_ */
| [
"mahedee.hasan@gmail.com"
] | mahedee.hasan@gmail.com |
e53950b4e13fc127e1141faddddfa78588415365 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/ds/security/base/lsa/server/efsinit.cxx | af10b66a208a3878d725cac2f8d40493606bb342 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 85,172 | cxx | /*++
Copyright (c) 1997-1999 Microsoft Corporation
Module Name:
efsinit.cxx
Abstract:
EFS (Encrypting File System) Server
Author:
Robert Reichel (RobertRe) July 4, 1997
Robert Gu (RobertGu) Jan 7, 1998
Environment:
Revision History:
--*/
#include <lsapch.hxx>
extern "C" {
#include <nt.h>
#include <ntdef.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <windows.h>
#include <stdio.h>
#include <efsstruc.h>
#include "lsasrvp.h"
#include "debug.h"
#include "efssrv.hxx"
#include "userkey.h"
#include <cfgmgr32.h>
#include <initguid.h>
#include <mountmgr.h>
#include <Userenv.h>
}
#define TIME_UNIT 10000000 // 1 TIME_UNIT == 1 second
#define CERT_VALID_TIME 86400 // seconds - Default cache length 1 day
//
// Local prototypes of CFGMGR32 functions for dynamic load
//
typedef CMAPI CONFIGRET (WINAPI *
CM_GET_DEVICE_INTERFACE_LISTW)(
IN LPGUID,
IN DEVINSTID_W,
OUT PWCHAR,
IN ULONG,
IN ULONG );
typedef CMAPI CONFIGRET (WINAPI *
CM_GET_DEVICE_INTERFACE_LIST_SIZEW)(
IN PULONG,
IN LPGUID,
IN DEVINSTID_W,
IN ULONG
);
typedef CONFIGRET ( * CMP_WAITSERVICESAVAILABLE)(
IN HMACHINE
);
//
// Extern Vars
//
extern RTL_RESOURCE RecoveryPolicyResource;
extern CURRENT_RECOVERY_POLICY CurrentRecoveryPolicy;
extern "C" BOOLEAN EfsDisabled;
//
// Event handle used to sync with the driver
//
HANDLE EfsInitEventHandle = 0;
//
// Efs event handle to get policy change notification
//
HANDLE EfsPolicyEventHandle = 0;
HANDLE EfsWaitHandle = 0;
EFS_POL_CALLBACK EfsPolCallBack;
BOOLEAN EfsServerInitialized = FALSE;
extern "C" BOOLEAN EfsPersonalVer = TRUE;
BOOLEAN EfspInDomain = FALSE;
//
// Cache values
//
HCRYPTPROV hProvVerify = 0;
WCHAR EfsComputerName[MAX_COMPUTERNAME_LENGTH + 1];
LIST_ENTRY UserCacheList;
RTL_CRITICAL_SECTION GuardCacheListLock;
LONG UserCacheListLimit = 5; // We might read this number from the registry in the future
LONG UserCacheListCount = 0;
LONGLONG CACHE_CERT_VALID_TIME;
LONG RecoveryCertIsValidating = 0;
static PSID LocalSystemSid;
DWORD
InitRecoveryPolicy(
VOID
);
DWORD
SetDefaultRecoveryPolicy(
VOID
);
DWORD
ParseRecoveryPolicy_1_1(
IN PLSAPR_POLICY_DOMAIN_EFS_INFO PolicyEfsInfo OPTIONAL,
OUT PCURRENT_RECOVERY_POLICY ParsedRecoveryPolicy
);
VOID
EfsGetRegSettings(
VOID
);
NTSTATUS
EfsServerInit(
VOID
)
/*++
Routine Description:
This routine is called during server initialization to allow
EFS to initialize its data structures and inform the EFS Driver
that it's up and running.
Arguments:
None.
Return Value:
None.
--*/
{
OBJECT_ATTRIBUTES ObjA;
NTSTATUS Status;
UNICODE_STRING EfsInitEventName;
OSVERSIONINFOEX Osvi;
DWORD Result;
DWORD nSize = MAX_COMPUTERNAME_LENGTH + 1;
CACHE_CERT_VALID_TIME = (LONGLONG) CERT_VALID_TIME;
CACHE_CERT_VALID_TIME *= (LONGLONG) TIME_UNIT;
if ( !GetComputerName ( EfsComputerName, &nSize )){
KdPrint(("EfsServerInit - GetComputerName failed 0x%lx\n", GetLastError()));
return STATUS_UNSUCCESSFUL;
}
Osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (GetVersionEx((LPOSVERSIONINFO)&Osvi)){
if ((Osvi.wProductType == VER_NT_WORKSTATION) && ( Osvi.wSuiteMask & VER_SUITE_PERSONAL)) {
EfsPersonalVer = TRUE;
return STATUS_UNSUCCESSFUL;
} else {
EfsPersonalVer = FALSE;
}
} else {
//
// Treat as personal
//
EfsPersonalVer = TRUE;
return STATUS_UNSUCCESSFUL;
}
//
// Init the cache list
//
InitializeListHead(&UserCacheList);
Status = RtlInitializeCriticalSection(&GuardCacheListLock);
if (!NT_SUCCESS(Status)) {
return Status;
}
EfsGetRegSettings();
Status = InitDriverSessionKey();
if (!NT_SUCCESS(Status)) {
KdPrint(("EfsServerInit - EFS Init Session Key failed 0x%lx\n", Status));
return( Status );
}
DebugLog((DEB_TRACE_EFS, "In EfsServerInit\n" ));
//
// Zero out the initial recovery policy structure
//
Result = ParseRecoveryPolicy_1_1(
NULL,
&CurrentRecoveryPolicy
);
//
// Determine if we're in a domain or not. This must be done
// before checking the recovery policy.
//
EfspRoleChangeCallback( (POLICY_NOTIFICATION_INFORMATION_CLASS)NULL );
Status = LsaIRegisterPolicyChangeNotificationCallback(
&EfspRoleChangeCallback,
PolicyNotifyDnsDomainInformation
);
//
// Try to get the current recovery policy.
//
__try
{
RtlInitializeResource( &RecoveryPolicyResource );
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
Status = GetExceptionCode();
}
if ( !NT_SUCCESS( Status ) ) {
return Status ;
}
Result = InitRecoveryPolicy();
if (ERROR_SUCCESS != Result) {
//
// We couldn't initialize our recovery policy. Continue to
// initialize the server so that the driver can proceed.
//
DebugLog((DEB_ERROR, "EfsServerInit - EFS Init Recovery Policy failed 0x%lx\n\n" ,Result ));
}
//
// Try to establish connection with the driver.
// Normally, the driver has not been loaded yet. Create
// an event and wait for the driver. If the event already
// exists, signal it.
//
RtlInitUnicodeString( &EfsInitEventName, L"\\EFSInitEvent" );
InitializeObjectAttributes(
&ObjA,
&EfsInitEventName,
0,
NULL,
NULL
);
Status = NtCreateEvent(
&EfsInitEventHandle,
EVENT_MODIFY_STATE,
&ObjA,
NotificationEvent,
FALSE
);
if (!NT_SUCCESS(Status)) {
if (STATUS_OBJECT_NAME_COLLISION == Status) {
//
// EFS driver has been loaded.
// Open and signal the event. Event handle will be closed
// in GenerateDriverSessionKey()
//
Status = NtOpenEvent(
&EfsInitEventHandle,
EVENT_MODIFY_STATE,
&ObjA
);
//
// If the EFS Init event could not be opened, the EFS Server cannot
// synchronize with the EFS Driver so neither component will
// function correctly.
//
if (!NT_SUCCESS(Status)) {
KdPrint(("EfsServerInit - Connection with the driver failed 0x%lx\n",Status));
return( Status );
}
//
// Signal the EFS Init Event. If the signalling fails, the EFS Server
// is not able to synchronize properly with the EFS Driver.
// This is a serious error which prevents both components from
// functioning correctly.
//
Status = NtSetEvent( EfsInitEventHandle, NULL );
if (!NT_SUCCESS(Status)) {
KdPrint(("EfsServerInit - Init Event Set failed 0x%lx\n",Status));
return( Status );
}
} else {
//
// Other unexpected error
//
KdPrint(("EfsServerInit - Event handling failed 0x%lx\n",Status));
return( Status );
}
}
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
Status = RtlAllocateAndInitializeSid(
&NtAuthority,
1,
SECURITY_LOCAL_SYSTEM_RID,
0, 0, 0, 0, 0, 0, 0,
&LocalSystemSid
);
Status = LsaIRegisterPolicyChangeNotificationCallback(
&RecoveryInformationCallback,
PolicyNotifyDomainEfsInformation
);
//
// Check EFS disable policy if a DC member
//
if (EfspInDomain) {
//
// Only do this if in the domain
//
EfsPolicyEventHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
if (EfsPolicyEventHandle) {
HANDLE waitHandle;
EfsPolCallBack.EfsDisable = &EfsDisabled;
EfsPolCallBack.EfsPolicyEventHandle = &EfsPolicyEventHandle;
//
// We got the event handle. Let's register it to the GP notification.
// If we can't wait on it, we don't need to register it.
//
if (RegisterGPNotification(EfsPolicyEventHandle, TRUE)){
if (!NT_SUCCESS(RtlRegisterWait(
&EfsWaitHandle,
EfsPolicyEventHandle,
EfsGetPolRegSettings,
&EfsPolCallBack,
INFINITE,
WT_EXECUTEONLYONCE))){
//
// We couldn't use the thread pool.
//
UnregisterGPNotification(EfsPolicyEventHandle);
CloseHandle(EfsPolicyEventHandle);
EfsPolicyEventHandle = 0;
}
} else {
//
// We failed to register. No need to wait for the notification.
//
//RtlDeregisterWait(EfsWaitHandle);
CloseHandle(EfsPolicyEventHandle);
EfsPolicyEventHandle = 0;
}
}
//
// Now let's read the policy data left by the last session.
// Pass in &EfsDisabled so that later we could easily change this to
// include more features, such as algorithms controlled by the policy.
//
EfsApplyLastPolicy(&EfsDisabled);
} else {
//
// Delete the possible left over key if there is. We may move this to
// DC disjoin later.
//
EfsRemoveKey();
}
EfsServerInitialized = TRUE;
if (NT_SUCCESS( Status )) {
DebugLog((DEB_TRACE_EFS, "EFS Server initialized successfully\n" ));
} else {
DebugLog((DEB_ERROR, "EFS Server Init failed, Status = %x\n" ,Status ));
}
return( Status );
}
NTSTATUS
InitDriverSessionKey(
VOID
)
/*++
Routine Description:
Generates a session key to be used by the driver and the server
for sending information back and forth securely.
Arguments:
None.
Return Value:
STATUS_SUCCESS on success, STATUS_UNSUCCESSFUL otherwise.
--*/
{
BOOL rc;
//
// hProvVerify will remain open until the process is shut down.
// CryptReleaseContext(hProvVerify, 0) will not be called for this handle.
//
//
if (!CryptAcquireContext(&hProvVerify, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
KdPrint(("InitDriverSessionKey - CryptAcquireContext failed, error = %x\n", GetLastError()));
return( STATUS_UNSUCCESSFUL );
}
rc = CryptGenRandom( hProvVerify, SESSION_KEY_SIZE, DriverSessionKey );
if (!rc) {
return( STATUS_UNSUCCESSFUL );
} else {
LsaPid = (HANDLE) LongToPtr(GetCurrentProcessId());
deskey( &DesTable, DriverSessionKey );
return( STATUS_SUCCESS );
}
}
NTSTATUS
GenerateDriverSessionKey(
OUT PEFS_INIT_DATAEXG InitDataExg
)
/*++
Routine Description:
Actually it just sends the pre-created session key back to the
caller. The key is generated in InitDriverSessionKey.
Arguments:
InitDataExg - Supplies a pointer to a structure in which to put
the initial data to be sent to the driver.
Return Value:
STATUS_SUCCESS.
--*/
{
memcpy( InitDataExg->Key, DriverSessionKey, SESSION_KEY_SIZE );
InitDataExg->LsaProcessID = LsaPid;
if ( EfsInitEventHandle ){
//
// Connection to driver established
//
NtClose( EfsInitEventHandle );
EfsInitEventHandle = 0;
}
return( STATUS_SUCCESS );
}
inline
VOID
AcquireRecoveryPolicyWriteLock()
{
BOOL b = RtlAcquireResourceExclusive( &RecoveryPolicyResource, TRUE );
ASSERT( b );
}
inline
VOID
ReleaseRecoveryPolicyWriteLock()
{
RtlReleaseResource( &RecoveryPolicyResource );
}
DWORD
InitRecoveryPolicy(
VOID
)
/*++
Routine Description:
This routine is used to initialize the current recovery policy.
Arguments:
None
Return Value:
None.
--*/
{
//
// Attempt to query the recovery policy
// from LSA, and if there isn't any,
// attempt to create a default set.
//
DWORD Result = ERROR_SUCCESS;
PLSAPR_POLICY_DOMAIN_EFS_INFO PolicyEfsInfo = NULL;
NTSTATUS Status = LsarQueryDomainInformationPolicy(
LsapPolicyHandle,
PolicyDomainEfsInformation,
(PLSAPR_POLICY_DOMAIN_INFORMATION *)&PolicyEfsInfo
);
if (!NT_SUCCESS( Status )) {
return( RtlNtStatusToDosError(Status) );
}
//
// We're going to parse it right into the global that maintains
// the current recovery data, so take the write lock.
//
AcquireRecoveryPolicyWriteLock();
//
// Free the old parsed recovery bits
//
FreeParsedRecoveryPolicy( &CurrentRecoveryPolicy );
Result = ParseRecoveryPolicy_1_1( PolicyEfsInfo, &CurrentRecoveryPolicy );
if (PolicyEfsInfo != NULL) {
LsaIFree_LSAPR_POLICY_DOMAIN_INFORMATION (
PolicyDomainEfsInformation,
(PLSAPR_POLICY_DOMAIN_INFORMATION)PolicyEfsInfo
);
}
ReleaseRecoveryPolicyWriteLock();
return( Result );
}
DWORD
ParseRecoveryPolicy_1_1(
IN PLSAPR_POLICY_DOMAIN_EFS_INFO PolicyEfsInfo OPTIONAL,
OUT PCURRENT_RECOVERY_POLICY ParsedRecoveryPolicy
)
/*++
Routine Description:
This routine takes the currently defined recovery policy and parses
it into a form that can be used conveniently.
Arguments:
PolicyEfsInfo - Optionally supplies a pointer to the current
recovery policy from the LSA.
ParsedRecoveryPolicy - Returns a structure containing recovery information
in an easy-to-digest format.
Return Value:
return-value - Description of conditions needed to return value. - or -
None.
--*/
{
//
// Fill in the contents of the ParsedRecoveryPolicy structure
// with the contents of the passed policy information.
//
PRECOVERY_POLICY_1_1 RecoveryPolicy;
DWORD Found = 0;
PRECOVERY_KEY_1_1 RecoveryKey;
DWORD rc = ERROR_SUCCESS;
BOOL b = FALSE;
if (PolicyEfsInfo == NULL) {
//
// NULL recovery policy
//
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_NULL;
goto NoPolicy1;
}
RecoveryPolicy = (PRECOVERY_POLICY_1_1)PolicyEfsInfo->EfsBlob;
if (RecoveryPolicy == NULL) {
//
// Empty recovery policy
//
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_EMPTY;
goto NoPolicy1;
}
ParsedRecoveryPolicy->dwKeyCount = RecoveryPolicy->RecoveryPolicyHeader.RecoveryKeyCount;
if (ParsedRecoveryPolicy->dwKeyCount == 0) {
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_NO_AGENT;
goto NoPolicy1;
}
__try {
//
// Scan the recovery data looking for recovery keys in a format we understand
//
ULONG i;
RecoveryKey = (PRECOVERY_KEY_1_1) &(RecoveryPolicy->RecoveryKeyList[0]);
for (i=0 ; i< (ParsedRecoveryPolicy->dwKeyCount) ; i++) {
PEFS_PUBLIC_KEY_INFO PublicKeyInfo = &RecoveryKey->PublicKeyInfo;
if (* ((ULONG UNALIGNED *) &(PublicKeyInfo->KeySourceTag)) == EfsCertificate) {
Found++;
}
RecoveryKey = (PRECOVERY_KEY_1_1)( ((PBYTE)RecoveryKey) + * ((ULONG UNALIGNED *) &(RecoveryKey->TotalLength)) );
}
if (0 == Found) {
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_BAD_POLICY;
goto NoPolicy1;
} else {
ParsedRecoveryPolicy->Base = (PBYTE)LsapAllocateLsaHeap( 7 * sizeof( PVOID ) * Found );
if (ParsedRecoveryPolicy->Base) {
ZeroMemory( ParsedRecoveryPolicy->Base, 7 * sizeof( PVOID ) * Found);
PBYTE Base = ParsedRecoveryPolicy->Base;
ParsedRecoveryPolicy->pbHash = (PBYTE *)Base;
Base += Found * sizeof(PVOID);
ParsedRecoveryPolicy->cbHash = (PDWORD)Base;
Base += Found * sizeof(PVOID);
ParsedRecoveryPolicy->pbPublicKeys = (PBYTE *)Base;
Base += Found * sizeof(PVOID);
ParsedRecoveryPolicy->cbPublicKeys = (PDWORD)Base;
Base += Found * sizeof(PVOID);
ParsedRecoveryPolicy->lpDisplayInfo = (LPWSTR *)Base;
Base += Found * sizeof(PVOID);
ParsedRecoveryPolicy->pCertContext = (PCCERT_CONTEXT *)Base;
Base += Found * sizeof(PVOID);
ParsedRecoveryPolicy->pSid = (PSID *)Base;
} else {
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_NO_MEMORY;
return( ERROR_NOT_ENOUGH_MEMORY );
}
ParsedRecoveryPolicy->dwKeyCount = Found;
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_OK;
//
// Make a copy of the policy information so we can free what we were passed in the caller
//
RecoveryKey = (PRECOVERY_KEY_1_1) &(RecoveryPolicy->RecoveryKeyList[0]);
for (i=0 ; i< (ParsedRecoveryPolicy->dwKeyCount) ; i++) {
PEFS_PUBLIC_KEY_INFO PublicKeyInfo = &RecoveryKey->PublicKeyInfo;
if (* ((ULONG UNALIGNED *) &(PublicKeyInfo->KeySourceTag)) == EfsCertificate) {
b = ParseRecoveryCertificate( PublicKeyInfo,
&ParsedRecoveryPolicy->pbHash[i],
&ParsedRecoveryPolicy->cbHash[i],
&ParsedRecoveryPolicy->pbPublicKeys[i],
&ParsedRecoveryPolicy->cbPublicKeys[i],
&ParsedRecoveryPolicy->lpDisplayInfo[i],
&ParsedRecoveryPolicy->pCertContext[i],
&ParsedRecoveryPolicy->pSid[i]
);
if (!b) {
break;
}
}
RecoveryKey = (PRECOVERY_KEY_1_1)( ((PBYTE)RecoveryKey) + * ((ULONG UNALIGNED *) &(RecoveryKey->TotalLength)) );
}
}
} __except (EXCEPTION_EXECUTE_HANDLER) {
b = FALSE;
//
// There was something wrong with the recovery policy.
// Return this so we can at least print out an error.
//
rc = GetExceptionCode();
}
if (!b) {
//
// Something failed, clean up
//
rc = GetLastError();
FreeParsedRecoveryPolicy( ParsedRecoveryPolicy );
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_UNKNOWN_BAD;
DebugLog((DEB_WARN, "Error parsing recovery policy\n" ));
}
//
// Policy refreshed. The Cert validation needs to be refreshed.
//
ParsedRecoveryPolicy->CertValidated = CERT_NOT_VALIDATED;
return( rc );
NoPolicy1:
ParsedRecoveryPolicy->dwKeyCount = 0;
ParsedRecoveryPolicy->TimeStamp.QuadPart = 0;
ParsedRecoveryPolicy->CertValidated = CERT_NOT_VALIDATED;
ParsedRecoveryPolicy->Base = NULL;
ParsedRecoveryPolicy->pbHash = NULL;
ParsedRecoveryPolicy->cbHash = NULL;
ParsedRecoveryPolicy->pbPublicKeys = NULL;
ParsedRecoveryPolicy->cbPublicKeys = NULL;
ParsedRecoveryPolicy->lpDisplayInfo = NULL;
ParsedRecoveryPolicy->pCertContext = NULL;
ParsedRecoveryPolicy->pSid = NULL;
return( ERROR_SUCCESS );
}
VOID
FreeParsedRecoveryPolicy(
PCURRENT_RECOVERY_POLICY ParsedRecoveryPolicy
)
/*++
Routine Description:
This routine will free the allocated memory in a
CURRENT_RECOVERY_POLICY structure.
Arguments:
ParsedRecoveryPolicy - Supplies a structure that has
had data parsed into it.
Return Value:
None.
--*/
{
//
// Walk through the recovery policy and free everything
//
DWORD i;
if (ParsedRecoveryPolicy->Base) {
for (i=0; i<ParsedRecoveryPolicy->dwKeyCount; i++) {
if (ParsedRecoveryPolicy->pbHash[i] != NULL) {
LsapFreeLsaHeap( ParsedRecoveryPolicy->pbHash[i] );
}
if (ParsedRecoveryPolicy->pbPublicKeys[i] != NULL) {
LsapFreeLsaHeap( ParsedRecoveryPolicy->pbPublicKeys[i] );
}
if (ParsedRecoveryPolicy->lpDisplayInfo[i] != NULL) {
LsapFreeLsaHeap( ParsedRecoveryPolicy->lpDisplayInfo[i] );
}
if (ParsedRecoveryPolicy->pCertContext[i] != NULL) {
CertFreeCertificateContext( ParsedRecoveryPolicy->pCertContext[i] );
}
if (ParsedRecoveryPolicy->pSid[i] != NULL) {
LsapFreeLsaHeap( ParsedRecoveryPolicy->pSid[i] );
}
}
LsapFreeLsaHeap( ParsedRecoveryPolicy->Base );
}
//
// Paranoia
//
ParsedRecoveryPolicy->Base = NULL;
ParsedRecoveryPolicy->CertValidated = CERT_NOT_VALIDATED;
ParsedRecoveryPolicy->PolicyStatus = RECOVERY_POLICY_NULL;
ParsedRecoveryPolicy->dwKeyCount = 0;
ParsedRecoveryPolicy->pbHash = NULL;
ParsedRecoveryPolicy->cbHash = NULL;
ParsedRecoveryPolicy->pbPublicKeys = NULL;
ParsedRecoveryPolicy->cbPublicKeys = NULL;
ParsedRecoveryPolicy->lpDisplayInfo = NULL;
ParsedRecoveryPolicy->pCertContext = NULL;
ParsedRecoveryPolicy->pSid = NULL;
}
DWORD WINAPI
EFSRecover(
IN LPVOID Param
)
/*++
Routine Description:
Enumerate the volumes and do the possible recovery jobs caused by
power outage or crash during encryption or decryption.
Arguments:
Param -- Standard parameter for thread. Not used.
Return Value:
Operation result.
--*/
{
CONFIGRET RetCode;
WCHAR *VolBuffer;
WCHAR *PathName;
ULONG VolOffset;
ULONG bufLen;
HMODULE hCfgMgr ;
CMP_WAITSERVICESAVAILABLE pCMP_WaitServicesAvailable ;
CM_GET_DEVICE_INTERFACE_LIST_SIZEW pCM_Get_Device_Interface_List_Size ;
CM_GET_DEVICE_INTERFACE_LISTW pCM_Get_Device_Interface_List ;
// hCfgMgr = LoadLibrary( TEXT("cfgmgr32.dll" ) );
hCfgMgr = LoadLibrary( TEXT("setupapi.dll" ) );
if ( hCfgMgr )
{
pCMP_WaitServicesAvailable = (CMP_WAITSERVICESAVAILABLE)
GetProcAddress( hCfgMgr,
"CMP_WaitServicesAvailable" );
pCM_Get_Device_Interface_List_Size = (CM_GET_DEVICE_INTERFACE_LIST_SIZEW)
GetProcAddress( hCfgMgr,
"CM_Get_Device_Interface_List_SizeW" );
pCM_Get_Device_Interface_List = (CM_GET_DEVICE_INTERFACE_LISTW)
GetProcAddress( hCfgMgr,
"CM_Get_Device_Interface_ListW" );
if ( (!pCMP_WaitServicesAvailable) ||
(!pCM_Get_Device_Interface_List_Size) ||
(!pCM_Get_Device_Interface_List) )
{
FreeLibrary( hCfgMgr );
return GetLastError() ;
}
} else {
return GetLastError() ;
}
RetCode = pCMP_WaitServicesAvailable( NULL );
if ( CR_SUCCESS != RetCode ){
FreeLibrary( hCfgMgr );
return RetCode;
}
RetCode = pCM_Get_Device_Interface_List_Size(
&bufLen,
(LPGUID)&MOUNTDEV_MOUNTED_DEVICE_GUID,
NULL,
CM_GET_DEVICE_INTERFACE_LIST_PRESENT
);
if ( CR_SUCCESS == RetCode ){
VolBuffer = (WCHAR *) LsapAllocateLsaHeap( bufLen * sizeof(WCHAR) );
PathName = (WCHAR *) LsapAllocateLsaHeap( MAX_PATH_LENGTH );
if ( (NULL != VolBuffer) && (NULL != PathName) ){
RetCode = pCM_Get_Device_Interface_List(
(LPGUID)&MOUNTDEV_MOUNTED_DEVICE_GUID,
NULL,
VolBuffer,
bufLen,
CM_GET_DEVICE_INTERFACE_LIST_PRESENT
);
if ( CR_SUCCESS == RetCode ){
VolOffset = 0;
while (*(VolBuffer + VolOffset)) {
//
// See if recovery is needed on the volume
//
wcscpy(PathName, VolBuffer + VolOffset);
wcscat(PathName, EFSDIR);
TryRecoverVol(VolBuffer + VolOffset, PathName);
while (*(VolBuffer + VolOffset++));
}
} else {
HANDLE EventHandleLog = RegisterEventSource(
NULL,
EFSSOURCE
);
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_GET_VOLUMES_ERROR,
NULL,
0,
4,
NULL,
&RetCode
);
DeregisterEventSource( EventHandleLog );
}
if ( CR_REGISTRY_ERROR == RetCode ){
//
// Map CR error to winerror
//
RetCode = ERROR_REGISTRY_CORRUPT;
}
}
LsapFreeLsaHeap( VolBuffer );
LsapFreeLsaHeap( PathName );
} else {
if ( NULL != PathName ){
LsapFreeLsaHeap( PathName );
}
if ( NULL != VolBuffer ) {
LsapFreeLsaHeap( VolBuffer );
}
RetCode = ERROR_NOT_ENOUGH_MEMORY;
}
} else {
DWORD RetCode1 = GetLastError();
HANDLE EventHandleLog = RegisterEventSource(
NULL,
EFSSOURCE
);
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_PNP_NOT_READY,
NULL,
0,
4,
NULL,
&RetCode1
);
DeregisterEventSource( EventHandleLog );
}
if ( CR_REGISTRY_ERROR == RetCode1 ){
//
// Map CR error to winerror
//
RetCode = ERROR_REGISTRY_CORRUPT;
}
}
FreeLibrary( hCfgMgr );
return RetCode;
}
void
TryRecoverVol(
IN const WCHAR *VolumeName,
IN WCHAR *CacheDir
)
/*++
Routine Description:
Do the possible recovery jobs caused by
power outage or crash during encryption or decryption on the volume.
Arguments:
VolumeName -- volume name to be checked.
CacheDir -- EFSCACHE dir. The buffer can be used in this routine.
Return Value:
None.
--*/
{
HANDLE EfsCacheDir;
LPWIN32_FIND_DATA FindFileInfo;
HANDLE FindHandle;
//
// Check if the directory EFSCACHE exist or not
//
EfsCacheDir = CreateFile(
CacheDir,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0
);
if (EfsCacheDir == INVALID_HANDLE_VALUE){
//
// No recovery needed
//
return;
}
CloseHandle(EfsCacheDir);
//
// Search the possible log file
//
FindFileInfo = ( LPWIN32_FIND_DATA ) LsapAllocateLsaHeap ( sizeof ( WIN32_FIND_DATA ));
ASSERT( FindFileInfo );
if ( NULL == FindFileInfo ){
return;
}
wcscat(CacheDir, EFSLOGPATTERN);
FindHandle = FindFirstFile( CacheDir, FindFileInfo );
if (FindHandle == INVALID_HANDLE_VALUE){
//
// No LogFile found. No recovery needed
//
LsapFreeLsaHeap( FindFileInfo);
return;
}
//
// Log file found. FT procedure begins
//
HANDLE EventHandleLog = RegisterEventSource(
NULL,
EFSSOURCE
);
if ( EventHandleLog ){
//
// Error in handling Event Log should not prevent real FT job.
//
ReportEvent(
EventHandleLog,
EVENTLOG_INFORMATION_TYPE,
0,
EFS_FT_STARTED,
NULL,
0,
0,
NULL,
NULL
);
}
for (;;){
BOOL b;
TryRecoverFile( VolumeName, FindFileInfo, EventHandleLog );
b = FindNextFile( FindHandle, FindFileInfo );
if ( !b ) {
break;
}
}
if ( EventHandleLog ){
DeregisterEventSource( EventHandleLog );
}
LsapFreeLsaHeap( FindFileInfo);
FindClose( FindHandle );
return;
}
void
TryRecoverFile(
IN const WCHAR *VolumeName,
IN LPWIN32_FIND_DATA FindFileInfo,
IN HANDLE EventHandleLog
)
/*++
Routine Description:
Do the possible recovery jobs caused by
power outage or crash during encryption or decryption for the file.
Arguments:
VolumeName -- volume name the log file is in.
FindFileInfo -- Information about this log file.
Return Value:
None.
--*/
{
WCHAR *FileName;
HANDLE LogFile;
HANDLE TmpFile;
HANDLE Target;
HANDLE VolumeHandle;
LPWSTR TargetName;
LPWSTR TmpName = NULL;
LOGHEADER FileHeader;
ULONG SectorSize;
BYTE *ReadBuffer;
BYTE *StatusBuffer;
BOOL b;
ULONG BufferSize;
DWORD BytesRead;
ULONG CheckSum;
EFS_ACTION_STATUS Action;
NTSTATUS Status;
UNICODE_STRING FileId;
VolumeHandle = CreateFile(
VolumeName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0
);
if ( INVALID_HANDLE_VALUE == VolumeHandle ){
//
// Directory on this volume opened successfully. It is unlikely that we will
// come here.
//
return;
}
FileName = (WCHAR *) LsapAllocateLsaHeap( MAX_PATH_LENGTH );
//
// Out of memory is unlikely at the boot time
//
ASSERT (FileName);
if ( NULL == FileName ){
CloseHandle( VolumeHandle );
return;
}
//
// Construct the log file name
//
wcscpy( FileName, VolumeName );
wcscat( FileName, EFSDIR );
wcscat( FileName, L"\\");
wcscat( FileName, FindFileInfo->cFileName);
LogFile = CreateFile(
FileName,
GENERIC_READ | GENERIC_WRITE | DELETE,
0,
NULL,
OPEN_EXISTING,
0,
0
);
if ( INVALID_HANDLE_VALUE == LogFile ){
DWORD ErrCode = GetLastError();
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_OPEN_LOGFILE_ERROR,
NULL,
0,
4,
NULL,
&ErrCode
);
}
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(FileName);
return;
}
b = ReadFile(
LogFile,
&FileHeader,
sizeof( LOGHEADER ),
&BytesRead,
NULL
);
if ( !b ){
//
// File IO error
//
DWORD ErrCode = GetLastError();
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_READ_LOGFILE_ERROR,
NULL,
0,
4,
NULL,
&ErrCode
);
}
CloseHandle( LogFile );
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(FileName);
return;
}
if ( 0 == BytesRead ){
//
// Zero length log file. Nothing started. Delete it.
//
MarkFileForDelete( LogFile );
CloseHandle( LogFile );
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(FileName);
return;
}
if ( (BytesRead < sizeof( LOGHEADER )) ||
(LOGSIGLEN * sizeof (WCHAR) != RtlCompareMemory(
&(FileHeader.SIGNATURE[0]),
LOGSIG,
LOGSIGLEN * sizeof (WCHAR)
)) ||
( LOGVERID != FileHeader.VerID )){
//
// Probably not our log file
//
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_INFORMATION_TYPE,
0,
EFS_LOGFILE_FORMAT_ERROR,
NULL,
0,
0,
NULL,
NULL
);
}
CloseHandle( LogFile );
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(FileName);
return;
}
//
// Read in the whole header to continue the process
//
SectorSize = FileHeader.SectorSize;
BufferSize = FileHeader.HeaderBlockSize;
ASSERT( BufferSize % SectorSize == 0 );
ReadBuffer = (BYTE *) LsapAllocateLsaHeap( BufferSize );
//
// StatusBuffer must be aligned for cached IO.
// LsapAllocateLsaHeap() is not aligned.
//
if ((FileHeader.Flag & LOG_DIRECTORY) == 0) {
StatusBuffer = (BYTE *) VirtualAlloc(
NULL,
FileHeader.OffsetStatus2 - FileHeader.OffsetStatus1,
MEM_COMMIT,
PAGE_READWRITE
);
} else {
StatusBuffer = NULL;
}
ASSERT( (FileHeader.OffsetStatus2 - FileHeader.OffsetStatus1) % SectorSize == 0 );
ASSERT( ReadBuffer );
if ( (NULL == ReadBuffer) || ((NULL == StatusBuffer) && ((FileHeader.Flag & LOG_DIRECTORY) == 0)) ){
//
// Out of memory is almost impossible during the boot time.
//
if ( ReadBuffer ) {
LsapFreeLsaHeap(ReadBuffer);
}
if ( StatusBuffer ) {
VirtualFree(
StatusBuffer,
0,
MEM_RELEASE
);
}
CloseHandle( LogFile );
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(FileName);
return;
}
SetFilePointer( LogFile, 0, NULL, FILE_BEGIN);
b = ReadFile(
LogFile,
ReadBuffer,
BufferSize,
&BytesRead,
NULL
);
if ( !b || ( BytesRead != BufferSize ) ){
//
// File IO error, Should sent out some debug Info?
//
DWORD ErrCode = GetLastError();
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_READ_LOGFILE_ERROR,
NULL,
0,
4,
NULL,
&ErrCode
);
}
CloseHandle( LogFile );
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(ReadBuffer);
VirtualFree(
StatusBuffer,
0,
MEM_RELEASE
);
LsapFreeLsaHeap(FileName);
return;
}
CheckSum = GetCheckSum(ReadBuffer, FileHeader.HeaderSize );
if (CheckSum == *(ULONG* ) (ReadBuffer + BufferSize - sizeof(ULONG))){
OBJECT_ATTRIBUTES Obja;
IO_STATUS_BLOCK IoStatusBlock;
//
// The header is in good condition. Get TargetName and TmpName for the error
// msg in system log.
//
TargetName = (WCHAR *)( ReadBuffer + FileHeader.TargetFilePathOffset );
if ( (FileHeader.Flag & LOG_DIRECTORY) == 0 ){
//
// Operation was on File not on Directory
// The real status is in Status block. Read in the status block.
// Log file may updated. We need to reopen it with non-cached IO.
//
CloseHandle( LogFile );
LogFile = CreateFile(
FileName,
GENERIC_READ | GENERIC_WRITE | DELETE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0
);
//
// Log File name is done. We are going to use FileName memory space
// to get a temp file name.
//
if ( INVALID_HANDLE_VALUE == LogFile ){
//
// Log File cannot be open as non-cached IO. Try next time.
// This is weird.
//
DWORD ErrCode = GetLastError();
ASSERT (FALSE);
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_OPEN_LOGFILE_NC_ERROR,
NULL,
0,
4,
NULL,
&ErrCode
);
}
LsapFreeLsaHeap(FileName);
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(ReadBuffer);
VirtualFree(
StatusBuffer,
0,
MEM_RELEASE
);
return;
}
//
// Open the temp file first.
//
TmpName = (WCHAR *)( ReadBuffer + FileHeader.TempFilePathOffset );
FileId.Buffer = (WCHAR *) &(FileHeader.TempFileInternalName);
FileId.Length = FileId.MaximumLength = sizeof (LARGE_INTEGER);
InitializeObjectAttributes(
&Obja,
&FileId,
0,
VolumeHandle,
NULL
);
Status = NtCreateFile(
&TmpFile,
GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE,
&Obja,
&IoStatusBlock,
NULL,
0,
0,
FILE_OPEN,
FILE_OPEN_BY_FILE_ID | FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
NULL,
0
);
if (NT_SUCCESS( Status )){
OBJECT_NAME_INFORMATION *ATempFileName;
ULONG PathLength;
//
// Temp file opened with File ID. File open by ID cannot be deleted. So
// we need to get a name and reopen it using the name with DELETE
// access
//
ATempFileName = (OBJECT_NAME_INFORMATION *)FileName;
Status = NtQueryObject(
TmpFile,
ObjectNameInformation,
ATempFileName,
MAX_PATH_LENGTH,
&PathLength
);
if ( NT_SUCCESS( Status ) ){
CloseHandle(TmpFile);
TmpFile = 0;
InitializeObjectAttributes(
&Obja,
&(ATempFileName->Name),
0,
0,
NULL
);
Status = NtCreateFile(
&TmpFile,
GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE | DELETE,
&Obja,
&IoStatusBlock,
NULL,
0,
0,
FILE_OPEN,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
NULL,
0
);
if (!NT_SUCCESS( Status )){
//
// Well, we cannot open with the name got. Strange.
// Reopen it with File ID. Temp file is not going to be deleted.
//
ASSERT(FALSE);
if ( EventHandleLog ){
LPWSTR lpStrings[2];
lpStrings[1] = TargetName;
lpStrings[0] = TmpName;
ReportEvent(
EventHandleLog,
EVENTLOG_WARNING_TYPE,
0,
EFS_TMP_OPEN_NAME_ERROR,
NULL,
2,
4,
(LPCTSTR *) &lpStrings[0],
&Status
);
}
InitializeObjectAttributes(
&Obja,
&FileId,
0,
VolumeHandle,
NULL
);
Status = NtCreateFile(
&TmpFile,
GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE,
&Obja,
&IoStatusBlock,
NULL,
0,
0,
FILE_OPEN,
FILE_OPEN_BY_FILE_ID | FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
NULL,
0
);
if (!NT_SUCCESS( Status )){
//
// Well, more strange. We cannot even open the file we opened
// Nothing we can do this time. Try next time.
//
if ( EventHandleLog ){
LPWSTR lpStrings[2];
lpStrings[1] = TargetName;
lpStrings[0] = TmpName;
ReportEvent(
EventHandleLog,
EVENTLOG_WARNING_TYPE,
0,
EFS_TMP_FILEID_ERROR,
NULL,
2,
4,
(LPCTSTR*) &lpStrings[0],
&Status
);
}
LsapFreeLsaHeap(FileName);
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(ReadBuffer);
VirtualFree(
StatusBuffer,
0,
MEM_RELEASE
);
return;
}
}
} else {
if ( EventHandleLog ){
LPWSTR lpStrings[2];
lpStrings[0] = TargetName;
lpStrings[1] = TmpName;
ReportEvent(
EventHandleLog,
EVENTLOG_WARNING_TYPE,
0,
EFS_TMP_FILENAME_ERROR,
NULL,
2,
4,
(LPCTSTR*) &lpStrings[0],
&Status
);
}
}
//
// If a name cannot be got, the following apply.
// Temp file is existed. But we cannot get a name. Weird.
// The recover will go on. But the temp file will not be deleted
//
} else {
//
// Temp file is not exist. May be deleted by our operations.
// Make sure the handle is 0.
//
TmpFile = 0;
}
//
// FileName is done.
//
LsapFreeLsaHeap(FileName);
FileName = NULL;
Status = ReadLogFile(
LogFile,
StatusBuffer,
FileHeader.OffsetStatus1,
FileHeader.OffsetStatus2
);
if (!NT_SUCCESS( Status )) {
//
// Status copies are not valid. Nothing have started or we can do nothing
// to recover. Delete the log file.
//
MarkFileForDelete( LogFile );
CloseHandle( LogFile );
if ( TmpFile ){
CloseHandle( TmpFile );
}
CloseHandle( VolumeHandle );
LsapFreeLsaHeap(ReadBuffer);
VirtualFree(
StatusBuffer,
0,
MEM_RELEASE
);
return;
}
Action = * (EFS_ACTION_STATUS *) (StatusBuffer + sizeof (ULONG));
} else {
//
// Operations were on a directory
//
if ( FileHeader.Flag & LOG_DECRYPTION ){
Action = BeginDecryptDir;
} else {
Action = BeginEncryptDir;
}
TmpFile = 0;
}
//
// Open the target file.
//
if (StatusBuffer) {
VirtualFree(
StatusBuffer,
0,
MEM_RELEASE
);
}
FileId.Buffer = (WCHAR* ) &(FileHeader.TargetFileInternalName);
FileId.Length = FileId.MaximumLength = sizeof (LARGE_INTEGER);
InitializeObjectAttributes(
&Obja,
&FileId,
0,
VolumeHandle,
NULL
);
Status = NtCreateFile(
&Target,
GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE ,
&Obja,
&IoStatusBlock,
NULL,
0,
0,
FILE_OPEN,
FILE_OPEN_BY_FILE_ID | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
NULL,
0
);
if (!NT_SUCCESS( Status )) {
//
// OOPS! We can not open the target. What can we do without the target.
// Delete the log file.
//
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_WARNING_TYPE,
0,
EFS_TARGET_OPEN_ERROR,
NULL,
1,
4,
(LPCTSTR*) &TargetName,
&Status
);
}
MarkFileForDelete( LogFile );
CloseHandle( LogFile );
CloseHandle( VolumeHandle );
if ( TmpFile ){
CloseHandle( TmpFile );
}
LsapFreeLsaHeap(ReadBuffer);
return;
}
//
// We survived so far. Now is the show time!
//
DoRecover(
Target,
TmpFile,
LogFile,
TargetName,
TmpName,
FileHeader.OffsetStatus2 - FileHeader.OffsetStatus1,
FileHeader.OffsetStatus1,
Action,
EventHandleLog
);
CloseHandle ( Target );
if ( TmpFile ){
CloseHandle( TmpFile );
}
} else {
//
// The header is not fully written. Nothing could have be done.
// Just delete the log file and we are done.
//
MarkFileForDelete( LogFile );
if (StatusBuffer) {
VirtualFree(
StatusBuffer,
0,
MEM_RELEASE
);
}
LsapFreeLsaHeap(FileName);
}
LsapFreeLsaHeap(ReadBuffer);
CloseHandle( LogFile );
CloseHandle( VolumeHandle );
return;
}
NTSTATUS
ReadLogFile(
IN HANDLE LogFile,
OUT BYTE* ReadBuffer,
IN ULONG FirstCopy,
IN ULONG SecondCopy
)
/*++
Routine Description:
Read Status Log Information.
Arguments:
LogFile -- A handle to the log file
ReadBuffer -- Buffer for the output data.
FirstCopy -- Offset of first status information copy in the logfile.
SecondCopy -- Offset of second status information copy in the logfile.
Return Value:
The status of operation.
--*/
{
ULONG ReadBytes;
NTSTATUS Status;
IO_STATUS_BLOCK IoStatusBlock;
LARGE_INTEGER ByteOffset;
ULONG CheckSum;
BOOLEAN WrongCheckSum = FALSE;
//
// Write out the header sector
//
ByteOffset.QuadPart = (LONGLONG) FirstCopy;
ReadBytes = SecondCopy - FirstCopy;
Status = NtReadFile(
LogFile,
0,
NULL,
NULL,
&IoStatusBlock,
ReadBuffer,
ReadBytes,
&ByteOffset,
NULL
);
if ( NT_SUCCESS(Status) ) {
//
// Check the integrity of the data
//
CheckSum = GetCheckSum( ReadBuffer, 2 * sizeof (ULONG) );
if ( CheckSum != *(ULONG *)( ReadBuffer + ReadBytes - sizeof (ULONG) )){
WrongCheckSum = TRUE;
}
}
if ( !NT_SUCCESS(Status) || WrongCheckSum ) {
ByteOffset.QuadPart = (LONGLONG) SecondCopy;
Status = NtReadFile(
LogFile,
0,
NULL,
NULL,
&IoStatusBlock,
ReadBuffer,
ReadBytes,
&ByteOffset,
NULL
);
if ( NT_SUCCESS(Status) ) {
//
// Check the integrity of the data
//
CheckSum = GetCheckSum( ReadBuffer, 2 * sizeof (ULONG) );
if ( CheckSum != *(ULONG *)( ReadBuffer + ReadBytes - sizeof (ULONG) )){
//
// Both status copy are bad.
//
Status = STATUS_FILE_CORRUPT_ERROR;
}
}
}
return Status;
}
NTSTATUS
DoRecover(
IN HANDLE Target,
IN HANDLE TmpFile OPTIONAL,
IN HANDLE LogFile,
IN LPCWSTR TargetName,
IN LPCWSTR TmpName OPTIONAL,
IN ULONG StatusCopySize,
IN ULONG StatusStartOffset,
IN ULONG Action,
IN HANDLE EventHandleLog
)
/*++
Routine Description:
Do the real dirty recovery job here.
Arguments:
Target -- A handle to the target file or directory.
TmpFile -- A handle to the temp file if Target is a file.
LogFile -- A handle to the log file.
TargetName -- Target file name. This info is used for error log only.
TmpName -- Temp backup file name. This info is used for error log only.
StatusCopySize -- Log file status copy section size.
StatusStartOffset -- Offset of status copy in the log file.
Action -- The status to begin.
EventHandleLog -- Event log handle.
Return Value:
The status of operation.
--*/
{
NTSTATUS Status = STATUS_SUCCESS;
EFSP_OPERATION Operation = EncryptRecovering;
if ( ( BeginEncryptDir == Action ) || ( BeginDecryptDir == Action ) ){
//
// In both cases, we will do Decrypt on the directory
//
Status = DecryptDir( Target, TargetName );
if ( NT_SUCCESS(Status) ) {
//
// The operation was successful
//
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_INFORMATION_TYPE,
0,
EFS_TARGET_RECOVERED,
NULL,
1,
0,
(LPCTSTR*) &TargetName,
NULL
);
}
MarkFileForDelete( LogFile );
} else {
//
// EFS driver might not be loaded. Log the information.
//
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_DRIVER_MISSING,
NULL,
1,
0,
(LPCTSTR*) &TargetName,
NULL
);
}
}
} else {
//
// File operations
//
switch ( Action ) {
case EncryptionMessup:
//
// The original file is messed up due to the unknown reason.
// Operation required,
// Same as EncryptTmpFileWritten.
//
Operation = EncryptRecovering;
// ***** Fall through intended *****
case DecryptTmpFileWritten:
//
// Temp file is created and written during the decryption. The original file is probably
// damaged. Operation required,
// Same as the EncryptTmpFileWritten. The file will end up as plain text.
//
if ( DecryptTmpFileWritten == Action ){
Operation = DecryptRecovering;
}
//
// ***** Fall through intended *****
//
case EncryptTmpFileWritten:
if ( EncryptTmpFileWritten == Action ){
Operation = EncryptRecovering;
}
//
// Temp file is created and written during the encryption. The original file is probably
// damaged. Operation required,
// FSCTL decrypt each stream, copy the data back to the original file. Log file
// will be updated to BeginEncryptFile after all the streams are copied back. Then
// continue the case indicated in BeginEncryptFile.
//
if ( !TmpFile ){
//
// Temp backup not existed or open failed, we can do nothing for this.
// Log the error information and quit.
//
if ( EventHandleLog ){
LPCWSTR lpStrings[2];
lpStrings[1] = TargetName;
lpStrings[0] = TmpName;
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_TMPFILE_MISSING,
NULL,
2,
4,
&lpStrings[0],
&Status
);
}
return STATUS_NO_SUCH_FILE;
}
Status = RestoreTarget(
Target,
TmpFile,
TargetName,
TmpName,
EventHandleLog,
Operation
);
if ( NT_SUCCESS(Status) ) {
WriteLogFile(
LogFile,
StatusCopySize,
StatusStartOffset,
BeginEncryptFile
);
} else {
return Status;
}
// ***** Fall through intended *****
case DecryptionDone:
//
// All the streams are marked decrypted. The file might still have the flag set.
// Operation required,
// Same as BeginEncryptFile.
//
// ***** Fall through intended *****
case EncryptionBackout:
//
// Encryption failed but we managed the original streams back. The file might
// be in a transition status.
// Operation required,
// Same as BeginEncryptFile.
//
// ***** Fall through intended *****
case BeginEncryptFile:
//
// File encryption just begin. Original file is not changed.
// Operation required,
// Remove the $EFS, remove the tempfile if existed and remove the log file.
//
Status = SendGenFsctl(
Target,
EFS_DECRYPT_FILE,
EFS_DECRYPT_FILE,
EFS_SET_ENCRYPT,
FSCTL_SET_ENCRYPTION
);
if ( NT_SUCCESS(Status) ) {
if ( TmpFile ){
MarkFileForDelete( TmpFile );
}
MarkFileForDelete( LogFile );
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_INFORMATION_TYPE,
0,
EFS_TARGET_RECOVERED,
NULL,
1,
0,
&TargetName,
NULL
);
}
} else {
//
// EFS driver may not be loaded. Write the log info.
//
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_DRIVER_MISSING,
NULL,
1,
0,
&TargetName,
NULL
);
}
}
break;
case BeginDecryptFile:
//
// File decryption just begin. Original file is not changed.
// Operation required,
// Set the transition status to normal, remove the tempfile if existed and
// remove the log file.
//
// ***** Fall through intended *****
case EncryptionDone:
//
// All the streams were encrypted. The original file might be in transition status.
// Operation required,
// FSCTL to set the transition status to normal. Update the log status to
// EncryptionSrcDone. Continue to EncryptionSrcDone.
//
Status = SendGenFsctl(
Target,
0,
0,
EFS_ENCRYPT_DONE,
FSCTL_ENCRYPTION_FSCTL_IO
);
if ( !NT_SUCCESS(Status) ) {
//
// EFS driver might not be loaded. Log error.
//
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_DRIVER_MISSING,
NULL,
1,
0,
&TargetName,
NULL
);
}
return Status;
}
// ***** Fall through intended *****
case EncryptionSrcDone:
//
// The original file is encrypted successfully. The temp file might still be left.
// Operation required,
// Remove the temp file if existed and remove the log file.
//
if ( TmpFile ){
MarkFileForDelete( TmpFile );
}
MarkFileForDelete( LogFile );
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_INFORMATION_TYPE,
0,
EFS_TARGET_RECOVERED,
NULL,
1,
0,
&TargetName,
NULL
);
}
break;
default:
//
// Not our log file or tempered by someone.
// Write to the log to notify the user.
//
Status = STATUS_FILE_CORRUPT_ERROR;
break;
}
}
return Status;
}
NTSTATUS
DecryptDir(
IN HANDLE Target,
IN LPCWSTR TargetName
)
/*++
Routine Description:
Decrypt a directory.
Arguments:
Target -- A handle to the target file or directory.
TargetName -- Target file name. This info is used for error log only.
Return Value:
The status of operation.
--*/
{
NTSTATUS Status = STATUS_SUCCESS;
Status = SendGenFsctl(
Target,
EFS_DECRYPT_STREAM,
EFS_DECRYPT_DIRSTR,
EFS_SET_ENCRYPT,
FSCTL_SET_ENCRYPTION
);
if ( NT_SUCCESS( Status ) ){
Status = SendGenFsctl(
Target,
EFS_DECRYPT_FILE,
EFS_DECRYPT_DIRFILE,
EFS_SET_ENCRYPT,
FSCTL_SET_ENCRYPTION
);
}
return Status;
}
NTSTATUS
RestoreTarget(
IN HANDLE Target,
IN HANDLE TmpFile,
IN LPCWSTR TargetName,
IN LPCWSTR TmpName,
IN HANDLE EventHandleLog,
EFSP_OPERATION Operation
)
/*++
Routine Description:
Copy all the streams in the temp backup file to the original target file.
Arguments:
Target -- A handle to the target file or directory.
TmpFile -- A handle to the temp file if Target is a file.
TargetName -- Target file name. This info is used for error log only.
TmpName -- Temp backup file name. This info is used for error log only.
Operation -- Indicate if encryption or decryption was tried.
Return Value:
The status of operation.
--*/
{
NTSTATUS Status;
DWORD hResult;
PFILE_STREAM_INFORMATION StreamInfoBase = NULL;
ULONG StreamInfoSize = 0;
ULONG StreamCount = 0;
PEFS_STREAM_SIZE StreamSizes;
PHANDLE StreamHandles;
PUNICODE_STRING StreamNames;
Status = GetStreamInformation(
TmpFile,
&StreamInfoBase,
&StreamInfoSize
);
if ( NT_SUCCESS( Status ) ){
hResult = OpenFileStreams(
TmpFile,
FILE_SHARE_DELETE, // have to share with delete-ers, since the main stream is open for delete
OPEN_FOR_FTR,
StreamInfoBase,
FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
NULL,
&StreamNames, // Free this but not the contents!
&StreamHandles, // Free this
&StreamSizes, // Free this
&StreamCount
);
if (hResult == ERROR_SUCCESS) {
ULONG FsInputDataSize;
PUCHAR FsInputData;
PHANDLE TargetStreamHandles;
LONG ArrIndex;
TargetStreamHandles = ( PHANDLE ) LsapAllocateLsaHeap(StreamCount * sizeof (HANDLE));
if ( TargetStreamHandles ){
//
// Open streams at the original target file
//
for ( ArrIndex = 0; ArrIndex < (LONG) StreamCount; ArrIndex++){
if ( StreamHandles[ArrIndex] == TmpFile ){
TargetStreamHandles[ArrIndex] = Target;
} else {
OBJECT_ATTRIBUTES Obja;
IO_STATUS_BLOCK IoStatusBlock;
InitializeObjectAttributes(
&Obja,
&StreamNames[ArrIndex],
0,
Target,
NULL
);
Status = NtCreateFile(
&TargetStreamHandles[ArrIndex],
GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE,
&Obja,
&IoStatusBlock,
NULL,
0,
0,
FILE_OPEN_IF,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
NULL,
0
);
if (!NT_SUCCESS( Status )){
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_TARGET_STREAM_OPEN_ERROR,
NULL,
1,
4,
&TargetName,
&Status
);
}
break;
}
}
}
if ( NT_SUCCESS( Status ) ){
//
// Adjust ArrIndex for clean up
//
ArrIndex--;
//
// Make a FSCTL request input data block
//
FsInputDataSize = 7 * sizeof( ULONG ) + 2 * sizeof(DriverSessionKey);
FsInputData = (PUCHAR) LsapAllocateLsaHeap(FsInputDataSize);
if ( FsInputData ){
BOOLEAN CleanupSuccessful;
( VOID )GetDecryptFsInput(
Target,
FsInputData,
&FsInputDataSize
);
hResult = CopyFileStreams(
StreamHandles, // handles to streams on the backup file
TargetStreamHandles, // Handles to the streams on the original file
StreamCount, // number of streams
StreamSizes, // sizes of streams
Operation, // mark StreamHandles as Decrypted before copy
FsInputData, // FSCTL input data
FsInputDataSize, // FSCTL input data size
&CleanupSuccessful
);
LsapFreeLsaHeap( FsInputData );
if ( hResult != ERROR_SUCCESS ){
if ( EventHandleLog ){
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_STREAM_COPY_ERROR,
NULL,
1,
4,
&TargetName,
&hResult
);
}
Status = STATUS_UNSUCCESSFUL;
}
} else {
//
// Out of memory. Almost impossible during LSA init.
//
ASSERT(FALSE);
Status = STATUS_INSUFFICIENT_RESOURCES;
}
}
//
// Clean up TargetStreamHandles at the target.
//
while (ArrIndex >= 0){
if ( TargetStreamHandles[ArrIndex] != Target ){
CloseHandle(TargetStreamHandles[ArrIndex]);
}
ArrIndex--;
}
LsapFreeLsaHeap( TargetStreamHandles );
}
//
// Clean up StreamHandles and etc.
//
for (ArrIndex = 0; ArrIndex< (LONG) StreamCount ; ArrIndex++) {
if ( StreamHandles[ArrIndex] != TmpFile){
NtClose( StreamHandles[ArrIndex] );
}
}
LsapFreeLsaHeap( StreamHandles);
LsapFreeLsaHeap( StreamNames);
LsapFreeLsaHeap( StreamSizes);
} else {
//
// Not all the requested streams could be opened.
// Write the log info.
//
if ( EventHandleLog ){
LPCWSTR lpStrings[2];
lpStrings[1] = TargetName;
lpStrings[0] = TmpName;
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_TMP_STREAM_OPEN_ERROR,
NULL,
2,
4,
&lpStrings[0],
&hResult
);
}
Status = STATUS_UNSUCCESSFUL;
}
LsapFreeLsaHeap( StreamInfoBase );
} else {
//
// Stream info cannot be got. Write LOG info.
//
if ( EventHandleLog ){
LPCWSTR lpStrings[2];
lpStrings[1] = TargetName;
lpStrings[0] = TmpName;
ReportEvent(
EventHandleLog,
EVENTLOG_ERROR_TYPE,
0,
EFS_TMP_STREAM_INFO_ERROR,
NULL,
2,
4,
&lpStrings[0],
&Status
);
}
}
return Status;
}
BOOL
ParseRecoveryCertificate(
IN PEFS_PUBLIC_KEY_INFO pPublicKeyInfo,
OUT PBYTE * pbHash,
OUT PDWORD cbHash,
OUT PBYTE * pbPublicKey,
OUT PDWORD cbPublicKey,
OUT LPWSTR * lpDisplayInfo,
OUT PCCERT_CONTEXT * pCertContext,
OUT PSID * pSid
)
/*++
Routine Description:
This routine takes a certificate passed in the recovery policy and
extracts the interesting information.
Arguments:
pPublicKeyInfo - Takes the public key info structure from the
recovery policy.
pbHash - Returns the hash of the passed certificate.
cbHash - Returns the lengh in bytes of the returned hash.
pbPublicKey - Returns a pointer to the public key blob of the certificate.
cbPublicKey - Returns the length in bytes of the public key.
lpDisplayInfo - Returns display information about the certificate.
pCertContext - Cert context for the passed certificate.
pSid - Returns SID of the recovery agent
Return Value:
TRUE on success, FALSE on failure. Call GetLastError() for more details.
--*/
{
//
// Get the certificate out of the public key info structure
//
PEFS_PUBLIC_KEY_INFO pAlignedPublicKeyInfo;
BOOLEAN freeAlignedInfo;
DWORD rc = ERROR_SUCCESS;
rc = EfsAlignBlock(
pPublicKeyInfo,
(PVOID *)&pAlignedPublicKeyInfo,
&freeAlignedInfo
);
if (!pAlignedPublicKeyInfo) {
//
// OOM. Treat it as not current.
//
rc = ERROR_NOT_ENOUGH_MEMORY;
return FALSE;
}
ASSERT( pAlignedPublicKeyInfo->KeySourceTag == EfsCertificate );
//
// Initialize OUT parameters
//
*pbHash = NULL;
*pbPublicKey = NULL;
*lpDisplayInfo = NULL;
*pCertContext = NULL;
*pSid = NULL;
PBYTE pbCert = (PBYTE)OFFSET_TO_POINTER(CertificateInfo.Certificate, pAlignedPublicKeyInfo);
DWORD cbCert = pAlignedPublicKeyInfo->CertificateInfo.CertificateLength;
*pCertContext = CertCreateCertificateContext(
CRYPT_ASN_ENCODING,
(const PBYTE)pbCert,
cbCert);
if (*pCertContext) {
PCERT_INFO pCertInfo = (*pCertContext)->pCertInfo;
CERT_PUBLIC_KEY_INFO * pSubjectPublicKeyInfo = &pCertInfo->SubjectPublicKeyInfo;
CRYPT_BIT_BLOB * PublicKey = &pSubjectPublicKeyInfo->PublicKey;
*cbPublicKey = 0;
if (CryptDecodeObject(
CRYPT_ASN_ENCODING,
RSA_CSP_PUBLICKEYBLOB,
PublicKey->pbData,
PublicKey->cbData,
0,
NULL,
cbPublicKey
)) {
if (*pbPublicKey = (PBYTE)LsapAllocateLsaHeap( *cbPublicKey )) {
if (CryptDecodeObject(
CRYPT_ASN_ENCODING,
RSA_CSP_PUBLICKEYBLOB,
PublicKey->pbData,
PublicKey->cbData,
0,
*pbPublicKey,
cbPublicKey
)) {
//
// Get the certificate hash
//
*cbHash = 0;
if (CertGetCertificateContextProperty(
*pCertContext,
CERT_HASH_PROP_ID,
NULL,
cbHash
)) {
*pbHash = (PBYTE)LsapAllocateLsaHeap( *cbHash );
if (*pbHash) {
if (CertGetCertificateContextProperty(
*pCertContext,
CERT_HASH_PROP_ID,
*pbHash,
cbHash
)) {
//
// Get the display information
//
*lpDisplayInfo = EfspGetCertDisplayInformation( *pCertContext );
if (*lpDisplayInfo == NULL) {
rc = GetLastError();
}
//
// Try to get the recovery agent SID
// This info is not very important. If we fail, we should continue.
//
if (pAlignedPublicKeyInfo->PossibleKeyOwner) {
DWORD SidLength;
PSID RecSid = (PSID) OFFSET_TO_POINTER( PossibleKeyOwner, pAlignedPublicKeyInfo );
SidLength = GetLengthSid(RecSid);
*pSid = (PSID)LsapAllocateLsaHeap( SidLength );
if (*pSid) {
RtlCopyMemory( *pSid, RecSid, SidLength );
}
}
} else {
rc = GetLastError();
}
} else {
rc = ERROR_NOT_ENOUGH_MEMORY;
}
} else {
rc = GetLastError();
}
} else {
rc = GetLastError();
}
} else {
rc = ERROR_NOT_ENOUGH_MEMORY;
}
} else {
rc = GetLastError();
}
} else {
rc = GetLastError();
}
if (freeAlignedInfo) {
LsapFreeLsaHeap( pAlignedPublicKeyInfo );
}
if (rc != ERROR_SUCCESS) {
//
// Free the stuff we were going to return
//
if (*pbHash != NULL) {
LsapFreeLsaHeap( *pbHash );
*pbHash = NULL;
}
if (*pbPublicKey != NULL) {
LsapFreeLsaHeap( *pbPublicKey );
*pbPublicKey = NULL;
}
if (*lpDisplayInfo != NULL) {
LsapFreeLsaHeap( *lpDisplayInfo );
*lpDisplayInfo = NULL;
}
if (*pCertContext != NULL) {
CertFreeCertificateContext( *pCertContext );
*pCertContext = NULL;
}
if (*pSid != NULL) {
LsapFreeLsaHeap( *pSid );
*pSid = NULL;
}
}
SetLastError( rc );
return( rc == ERROR_SUCCESS );
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
f9b60149e79b491926054938361c1aaf9ea7e1cf | a59275637441c4c734270f06cc38e42931f6aecc | /openCVCalibSample.cpp | afc6c3a262c033d4a902df6dc3bfc9a0022c0cc9 | [] | no_license | LiuSQ123/zhangCalibration | 2a9edc2810811810f5ec99e5298126f3c391f600 | 88220c206f9488720aabdfb91a57f504c90dfe4c | refs/heads/main | 2023-03-06T23:31:17.736001 | 2021-02-26T15:59:31 | 2021-02-26T15:59:31 | 342,616,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,078 | cpp | //
// Created by liushiqi on 21-2-4.
//
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <time.h>
using namespace cv;
using namespace std;
const char * usage =
" \nexample command line for calibration from a live feed.\n"
" calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe\n"
" \n"
" example command line for calibration from a list of stored images:\n"
" imagelist_creator image_list.xml *.png\n"
" calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe image_list.xml\n"
" where image_list.xml is the standard OpenCV XML/YAML\n"
" use imagelist_creator to create the xml or yaml list\n"
" file consisting of the list of strings, e.g.:\n"
" \n"
"<?xml version=\"1.0\"?>\n"
"<opencv_storage>\n"
"<images>\n"
"view000.png\n"
"view001.png\n"
"<!-- view002.png -->\n"
"view003.png\n"
"view010.png\n"
"one_extra_view.jpg\n"
"</images>\n"
"</opencv_storage>\n";
const char* liveCaptureHelp =
"When the live video from camera is used as input, the following hot-keys may be used:\n"
" <ESC>, 'q' - quit the program\n"
" 'g' - start capturing images\n"
" 'u' - switch undistortion on/off\n";
static void help()
{
printf( "This is a camera calibration sample.\n"
"Usage: calibration\n"
" -w=<board_width> # the number of inner corners per one of board dimension\n"
" -h=<board_height> # the number of inner corners per another board dimension\n"
" [-pt=<pattern>] # the type of pattern: chessboard or circles' grid\n"
" [-n=<number_of_frames>] # the number of frames to use for calibration\n"
" # (if not specified, it will be set to the number\n"
" # of board views actually available)\n"
" [-d=<delay>] # a minimum delay in ms between subsequent attempts to capture a next view\n"
" # (used only for video capturing)\n"
" [-s=<squareSize>] # square size in some user-defined units (1 by default)\n"
" [-o=<out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n"
" [-op] # write detected feature points\n"
" [-oe] # write extrinsic parameters\n"
" [-zt] # assume zero tangential distortion\n"
" [-a=<aspectRatio>] # fix aspect ratio (fx/fy)\n"
" [-p] # fix the principal point at the center\n"
" [-v] # flip the captured images around the horizontal axis\n"
" [-V] # use a video file, and not an image list, uses\n"
" # [input_data] string for the video file name\n"
" [-su] # show undistorted images after calibration\n"
" [input_data] # input data, one of the following:\n"
" # - text file with a list of the images of the board\n"
" # the text file can be generated with imagelist_creator\n"
" # - name of video file with a video of the board\n"
" # if input_data not specified, a live view from the camera is used\n"
"\n" );
printf("\n%s",usage);
printf( "\n%s", liveCaptureHelp );
}
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
enum Pattern { CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
static double computeReprojectionErrors(
const vector<vector<Point3f> >& objectPoints,
const vector<vector<Point2f> >& imagePoints,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const Mat& cameraMatrix, const Mat& distCoeffs,
vector<float>& perViewErrors )
{
vector<Point2f> imagePoints2;
int i, totalPoints = 0;
double totalErr = 0, err;
perViewErrors.resize(objectPoints.size());
for( i = 0; i < (int)objectPoints.size(); i++ )
{
projectPoints(Mat(objectPoints[i]), rvecs[i], tvecs[i],
cameraMatrix, distCoeffs, imagePoints2);
err = norm(Mat(imagePoints[i]), Mat(imagePoints2), NORM_L2);
int n = (int)objectPoints[i].size();
perViewErrors[i] = (float)std::sqrt(err*err/n);
totalErr += err*err;
totalPoints += n;
}
return std::sqrt(totalErr/totalPoints);
}
static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners, Pattern patternType = CHESSBOARD)
{
corners.resize(0);
switch(patternType)
{
case CHESSBOARD:
case CIRCLES_GRID:
for( int i = 0; i < boardSize.height; i++ )
for( int j = 0; j < boardSize.width; j++ )
corners.push_back(Point3f(float(j*squareSize),
float(i*squareSize), 0));
break;
case ASYMMETRIC_CIRCLES_GRID:
for( int i = 0; i < boardSize.height; i++ )
for( int j = 0; j < boardSize.width; j++ )
corners.push_back(Point3f(float((2*j + i % 2)*squareSize),
float(i*squareSize), 0));
break;
default:
CV_Error(Error::StsBadArg, "Unknown pattern type\n");
}
}
static bool runCalibration( vector<vector<Point2f> > imagePoints,
Size imageSize, Size boardSize, Pattern patternType,
float squareSize, float aspectRatio,
int flags, Mat& cameraMatrix, Mat& distCoeffs,
vector<Mat>& rvecs, vector<Mat>& tvecs,
vector<float>& reprojErrs,
double& totalAvgErr)
{
cameraMatrix = Mat::eye(3, 3, CV_64F);
if( flags & CALIB_FIX_ASPECT_RATIO )
cameraMatrix.at<double>(0,0) = aspectRatio;
distCoeffs = Mat::zeros(8, 1, CV_64F);
vector<vector<Point3f> > objectPoints(1);
calcChessboardCorners(boardSize, squareSize, objectPoints[0], patternType);
objectPoints.resize(imagePoints.size(),objectPoints[0]);
double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K4|CALIB_FIX_K5);
///*|CALIB_FIX_K3*/|CALIB_FIX_K4|CALIB_FIX_K5);
printf("RMS error reported by calibrateCamera: %g\n", rms);
bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
return ok;
}
static void saveCameraParams( const string& filename,
Size imageSize, Size boardSize,
float squareSize, float aspectRatio, int flags,
const Mat& cameraMatrix, const Mat& distCoeffs,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const vector<float>& reprojErrs,
const vector<vector<Point2f> >& imagePoints,
double totalAvgErr )
{
FileStorage fs( filename, FileStorage::WRITE );
time_t tt;
time( &tt );
struct tm *t2 = localtime( &tt );
char buf[1024];
strftime( buf, sizeof(buf)-1, "%c", t2 );
fs << "calibration_time" << buf;
if( !rvecs.empty() || !reprojErrs.empty() )
fs << "nframes" << (int)std::max(rvecs.size(), reprojErrs.size());
fs << "image_width" << imageSize.width;
fs << "image_height" << imageSize.height;
fs << "board_width" << boardSize.width;
fs << "board_height" << boardSize.height;
fs << "square_size" << squareSize;
if( flags & CALIB_FIX_ASPECT_RATIO )
fs << "aspectRatio" << aspectRatio;
if( flags != 0 )
{
sprintf( buf, "flags: %s%s%s%s",
flags & CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
flags & CALIB_FIX_ASPECT_RATIO ? "+fix_aspectRatio" : "",
flags & CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
flags & CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
//cvWriteComment( *fs, buf, 0 );
}
fs << "flags" << flags;
fs << "camera_matrix" << cameraMatrix;
fs << "distortion_coefficients" << distCoeffs;
fs << "avg_reprojection_error" << totalAvgErr;
if( !reprojErrs.empty() )
fs << "per_view_reprojection_errors" << Mat(reprojErrs);
if( !rvecs.empty() && !tvecs.empty() )
{
CV_Assert(rvecs[0].type() == tvecs[0].type());
Mat bigmat((int)rvecs.size(), 6, rvecs[0].type());
for( int i = 0; i < (int)rvecs.size(); i++ )
{
Mat r = bigmat(Range(i, i+1), Range(0,3));
Mat t = bigmat(Range(i, i+1), Range(3,6));
CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);
CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);
//*.t() is MatExpr (not Mat) so we can use assignment operator
r = rvecs[i].t();
t = tvecs[i].t();
}
//cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
fs << "extrinsic_parameters" << bigmat;
}
if( !imagePoints.empty() )
{
Mat imagePtMat((int)imagePoints.size(), (int)imagePoints[0].size(), CV_32FC2);
for( int i = 0; i < (int)imagePoints.size(); i++ )
{
Mat r = imagePtMat.row(i).reshape(2, imagePtMat.cols);
Mat imgpti(imagePoints[i]);
imgpti.copyTo(r);
}
fs << "image_points" << imagePtMat;
}
}
static bool readStringList( const string& filename, vector<string>& l )
{
l.resize(0);
FileStorage fs(filename, FileStorage::READ);
if( !fs.isOpened() )
return false;
size_t dir_pos = filename.rfind('/');
if (dir_pos == string::npos)
dir_pos = filename.rfind('\\');
FileNode n = fs.getFirstTopLevelNode();
if( n.type() != FileNode::SEQ )
return false;
FileNodeIterator it = n.begin(), it_end = n.end();
for( ; it != it_end; ++it )
{
string fname = (string)*it;
if (dir_pos != string::npos)
{
string fpath = samples::findFile(filename.substr(0, dir_pos + 1) + fname, false);
if (fpath.empty())
{
fpath = samples::findFile(fname);
}
fname = fpath;
}
else
{
fname = samples::findFile(fname);
}
l.push_back(fname);
}
return true;
}
static bool runAndSave(const string& outputFilename,
const vector<vector<Point2f> >& imagePoints,
Size imageSize, Size boardSize, Pattern patternType, float squareSize,
float aspectRatio, int flags, Mat& cameraMatrix,
Mat& distCoeffs, bool writeExtrinsics, bool writePoints )
{
vector<Mat> rvecs, tvecs;
vector<float> reprojErrs;
double totalAvgErr = 0;
bool ok = runCalibration(imagePoints, imageSize, boardSize, patternType, squareSize,
aspectRatio, flags, cameraMatrix, distCoeffs,
rvecs, tvecs, reprojErrs, totalAvgErr);
printf("%s. avg reprojection error = %.2f\n",
ok ? "Calibration succeeded" : "Calibration failed",
totalAvgErr);
if( ok )
saveCameraParams( outputFilename, imageSize,
boardSize, squareSize, aspectRatio,
flags, cameraMatrix, distCoeffs,
writeExtrinsics ? rvecs : vector<Mat>(),
writeExtrinsics ? tvecs : vector<Mat>(),
writeExtrinsics ? reprojErrs : vector<float>(),
writePoints ? imagePoints : vector<vector<Point2f> >(),
totalAvgErr );
return ok;
}
int main( int argc, char** argv )
{
Size boardSize, imageSize;
float squareSize, aspectRatio;
Mat cameraMatrix, distCoeffs;
string outputFilename;
string inputFilename = "";
int i, nframes;
bool writeExtrinsics, writePoints;
bool undistortImage = false;
int flags = 0;
VideoCapture capture;
bool flipVertical;
bool showUndistorted;
bool videofile;
int delay;
clock_t prevTimestamp = 0;
int mode = DETECTION;
int cameraId = 0;
vector<vector<Point2f> > imagePoints;
vector<string> imageList;
Pattern pattern = CHESSBOARD;
cv::CommandLineParser parser(argc, argv,
"{help ||}{w||}{h||}{pt|chessboard|}{n|10|}{d|1000|}{s|1|}{o|out_camera_data.yml|}"
"{op||}{oe||}{zt||}{a|1|}{p||}{v||}{V||}{su||}"
"{@input_data|0|}");
if (parser.has("help"))
{
help();
return 0;
}
boardSize.width = parser.get<int>( "w" );
boardSize.height = parser.get<int>( "h" );
if ( parser.has("pt") )
{
string val = parser.get<string>("pt");
if( val == "circles" )
pattern = CIRCLES_GRID;
else if( val == "acircles" )
pattern = ASYMMETRIC_CIRCLES_GRID;
else if( val == "chessboard" )
pattern = CHESSBOARD;
else
return fprintf( stderr, "Invalid pattern type: must be chessboard or circles\n" ), -1;
}
squareSize = parser.get<float>("s");
nframes = parser.get<int>("n");
aspectRatio = parser.get<float>("a");
delay = parser.get<int>("d");
writePoints = parser.has("op");
writeExtrinsics = parser.has("oe");
if (parser.has("a"))
flags |= CALIB_FIX_ASPECT_RATIO;
if ( parser.has("zt") )
flags |= CALIB_ZERO_TANGENT_DIST;
if ( parser.has("p") )
flags |= CALIB_FIX_PRINCIPAL_POINT;
flipVertical = parser.has("v");
videofile = parser.has("V");
if ( parser.has("o") )
outputFilename = parser.get<string>("o");
showUndistorted = parser.has("su");
if ( isdigit(parser.get<string>("@input_data")[0]) )
cameraId = parser.get<int>("@input_data");
else
inputFilename = parser.get<string>("@input_data");
if (!parser.check())
{
help();
parser.printErrors();
return -1;
}
if ( squareSize <= 0 )
return fprintf( stderr, "Invalid board square width\n" ), -1;
if ( nframes <= 3 )
return printf("Invalid number of images\n" ), -1;
if ( aspectRatio <= 0 )
return printf( "Invalid aspect ratio\n" ), -1;
if ( delay <= 0 )
return printf( "Invalid delay\n" ), -1;
if ( boardSize.width <= 0 )
return fprintf( stderr, "Invalid board width\n" ), -1;
if ( boardSize.height <= 0 )
return fprintf( stderr, "Invalid board height\n" ), -1;
if( !inputFilename.empty() )
{
if( !videofile && readStringList(samples::findFile(inputFilename), imageList) )
mode = CAPTURING;
else
capture.open(samples::findFileOrKeep(inputFilename));
}
else
capture.open(cameraId);
if( !capture.isOpened() && imageList.empty() )
return fprintf( stderr, "Could not initialize video (%d) capture\n",cameraId ), -2;
if( !imageList.empty() )
nframes = (int)imageList.size();
if( capture.isOpened() )
printf( "%s", liveCaptureHelp );
namedWindow( "Image View", 1 );
for(i = 0;;i++)
{
Mat view, viewGray;
bool blink = false;
if( capture.isOpened() )
{
Mat view0;
capture >> view0;
view0.copyTo(view);
}
else if( i < (int)imageList.size() )
view = imread(imageList[i], 1);
if(view.empty())
{
if( imagePoints.size() > 0 )
runAndSave(outputFilename, imagePoints, imageSize,
boardSize, pattern, squareSize, aspectRatio,
flags, cameraMatrix, distCoeffs,
writeExtrinsics, writePoints);
break;
}
imageSize = view.size();
if( flipVertical )
flip( view, view, 0 );
vector<Point2f> pointbuf;
cvtColor(view, viewGray, COLOR_BGR2GRAY);
bool found;
switch( pattern )
{
case CHESSBOARD:
found = findChessboardCorners( view, boardSize, pointbuf,
CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE);
break;
case CIRCLES_GRID:
found = findCirclesGrid( view, boardSize, pointbuf );
break;
case ASYMMETRIC_CIRCLES_GRID:
found = findCirclesGrid( view, boardSize, pointbuf, CALIB_CB_ASYMMETRIC_GRID );
break;
default:
return fprintf( stderr, "Unknown pattern type\n" ), -1;
}
// improve the found corners' coordinate accuracy
if( pattern == CHESSBOARD && found) cornerSubPix( viewGray, pointbuf, Size(11,11),
Size(-1,-1), TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 30, 0.1 ));
if( mode == CAPTURING && found &&
(!capture.isOpened() || clock() - prevTimestamp > delay*1e-3*CLOCKS_PER_SEC) )
{
imagePoints.push_back(pointbuf);
prevTimestamp = clock();
blink = capture.isOpened();
}
if(found)
drawChessboardCorners( view, boardSize, Mat(pointbuf), found );
string msg = mode == CAPTURING ? "100/100" :
mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
int baseLine = 0;
Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
Point textOrigin(view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10);
if( mode == CAPTURING )
{
if(undistortImage)
msg = format( "%d/%d Undist", (int)imagePoints.size(), nframes );
else
msg = format( "%d/%d", (int)imagePoints.size(), nframes );
}
putText( view, msg, textOrigin, 1, 1,
mode != CALIBRATED ? Scalar(0,0,255) : Scalar(0,255,0));
if( blink )
bitwise_not(view, view);
if( mode == CALIBRATED && undistortImage )
{
Mat temp = view.clone();
undistort(temp, view, cameraMatrix, distCoeffs);
}
imshow("Image View", view);
char key = (char)waitKey(capture.isOpened() ? 50 : 500);
if( key == 27 )
break;
if( key == 'u' && mode == CALIBRATED )
undistortImage = !undistortImage;
if( capture.isOpened() && key == 'g' )
{
mode = CAPTURING;
imagePoints.clear();
}
if( mode == CAPTURING && imagePoints.size() >= (unsigned)nframes )
{
if( runAndSave(outputFilename, imagePoints, imageSize,
boardSize, pattern, squareSize, aspectRatio,
flags, cameraMatrix, distCoeffs,
writeExtrinsics, writePoints))
mode = CALIBRATED;
else
mode = DETECTION;
if( !capture.isOpened() )
break;
}
}
if( !capture.isOpened() && showUndistorted )
{
Mat view, rview, map1, map2;
initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),
getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
imageSize, CV_16SC2, map1, map2);
for( i = 0; i < (int)imageList.size(); i++ )
{
view = imread(imageList[i], 1);
if(view.empty())
continue;
//undistort( view, rview, cameraMatrix, distCoeffs, cameraMatrix );
remap(view, rview, map1, map2, INTER_LINEAR);
imshow("Image View", rview);
char c = (char)waitKey();
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
}
return 0;
}
| [
"shiqi6767@sina.com"
] | shiqi6767@sina.com |
9d7d5643e52dd136fb9b0a463307bc8c164fa254 | 31017c778a915b8d159eb5dea65bef8f0301a515 | /src/rpcdump.cpp | fd04ae9860d068a4c4e770ffe58323da404abffa | [
"MIT"
] | permissive | DaniilM/csbank-source | 75196ea1340c916e15e595c63b2eacb73e1f5f8b | d8bb96fecee29d8259394c82196d565e72b799e7 | refs/heads/master | 2020-03-27T20:50:16.250895 | 2018-06-17T21:26:56 | 2018-06-17T21:26:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,076 | cpp | // Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "main.h"
#include "script/script.h"
#include "script/standard.h"
#include "sync.h"
#include "util.h"
#include "utiltime.h"
#include "wallet.h"
#include <fstream>
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "json/json_spirit_value.h"
using namespace json_spirit;
using namespace std;
void EnsureWalletIsUnlocked();
std::string static EncodeDumpTime(int64_t nTime) {
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
int64_t static DecodeDumpTime(const std::string &str) {
static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
static const std::locale loc(std::locale::classic(),
new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
std::istringstream iss(str);
iss.imbue(loc);
boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
iss >> ptime;
if (ptime.is_not_a_date_time())
return 0;
return (ptime - epoch).total_seconds();
}
std::string static EncodeDumpString(const std::string &str) {
std::stringstream ret;
BOOST_FOREACH(unsigned char c, str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos+2 < str.length()) {
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
pos += 2;
}
ret << c;
}
return ret.str();
}
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey \"csbankprivkey\" ( \"label\" rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet.\n"
"\nArguments:\n"
"1. \"csbankprivkey\" (string, required) The private key (see dumpprivkey)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nDump a private key\n"
+ HelpExampleCli("dumpprivkey", "\"myaddress\"") +
"\nImport the private key with rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\"") +
"\nImport using a label and without rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")
);
EnsureWalletIsUnlocked();
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
CKey key = vchSecret.GetKey();
if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
{
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, strLabel, "receive");
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress))
return Value::null;
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(key, pubkey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
// whenever a key is imported, we need to scan the whole chain
pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'
if (fRescan) {
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
}
return Value::null;
}
Value importaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importaddress \"address\" ( \"label\" rescan )\n"
"\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n"
"1. \"address\" (string, required) The address\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nImport an address with rescan\n"
+ HelpExampleCli("importaddress", "\"myaddress\"") +
"\nImport using a label without rescan\n"
+ HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")
);
CScript script;
CBitcoinAddress address(params[0].get_str());
if (address.IsValid()) {
script = GetScriptForDestination(address.Get());
} else if (IsHex(params[0].get_str())) {
std::vector<unsigned char> data(ParseHex(params[0].get_str()));
script = CScript(data.begin(), data.end());
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CSbank address or script");
}
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
{
if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE)
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
// add to address book or update label
if (address.IsValid())
pwalletMain->SetAddressBook(address.Get(), strLabel, "receive");
// Don't throw error in case an address is already there
if (pwalletMain->HaveWatchOnly(script))
return Value::null;
pwalletMain->MarkDirty();
if (!pwalletMain->AddWatchOnly(script))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
if (fRescan)
{
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
}
return Value::null;
}
Value importwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"importwallet \"filename\"\n"
"\nImports keys from a wallet dump file (see dumpwallet).\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The wallet file\n"
"\nExamples:\n"
"\nDump the wallet\n"
+ HelpExampleCli("dumpwallet", "\"test\"") +
"\nImport the wallet\n"
+ HelpExampleCli("importwallet", "\"test\"") +
"\nImport using the json rpc call\n"
+ HelpExampleRpc("importwallet", "\"test\"")
);
EnsureWalletIsUnlocked();
ifstream file;
file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate);
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
bool fGood = true;
int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
file.seekg(0, file.beg);
pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
while (file.good()) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(vstr[0]))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwalletMain->SetAddressBook(keyid, strLabel, "receive");
nTimeBegin = std::min(nTimeBegin, nTime);
}
file.close();
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
CBlockIndex *pindex = chainActive.Tip();
while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200)
pindex = pindex->pprev;
if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
pwalletMain->nTimeFirstKey = nTimeBegin;
LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1);
pwalletMain->ScanForWalletTransactions(pindex);
pwalletMain->MarkDirty();
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey \"csbankaddress\"\n"
"\nReveals the private key corresponding to 'csbankaddress'.\n"
"Then the importprivkey can be used with this output\n"
"\nArguments:\n"
"1. \"csbankaddress\" (string, required) The csbank address for the private key\n"
"\nResult:\n"
"\"key\" (string) The private key\n"
"\nExamples:\n"
+ HelpExampleCli("dumpprivkey", "\"myaddress\"")
+ HelpExampleCli("importprivkey", "\"mykey\"")
+ HelpExampleRpc("dumpprivkey", "\"myaddress\"")
);
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CSbank address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CKey vchSecret;
if (!pwalletMain->GetKey(keyID, vchSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret).ToString();
}
Value dumpwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpwallet \"filename\"\n"
"\nDumps all wallet keys in a human-readable format.\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename\n"
"\nExamples:\n"
+ HelpExampleCli("dumpwallet", "\"test\"")
+ HelpExampleRpc("dumpwallet", "\"test\"")
);
EnsureWalletIsUnlocked();
ofstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CKeyID, int64_t> mapKeyBirth;
std::set<CKeyID> setKeyPool;
pwalletMain->GetKeyBirthTimes(mapKeyBirth);
pwalletMain->GetAllReserveKeys(setKeyPool);
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
vKeyBirth.push_back(std::make_pair(it->second, it->first));
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by CSbank %s (%s)\n", CLIENT_BUILD, CLIENT_DATE);
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr = CBitcoinAddress(keyid).ToString();
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
if (pwalletMain->mapAddressBook.count(keyid)) {
file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr);
} else if (setKeyPool.count(keyid)) {
file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
} else {
file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
}
}
}
file << "\n";
file << "# End of dump\n";
file.close();
return Value::null;
}
| [
"ypikass@gmail.com"
] | ypikass@gmail.com |
285d625e1447b21ab5a4d62dfab14147e93f149a | 8095a10eee005ef108b3fa68c10099d74c6a518e | /Algorithms/SieveOfEratosthenes/sieve_of_eratosthenes.cpp | bc7b298e904881449d665f91273c390bb4aa70f0 | [] | no_license | bitakshat/DSA | 49b49d809601cdd1b98c75d19fbd53dbfd638770 | 658b64627f19706a7a2949a21d9c0b7abecd9241 | refs/heads/master | 2023-04-09T16:30:04.278128 | 2021-04-24T08:53:54 | 2021-04-24T08:53:54 | 270,334,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cpp | #include <bits/stdc++.h>
void sieve_of_eratosthenes( int n ) {
bool prime[n+1];
memset(prime, true, sizeof(prime));
int p = 2;
for( int i=p; i<=n; ++i ) {
if( prime[i] == true) {
for( int j=i*i; j<=n; j+=i ) {
prime[j] = false;
}
}
}
std::cout <<"Prime numbers in range " << n << ": ";
/*Printing all prime numbers*/
for( int x=2; x<=n; x++ ) {
if( prime[x] ){
std::cout << x << " ";
}
}
}
int main( void ) {
sieve_of_eratosthenes(10);
return 0;
}
| [
"akshatpal1232@gmail.com"
] | akshatpal1232@gmail.com |
72bccb5f7e1bf4cf8aa7e7af4f880e8739f3270d | 31f70eb188d1ad6f354b3e0edee3aeec41534671 | /addjournalvoucher.h | 065504053910f8b9400cc36199c83177bdc4af90 | [
"MIT"
] | permissive | miantanveer/bizjust-erp | a25082916638e4fa518b1ec553c0b49203ca103b | d3291e212bf89ab6e753194127b3951afcd02548 | refs/heads/master | 2023-04-13T06:03:27.441353 | 2020-12-20T19:42:50 | 2020-12-20T19:42:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | h | #ifndef ADDJOURNALVOUCHER_H
#define ADDJOURNALVOUCHER_H
#include <QWidget>
#include "dbcon.h"
#include "erp.h"
#include <QCompleter>
#include "sch.h"
namespace Ui {
class AddJournalVoucher;
}
class AddJournalVoucher : public QWidget
{
Q_OBJECT
public:
QString loginid;
DbCon conn;
ERP erp;
SCH sch;
explicit AddJournalVoucher(QWidget *parent = 0);
~AddJournalVoucher();
private slots:
void autocompleter(QString sql, QLineEdit *txt1, QLineEdit *txt2);
void onItemHighlighted(const QModelIndex &index);
void editingFinished();
void on_accountname_textEdited(const QString &arg1);
void on_btn_add_clicked();
void on_btn_delete_row_clicked();
void on_btn_save_clicked();
void on_companytype_currentIndexChanged(int index);
void on_debit_valueChanged(double arg1);
void on_credit_valueChanged(double arg1);
private:
Ui::AddJournalVoucher *ui;
enum columns{
COMPANYTYPE,ACCOUNTNAME,ACCOUNTID,DESCRIPTION,DEBIT,CREDIT
};
void loadform();
void checktotal();
void clearForm();
};
#endif // ADDJOURNALVOUCHER_H
| [
"mr.tanveer007@gmail.com"
] | mr.tanveer007@gmail.com |
22fe03a9bb8948b9fccdb1f2ea7d6eb2bf48d7e0 | 9f3066aa79684c083156e4fe3d6f9134ca6ca659 | /BOJ[C++,STL]/10815.cpp | 007a09ef24cce834ee93421f224ecd63d247a129 | [] | no_license | morenerom/Algorithm_study | 7d9a4321fa361bf0fa5ef8031b258fa66144c1cb | 088dbac5d577d59f3b9ccd16320af56288581a20 | refs/heads/master | 2020-03-26T02:13:42.575332 | 2018-10-26T09:10:33 | 2018-10-26T09:10:33 | 144,401,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp | #include <iostream>
#include <set>
using namespace std;
int main() {
int n, tmp, m, marr[500001];
set<int> s;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> tmp;
s.insert(tmp);
}
cin >> m;
for (int i = 0; i < m; i++)
cin >> marr[i];
for (int i = 0; i < m; i++) {
if (s.find(marr[i]) == s.end())
cout << '0';
else
cout << '1';
if (i != m - 1)
cout << ' ';
else
cout << '\n';
}
return 0;
} | [
"audtmd5517@naver.com"
] | audtmd5517@naver.com |
dd3fd436ebdb20674f15fc050b63a4e8e23aad72 | cfd8a69953cdbaec0365dff77b36359446c7f712 | /tpIntegrador.1/Subject.cpp | 94ba3d1ef933e87e97bc6b05fcb6ade77fd1dcaa | [] | no_license | charlyfigue/tpIntegrador.1 | 054c5093872e5a9b42703ce8b44937ef281c3aae | 7da5b6c9baed7f7bcfbbb6ac010461f235e073d8 | refs/heads/master | 2020-08-29T02:06:32.306963 | 2019-11-04T16:53:47 | 2019-11-04T16:53:47 | 217,889,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | #include "Subject.h"
using namespace std;
void
Subject::attach(observer * observerPtr)
{
listOfObservers.push_back(observerPtr);
}
void
Subject::detach(observer * observerPtr)
{
listOfObservers.remove(observerPtr);
}
void
Subject::notifyAllObservers(void)
{
list<observer * >::iterator it;
for(it= listOfObservers.begin(); it != listOfObservers.end(); it++)
(*it)->update(this);
}
| [
"carlitoxfigue@yahoo.com.ar"
] | carlitoxfigue@yahoo.com.ar |
fd6f6d396305c12a0df39fa40c2a3979557ffc37 | 1f71511bcc0439a84720cd510e643c6d1a384657 | /moriServer/src/OrderFlow/EOS_ZB_LIST_EXAMINE_FAIL.cpp | f4802a5effd837e0f54799e7615bda793eb37c44 | [] | no_license | litao1009/SimpleServer | b01d1df3bf3f4a753ffd55c13c63d82beaf3912d | 1d101eb3f250107f52c4ecb3a30bed54e7ab5cce | refs/heads/master | 2021-01-20T18:53:02.726656 | 2016-07-29T08:30:45 | 2016-07-29T08:30:45 | 64,483,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,893 | cpp | #include "COrderState.h"
#include "Tool/LSTool.h"
IMPLEMENT_ORDERSTATE_MEMBER(order::EOS_ZB_LIST_EXAMINE_FAIL);
COrderState<order::EOS_ZB_LIST_EXAMINE_FAIL>::COrderState()
{
UpdateStatusFtr_ = [](GL_OrderInfo_Data& statusInfo,const SUserInfo& userInfo, const AStringType& comment)
{
statusInfo.ListAuditContent_ = comment;
};
}
template<>
IOrderState::NextStateList& COrderState<order::EOS_ZB_LIST_EXAMINE_FAIL>::_Init()
{
{
auto ftr = [](const SUserInfo& userInfo, const GL_OrderInfo_Data& statusInfo, bool allowEmpty)
{
if ( !_OrderVerify(userInfo, statusInfo) )
{
return false;
}
return true;
};
_GetNextStateList().emplace(order::EOS_ZB_SAVE, ftr);
}
return _GetNextStateList();
}
template<>
bool COrderState<order::EOS_ZB_LIST_EXAMINE_FAIL>::_PeekStateCondition(const SUserInfo& userInfo)
{
return false;
}
template<>
bool COrderState<order::EOS_ZB_LIST_EXAMINE_FAIL>::_OrderVerify(const SUserInfo& userInfo, const GL_OrderInfo_Data& statusInfo, bool isPeek)
{
return *userInfo.UserInfo_.UserID_ == *statusInfo.DesignerID_;
}
transMsg::EReturnStatus COrderState<order::EOS_ZB_LIST_EXAMINE_FAIL>::_DownloadOrder(const SUserInfo& userInfo, const GL_OrderInfo_Data& statusInfo, transMsg::ETableType tableType, AStringType& buffer, PathType& orderFile, soci::session& sql)
{
auto state = IOrderState::Factory(order::EOS_ZB_LIST_EXAMINE_DURING);
return state->Download(userInfo, statusInfo, tableType, buffer, orderFile, sql);
}
transMsg::EReturnStatus COrderState<order::EOS_ZB_LIST_EXAMINE_FAIL>::_UploadOrder( const SUserInfo& userInfo, const GL_OrderInfo_Data& statusInfo, AStringType& buffer, const PathType& orderFile, soci::session& sql )
{
return transMsg::ERS_ORDER_DENY;
}
void COrderState<order::EOS_ZB_LIST_EXAMINE_FAIL>::_PostOnChange( const SUserInfo& userInfo, GL_OrderInfo_Data& statusInfo, soci::session& sql )
{
} | [
"litao1009@gmail.com"
] | litao1009@gmail.com |
522d45de966f852cbb7919dce26ac13275b54182 | 57268daafd77c9a0073d7624ce07a75238c1366f | /11STACKS_QUEUES/02CleverStack/06Infix2Postfix.cpp | f55841b952b84193dbe01f5e06242e8425050495 | [] | no_license | EdgeLord836/DATA-STRUCTURES | 410c18a7ef623bb5ded22673fc154a98901b0302 | 18d64778b76648dda0682a07521a3ed63fd86607 | refs/heads/master | 2022-11-08T19:30:46.146375 | 2020-06-29T16:29:01 | 2020-06-29T16:29:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,547 | cpp | string Solution::solve(string A) {
std::unordered_map<char, int> precedenceMap;
precedenceMap.insert({'(', 0});
precedenceMap.insert({'^', 3});
precedenceMap.insert({'/', 2});
precedenceMap.insert({'*', 2});
precedenceMap.insert({'+', 1});
precedenceMap.insert({'-', 1});
std::string output;
std::stack<char> operatorStack;
for (int i = 0; i < A.size(); i++) {
if (A[i] != '(' && precedenceMap.count(A[i])) {
if (operatorStack.empty()) {
operatorStack.push(A[i]);
} else {
if (precedenceMap[operatorStack.top()] >= precedenceMap[A[i]]) {
while (!operatorStack.empty() && precedenceMap[operatorStack.top()] >= precedenceMap[A[i]]) {
output += operatorStack.top();
operatorStack.pop();
}
operatorStack.push(A[i]);
} else {
operatorStack.push(A[i]);
}
}
} else if (A[i] == '(') {
operatorStack.push(A[i]);
} else if (A[i] == ')') {
while (operatorStack.top() != '(') {
output += operatorStack.top();
operatorStack.pop();
}
operatorStack.pop();
} else {
output += A[i];
}
}
while (!operatorStack.empty()) {
output += operatorStack.top();
operatorStack.pop();
}
return output;
}
| [
"behlsachin47@gmail.com"
] | behlsachin47@gmail.com |
9b3bb7b08d8e5c078cc281e80926426dd324a702 | 69e2e5fb5220d3311b9d1e4c2bb2f6c1722a156a | /altona_wz4/wz4/wz4player/selector_win.cpp | 67b8d68455800c8519e62624b7121c6d52fe83a4 | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | kebby/fr_public | c2acb4787472c5e039805a084894a7858dd6d19a | 2bb82d30bf9d10cf2a94b445710942ac9f065391 | refs/heads/master | 2021-01-16T00:36:57.267206 | 2012-08-16T03:36:05 | 2012-08-16T03:36:05 | 4,026,092 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,970 | cpp | /*+**************************************************************************/
/*** ***/
/*** This file is distributed under a BSD license. ***/
/*** See LICENSE.txt for details. ***/
/*** ***/
/**************************************************************************+*/
#define MULTISAMPLING 1
/****************************************************************************/
#include "selector_win.hpp"
#include "wz4lib/doc.hpp"
#if sPLATFORM==sPLAT_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shellapi.h>
extern HWND sHWND;
/****************************************************************************/
namespace bob
{
static WNDCLASSEX SelWinClass;
static WNDCLASSEX LinkClass;
static HWND SelWin;
static sBool Done;
static const bSelectorSetup *Setup;
static bSelectorResult *Result;
static sScreenInfo *SI;
static sArray<sScreenInfoXY> Aspects;
// size of dialog window
//static const sInt H=160;
// dialog window members
static HFONT CaptionFont;
static HICON LinkIcon;
static HWND ResBox, AspectBox, FSAABox, FSCheck, VSCheck, LoopCheck, BenchmarkCheck, Die, Demo,CoreCheck,LowQCheck,HiddenPartBox;
struct Link
{
HWND Wnd;
HICON Icon;
Link() : Wnd(0), Icon(0) {}
};
sArray<Link> Links;
// reads controls and fills out results struct
static void FillResults()
{
sScreenMode &m=Result->Mode;
sInt res=SendMessage(ResBox,CB_GETCURSEL,0,0);
sInt asp=SendMessage(AspectBox,CB_GETCURSEL,0,0);
sInt fsaa = 0;
if(MULTISAMPLING)
fsaa=SendMessage(FSAABox,CB_GETCURSEL,0,0);
sBool fullscreen=SendMessage(FSCheck,BM_GETCHECK,0,0)==BST_CHECKED;
sBool vsync=SendMessage(VSCheck,BM_GETCHECK,0,0)==BST_CHECKED;
sBool loop=SendMessage(LoopCheck,BM_GETCHECK,0,0)==BST_CHECKED;
sBool core = SendMessage(CoreCheck,BM_GETCHECK,0,0)==BST_CHECKED;
sBool lowq = SendMessage(LowQCheck,BM_GETCHECK,0,0)==BST_CHECKED;
sBool benchmark=sFALSE;
if (Setup->DialogFlags & wDODF_Benchmark)
benchmark=SendMessage(BenchmarkCheck,BM_GETCHECK,0,0)==BST_CHECKED;
//sBool mblur=SendMessage(MBlurCheck,BM_GETCHECK,0,0)==BST_CHECKED;
sInt hp = SendMessage(HiddenPartBox,CB_GETCURSEL,0,0);
m.Display=-1; // use default
m.ScreenX=SI->Resolutions[res].x;
m.ScreenY=SI->Resolutions[res].y;
if (asp)
m.Aspect=sF32(Aspects[asp-1].x)/sF32(Aspects[asp-1].y);
else
m.Aspect=sF32(m.ScreenX)/sF32(m.ScreenY);
m.MultiLevel=fsaa-1;
m.Flags=sSM_VALID;
if (fullscreen) m.Flags|=sSM_FULLSCREEN;
if (!vsync) m.Flags|=sSM_NOVSYNC;
Result->Loop=loop;
Result->Benchmark=benchmark;
Result->OneCoreForOS = core;
Result->LowQuality = lowq;
Result->HiddenPart = hp-1;
Done=1;
}
static HWND AddStatic(const sChar *text,sInt x,sInt y,sInt w, sBool caption=sFALSE, sBool disabled=sFALSE)
{
sInt h=caption?30:20;
HWND wnd=CreateWindowEx(0,L"STATIC",text,WS_VISIBLE|WS_CHILD|(disabled?WS_DISABLED:0),x,y,w,h,SelWin,0,0,0);
SendMessage(wnd,WM_SETFONT,(WPARAM)(caption?CaptionFont:GetStockObject(DEFAULT_GUI_FONT)),0);
return wnd;
}
static HWND AddButton(const sChar *text,sInt x,sInt y, sInt w,sBool deflt)
{
if (!w) w=80;
sInt style=WS_VISIBLE|WS_CHILD|WS_TABSTOP;
if (deflt) style|=BS_DEFPUSHBUTTON; else style|=BS_PUSHBUTTON;
HWND wnd=CreateWindowEx(0,L"BUTTON",text,style,x,y,w,25,SelWin,0,0,0);
SendMessage(wnd,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
if (deflt) SetFocus(wnd);
return wnd;
}
static HWND AddGroup(const sChar *text,sInt x,sInt y, sInt w,sInt h)
{
sInt style=WS_VISIBLE|WS_CHILD|BS_GROUPBOX;
HWND wnd=CreateWindowEx(0,L"BUTTON",text,style,x,y,w,h,SelWin,0,0,0);
SendMessage(wnd,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
return wnd;
}
static Link& AddLink(const sChar *text,sInt x,sInt y, sInt w, sInt h)
{
if (!w) w=32;
if (!h) h=w;
sInt style=WS_VISIBLE|WS_CHILD|BS_OWNERDRAW;
HWND wnd=CreateWindowEx(0,L"bLink",text,style,x,y,w,h,SelWin,0,0,0);
Link l;
l.Wnd=wnd;
Links.AddTail(l);
return Links[Links.GetCount()-1];
}
static HWND AddCheck(const sChar *text,sInt x,sInt y, sInt w, sInt state)
{
sInt style=WS_VISIBLE|WS_CHILD|WS_TABSTOP;
style|=BS_AUTOCHECKBOX ;
HWND wnd=CreateWindowEx(0,L"BUTTON",text,style,x,y,w,22,SelWin,0,0,0);
SendMessage(wnd,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
SendMessage(wnd,BM_SETCHECK,state,0);
return wnd;
}
static HWND AddComboBox(const sChar *choices, sInt x, sInt y, sInt w, sInt sel)
{
sInt style=WS_VISIBLE|WS_CHILD|WS_TABSTOP|WS_VSCROLL;
style|=CBS_DROPDOWNLIST;
HWND wnd=CreateWindowEx(0,L"COMBOBOX",L"",style,x,y,w,125,SelWin,0,0,0);
SendMessage(wnd,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
while (choices && choices[0])
{
sString<64> opt;
sInt pipe=sFindFirstChar(choices,'|');
if (pipe>0)
{
sCopyString(opt,choices,pipe+1);
choices+=pipe+1;
}
else
{
sCopyString(opt,choices);
choices+=sGetStringLen(choices);
}
SendMessage(wnd,CB_ADDSTRING,0,(LPARAM)&opt[0]);
}
SendMessage(wnd,CB_SETCURSEL,sel,0);
return wnd;
}
static void OpenURL(HWND from)
{
sString<1024> url;
GetWindowText(from,url,1024);
ShellExecute(NULL,NULL,url,NULL,NULL,SW_SHOW);
}
static LRESULT CALLBACK SelWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_COMMAND:
{
HWND from=(HWND)lParam;
sInt code=wParam>>16;
if (from==Die && code==BN_CLICKED)
DestroyWindow(hwnd);
if (from==Demo && code==BN_CLICKED)
{
FillResults();
DestroyWindow(hwnd);
}
if ((Setup->DialogFlags & wDODF_Benchmark) && from==BenchmarkCheck && code==BN_CLICKED)
{
sBool bm=SendMessage(BenchmarkCheck,BM_GETCHECK,0,0)==BST_CHECKED;
EnableWindow(FSCheck,!bm);
EnableWindow(VSCheck,!bm);
if(LoopCheck)
EnableWindow(LoopCheck,!bm);
if(CoreCheck)
EnableWindow(CoreCheck,!bm);
if(LowQCheck)
EnableWindow(LowQCheck,!bm);
if (bm)
{
SendMessage(FSCheck,BM_SETCHECK,BST_CHECKED,0);
SendMessage(VSCheck,BM_SETCHECK,BST_UNCHECKED,0);
if(LoopCheck)
SendMessage(LoopCheck,BM_SETCHECK,BST_UNCHECKED,0);
if(CoreCheck)
SendMessage(CoreCheck,BM_SETCHECK,BST_UNCHECKED,0);
if(LowQCheck)
SendMessage(LowQCheck,BM_SETCHECK,BST_UNCHECKED,0);
}
}
Link *l;
sFORALL(Links, l)
if (from==l->Wnd && code==BN_CLICKED)
OpenURL(from);
}
break;
case WM_KEYDOWN:
{
switch (wParam)
{
case VK_TAB:
SetFocus(GetNextDlgTabItem(SelWin,GetFocus(),GetAsyncKeyState(VK_SHIFT)&0x8000));
break;
case VK_ESCAPE:
DestroyWindow(hwnd);
break;
case VK_RETURN:
FillResults();
DestroyWindow(hwnd);
break;
}
}
break;
case WM_DRAWITEM:
{
DRAWITEMSTRUCT *dis = (LPDRAWITEMSTRUCT)lParam;
RECT rect;
GetWindowRect(dis->hwndItem,&rect);
sInt w=rect.right-rect.left;
sInt h=rect.bottom-rect.top;
Link *l;
sFORALL(Links, l) if (dis->hwndItem==l->Wnd)
{
if (l->Icon)
DrawIconEx(dis->hDC,0,0,l->Icon,w,h,0,0,DI_NORMAL);
}
}
break;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
};
using namespace bob;
sBool bOpenSelector(const bSelectorSetup &setup,bSelectorResult &result)
{
// make choices
Done=sFALSE;
sClear(result);
Result=&result;
Setup=&setup;
sString<2048> resolutions;
sInt defres=0;
sString<1024> aspects;
sInt defasp=0;
sString<1024> fsaa;
sInt deffsaa=0;
SI = new sScreenInfo;
sGetScreenInfo(*SI,sSM_FULLSCREEN);
// resolutions...
for (sInt i=0; i<SI->Resolutions.GetCount(); i++)
{
const sScreenInfoXY &r=SI->Resolutions[i];
sString<64> str;
str.PrintF(L"%s%dx%d",i?L"|":L"",r.x,r.y);
sAppendString(resolutions,str);
if(sRELEASE && !sGetShellSwitch(L"w"))
{
if (r.x==SI->CurrentXSize && r.y==SI->CurrentYSize)
defres=i;
}
else
{
if (r.x==1280 && r.y==720) // optimal resolution for debugging - not to big and still quite big
defres=i;
}
}
if(setup.DialogFlags & wDODF_SetResolution)
{
sBool found=sFALSE;
for (sInt i=0; i<SI->Resolutions.GetCount(); i++)
{
const sScreenInfoXY &r=SI->Resolutions[i];
if(r.x==setup.DialogScreenX && r.y==setup.DialogScreenY)
{
defres=i;
found=sTRUE;
}
}
// if not found, try if there's a resolution with letterboxing that fits
if (!found) for (sInt i=0; i<SI->Resolutions.GetCount(); i++)
{
const sScreenInfoXY &r=SI->Resolutions[i];
if(r.x==setup.DialogScreenX && r.y>=setup.DialogScreenY && (defres<0 || r.y<SI->Resolutions[defres].y))
{
defres=i;
found=sTRUE;
}
}
// if not found, try if there's a resolution with pillarboxing that fits
if (!found) for (sInt i=0; i<SI->Resolutions.GetCount(); i++)
{
const sScreenInfoXY &r=SI->Resolutions[i];
if(r.x>=setup.DialogScreenX && r.y==setup.DialogScreenY && (defres<0 || r.x<SI->Resolutions[defres].x))
{
defres=i;
found=sTRUE;
}
}
}
// aspects...
Aspects.HintSize(32);
static const sScreenInfoXY defaultaspects[]={{4,3},{5,4},{16,10},{16,9}};
for (sInt i=0; i<sCOUNTOF(defaultaspects); i++)
Aspects.AddTail(defaultaspects[i]);
for (sInt i=0; i<SI->AspectRatios.GetCount(); i++)
{
sScreenInfoXY &r=SI->AspectRatios[i];
sInt found=0;
for (sInt j=0; j<Aspects.GetCount(); j++)
if (!sCmpMem(&r,&Aspects[j],sizeof(sScreenInfoXY)))
found=1;
if (!found)
Aspects.AddTail(r);
}
for (sInt i=0; i<Aspects.GetCount(); i++)
for (sInt j=i+1; j<Aspects.GetCount(); j++)
if ((sF32(Aspects[j].x)/sF32(Aspects[j].y))<(sF32(Aspects[i].x)/sF32(Aspects[i].y)))
sSwap(Aspects[i],Aspects[j]);
aspects.PrintF(L"Auto");
for (sInt i=0; i<Aspects.GetCount(); i++)
{
const sScreenInfoXY &r=Aspects[i];
sString<64> str;
str.PrintF(L"|%d:%d",r.x,r.y);
sAppendString(aspects,str);
}
// FSAA..
fsaa.PrintF(L"off");
for (sInt i=0; i<SI->MultisampleLevels; i++)
{
sString<64> str;
str.PrintF(L"|Level %d",i);
sAppendString(fsaa,str);
}
sBool full=sTRUE;
if(!sRELEASE || sGetShellSwitch(L"w"))
full = 0;
// create window class for links (like button, but: hand cursor)
LinkClass.cbSize=sizeof(LinkClass);
GetClassInfoEx(0,L"BUTTON",&LinkClass);
LinkClass.hCursor=LoadCursorW(0,IDC_HAND);
LinkClass.lpszClassName=L"bLink";
RegisterClassEx(&LinkClass);
// create window class and window
sClear(SelWinClass);
SelWinClass.cbSize=sizeof(SelWinClass);
SelWinClass.style=CS_DROPSHADOW;
SelWinClass.lpfnWndProc=SelWndProc;
SelWinClass.hInstance=GetModuleHandle(0);
SelWinClass.hIcon = LoadIcon(SelWinClass.hInstance,MAKEINTRESOURCE(100));
SelWinClass.hCursor=LoadCursorW(0,IDC_ARROW);
SelWinClass.hbrBackground=GetSysColorBrush(COLOR_BTNFACE);
SelWinClass.lpszClassName=L"bSelector";
RegisterClassEx(&SelWinClass);
static const sInt W=200;
CaptionFont=CreateFont(30,0,0,0,FW_BOLD,FALSE,FALSE,FALSE,DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,PROOF_QUALITY,DEFAULT_PITCH|FF_DONTCARE,L"Tahoma");
SelWin=CreateWindowEx(0,L"bSelector",setup.Title,WS_CAPTION,CW_USEDEFAULT,CW_USEDEFAULT,W,100,0,0,0,0);
Links.HintSize(32);
sInt y=0;
sInt leftx=5;
sInt leftx2=10;
sInt margin=5;
// add main link/icon if applicable
if (setup.IconInt)
{
y+=margin;
Link &l=AddLink(setup.IconURL,leftx,y,32,32);
l.Icon=LoadIcon(GetModuleHandle(0),MAKEINTRESOURCE(setup.IconInt));
AddStatic(setup.Caption,leftx+32+margin,y+2,200,sTRUE);
y+=32;
}
if (!setup.SubCaption.IsEmpty())
{
AddStatic(setup.SubCaption,leftx+32+margin,y,200,sFALSE,sTRUE);
y+=10;
}
y+=margin; sInt gy=y; y+=margin+15;
// add video options
sInt gw=90;
AddStatic(L"Resolution",leftx2,y,200);
ResBox=AddComboBox(resolutions,W-leftx2-gw,y-3,gw,defres);
y+=25;
AddStatic(L"Aspect Ratio",leftx2,y,200);
AspectBox=AddComboBox(aspects,W-leftx2-gw,y-3,gw,defasp);
y+=25;
if(MULTISAMPLING)
{
AddStatic(L"Multisampling",leftx2,y,200);
FSAABox=AddComboBox(fsaa,W-leftx2-gw,y-3,gw,deffsaa);
y+=25;
}
FSCheck=AddCheck(L"Fullscreen",leftx2,y,70,full);
VSCheck=AddCheck(L"Wait for VSync",W-leftx2-90,y,90,1);
y+=25;
AddGroup(L"Video",leftx,gy,W-2*leftx,y-gy);
y+=margin; gy=y; y+=margin+15;
//MBlurCheck=AddCheck(L"Motion Blur Effect",10,H-85,200,1);
LoopCheck = 0;
CoreCheck = 0;
LowQCheck = 0;
sBool advance = 0;
if(Setup->DialogFlags & wDODF_HiddenParts)
{
AddStatic(L"Hidden Parts",leftx2,y,200);
HiddenPartBox=AddComboBox(setup.HiddenPartChoices,W-leftx2-gw,y-3,gw,0);
y+=25;
}
if(!(Setup->DialogFlags & wDODF_NoLoop))
{
LoopCheck=AddCheck(L"Loop Demo",leftx2,y,100,0);
advance = 1;
}
if (Setup->DialogFlags & wDODF_Benchmark)
{
BenchmarkCheck=AddCheck(L"Benchmark",W-leftx2-72,y,72,0);
advance = 1;
}
if(advance)
y+=25;
if(Setup->DialogFlags & wDODF_Multithreading)
{
CoreCheck = AddCheck(L"Reserve one core for Windows",leftx2,y,200,0);
y+=25;
}
if(Setup->DialogFlags & wDODF_LowQuality)
{
LowQCheck = AddCheck(L"Low Quality Mode",leftx2,y,200,0);
y+=25;
}
AddGroup(L"Options",leftx,gy,W-2*leftx,y-gy);
y+=margin; gy=y; y+=15;
// sharing sites...
if (setup.Sites[0].IconInt)
{
sInt ssx=leftx2;
for (sInt i=0; i<sCOUNTOF(setup.Sites); i++)
{
const bSelectorSetup::ShareSite &site=setup.Sites[i];
if (!site.IconInt) break;
Link &l=AddLink(site.URL,ssx,y,16,16);
l.Icon=LoadIcon(GetModuleHandle(0),MAKEINTRESOURCE(site.IconInt));
ssx+=20;
}
y+=20;
AddGroup(L"Share!",leftx,gy,W-2*leftx,y-gy);
}
y+=2*margin;
Die=AddButton(L"Die",leftx,y,0,0);
Demo=AddButton(L"Demo",W-leftx-80,y,0,1);
AddStatic(L"||",leftx+92,y+6,15);
y+=25;
// size and position window
RECT crect, wrect;
sInt H=y+margin;
GetWindowRect(SelWin,&wrect);
GetClientRect(SelWin,&crect);
sInt ww=(wrect.right-wrect.left); ww+=W-(crect.right-crect.left);
sInt wh=(wrect.bottom-wrect.top); wh+=H-(crect.bottom-crect.top);
HWND dw=GetDesktopWindow();
GetWindowRect(dw,&wrect);
MoveWindow(SelWin,(wrect.right+wrect.left-ww)/2,(wrect.top+wrect.bottom-wh)/2,ww,wh,FALSE);
// ... and go!
UpdateWindow(SelWin);
ShowWindow(SelWin,SW_SHOW);
MSG msg;
GetMessage(&msg,0,0,0);
while(msg.message!=WM_QUIT)
{
TranslateMessage(&msg);
// message filter
if (msg.message==WM_KEYDOWN && (msg.wParam==VK_TAB || msg.wParam==VK_ESCAPE || msg.wParam==VK_RETURN))
msg.hwnd=SelWin;
DispatchMessage(&msg);
GetMessage(&msg,0,0,0);
}
DeleteObject(CaptionFont);
UnregisterClass(L"bSelector",0);
UnregisterClass(L"bLink",0);
sDelete(SI);
Aspects.Reset();
Links.Reset();
return Done;
}
/****************************************************************************/
#endif | [
"kb@kebby.org"
] | kb@kebby.org |
7792553a00967fb420b8c87e586c1ecb638ad899 | 2d361696ad060b82065ee116685aa4bb93d0b701 | /include/objtools/writers/gff_feature_record.hpp | ce41fe220b54765ff420874dcb7794b3b47f898d | [
"LicenseRef-scancode-public-domain"
] | permissive | AaronNGray/GenomeWorkbench | 5151714257ce73bdfb57aec47ea3c02f941602e0 | 7156b83ec589e0de8f7b0a85699d2a657f3e1c47 | refs/heads/master | 2022-11-16T12:45:40.377330 | 2020-07-10T00:54:19 | 2020-07-10T00:54:19 | 278,501,064 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,587 | hpp | /* $Id: gff_feature_record.hpp 564651 2018-05-31 16:44:56Z ludwigf $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Frank Ludwig
*
* File Description:
* GFF3 transient data structures
*
*/
#ifndef OBJTOOLS_WRITERS___GFF_FEATURE_RECORD__HPP
#define OBJTOOLS_WRITERS___GFF_FEATURE_RECORD__HPP
#include <objtools/writers/gff_base_record.hpp>
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// ============================================================================
class NCBI_XOBJWRITE_EXPORT CGffFeatureRecord
// ============================================================================
: public CGffBaseRecord
{
public:
CGffFeatureRecord(
const string& id="");
CGffFeatureRecord(
const CGffFeatureRecord& other);
virtual ~CGffFeatureRecord();
void InitLocation(
const CSeq_loc&);
void SetLocation(
const CSeq_interval&);
void SetEndpoints(
unsigned int start,
unsigned int stop,
ENa_strand strand);
const CSeq_loc& Location() const {
return *m_pLoc;
};
protected:
};
// ============================================================================
class NCBI_XOBJWRITE_EXPORT CGffSourceRecord
// ============================================================================
: public CGffBaseRecord
{
public:
CGffSourceRecord(
const string& id=""): CGffBaseRecord(id) {};
};
// ============================================================================
class NCBI_XOBJWRITE_EXPORT CGffAlignRecord
// ============================================================================
: public CGffBaseRecord
{
public:
CGffAlignRecord(
const string& id="");
void
AddInsertion(
unsigned int);
void
AddForwardShift(
unsigned int);
void
AddReverseShift(
unsigned int);
void
AddDeletion(
unsigned int);
void
AddMatch(
unsigned int);
void
FinalizeMatches();
string StrId() const { return mRecordId; };
string StrTarget() const;
string StrGap() const;
string StrAttributes() const;
protected:
string mRecordId;
string mAttrGap;
bool mGapIsTrivial;
unsigned int mAccumulatedMatches;
};
END_objects_SCOPE
END_NCBI_SCOPE
#endif // OBJTOOLS_WRITERS___GFF_FEATURE_RECORD__HPP
| [
"aaronngray@gmail.com"
] | aaronngray@gmail.com |
878970b64e0421bc9d3ec8f3e72e7e3139ea10f2 | f6439b5ed1614fd8db05fa963b47765eae225eb5 | /content/shell/renderer/test_runner/SpellCheckClient.cpp | e4c1e650179c3f874f7aebb8471e83e7a6741a63 | [
"BSD-3-Clause"
] | permissive | aranajhonny/chromium | b8a3c975211e1ea2f15b83647b4d8eb45252f1be | caf5bcb822f79b8997720e589334266551a50a13 | refs/heads/master | 2021-05-11T00:20:34.020261 | 2018-01-21T03:31:45 | 2018-01-21T03:31:45 | 118,301,142 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,226 | cpp | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/renderer/test_runner/SpellCheckClient.h"
#include "content/shell/renderer/test_runner/WebTestDelegate.h"
#include "content/shell/renderer/test_runner/mock_grammar_check.h"
#include "content/shell/renderer/test_runner/web_test_proxy.h"
#include "third_party/WebKit/public/web/WebTextCheckingCompletion.h"
#include "third_party/WebKit/public/web/WebTextCheckingResult.h"
using namespace blink;
namespace content {
namespace {
class HostMethodTask : public WebMethodTask<SpellCheckClient> {
public:
typedef void (SpellCheckClient::*CallbackMethodType)();
HostMethodTask(SpellCheckClient* object, CallbackMethodType callback)
: WebMethodTask<SpellCheckClient>(object)
, m_callback(callback)
{ }
virtual void runIfValid() OVERRIDE { (m_object->*m_callback)(); }
private:
CallbackMethodType m_callback;
};
} // namespace
SpellCheckClient::SpellCheckClient(WebTestProxyBase* webTestProxy)
: m_lastRequestedTextCheckingCompletion(0)
, m_webTestProxy(webTestProxy)
{
}
SpellCheckClient::~SpellCheckClient()
{
}
void SpellCheckClient::setDelegate(WebTestDelegate* delegate)
{
m_delegate = delegate;
}
// blink::WebSpellCheckClient
void SpellCheckClient::spellCheck(const WebString& text, int& misspelledOffset, int& misspelledLength, WebVector<WebString>* optionalSuggestions)
{
// Check the spelling of the given text.
m_spellcheck.spellCheckWord(text, &misspelledOffset, &misspelledLength);
}
void SpellCheckClient::checkTextOfParagraph(const WebString& text, WebTextCheckingTypeMask mask, WebVector<WebTextCheckingResult>* webResults)
{
std::vector<WebTextCheckingResult> results;
if (mask & WebTextCheckingTypeSpelling) {
size_t offset = 0;
base::string16 data = text;
while (offset < data.length()) {
int misspelledPosition = 0;
int misspelledLength = 0;
m_spellcheck.spellCheckWord(data.substr(offset), &misspelledPosition, &misspelledLength);
if (!misspelledLength)
break;
WebTextCheckingResult result;
result.decoration = WebTextDecorationTypeSpelling;
result.location = offset + misspelledPosition;
result.length = misspelledLength;
results.push_back(result);
offset += misspelledPosition + misspelledLength;
}
}
if (mask & WebTextCheckingTypeGrammar)
MockGrammarCheck::CheckGrammarOfString(text, &results);
webResults->assign(results);
}
void SpellCheckClient::requestCheckingOfText(
const WebString& text,
const WebVector<uint32_t>& markers,
const WebVector<unsigned>& markerOffsets,
WebTextCheckingCompletion* completion)
{
if (text.isEmpty()) {
if (completion)
completion->didCancelCheckingText();
return;
}
if (m_lastRequestedTextCheckingCompletion)
m_lastRequestedTextCheckingCompletion->didCancelCheckingText();
m_lastRequestedTextCheckingCompletion = completion;
m_lastRequestedTextCheckString = text;
if (m_spellcheck.hasInCache(text))
finishLastTextCheck();
else
m_delegate->postDelayedTask(new HostMethodTask(this, &SpellCheckClient::finishLastTextCheck), 0);
}
void SpellCheckClient::finishLastTextCheck()
{
if (!m_lastRequestedTextCheckingCompletion)
return;
std::vector<WebTextCheckingResult> results;
int offset = 0;
base::string16 text = m_lastRequestedTextCheckString;
if (!m_spellcheck.isMultiWordMisspelling(WebString(text), &results)) {
while (text.length()) {
int misspelledPosition = 0;
int misspelledLength = 0;
m_spellcheck.spellCheckWord(WebString(text), &misspelledPosition, &misspelledLength);
if (!misspelledLength)
break;
WebVector<WebString> suggestions;
m_spellcheck.fillSuggestionList(WebString(text.substr(misspelledPosition, misspelledLength)), &suggestions);
results.push_back(WebTextCheckingResult(WebTextDecorationTypeSpelling, offset + misspelledPosition, misspelledLength, suggestions.isEmpty() ? WebString() : suggestions[0]));
text = text.substr(misspelledPosition + misspelledLength);
offset += misspelledPosition + misspelledLength;
}
MockGrammarCheck::CheckGrammarOfString(m_lastRequestedTextCheckString, &results);
}
m_lastRequestedTextCheckingCompletion->didFinishCheckingText(results);
m_lastRequestedTextCheckingCompletion = 0;
m_webTestProxy->PostSpellCheckEvent(WebString("finishLastTextCheck"));
}
WebString SpellCheckClient::autoCorrectWord(const WebString&)
{
// Returns an empty string as Mac WebKit ('WebKitSupport/WebEditorClient.mm')
// does. (If this function returns a non-empty string, WebKit replaces the
// given misspelled string with the result one. This process executes some
// editor commands and causes layout-test failures.)
return WebString();
}
} // namespace content
| [
"jhonnyjosearana@gmail.com"
] | jhonnyjosearana@gmail.com |
dbfb32257daca6d16f806d60ea3a7ac1f1d2e325 | 9e71afd5bef444741bef62e5dc62245095c171c6 | /Sources/GameEngine/Renderers/GUI/Text/IGuiTextFactory.h | 32608e31d44d776ab3729f858033544a8c3a0e05 | [] | no_license | wbach/OpenGL_Engine | f243f5e5c854278660d077593f764f18bb7949c1 | b88cf1da8d57b4737544e6acdf4a5e1bfbbf4613 | refs/heads/master | 2023-02-23T08:40:26.120920 | 2023-02-18T16:48:24 | 2023-02-18T16:48:24 | 91,100,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | h | #pragma once
#include <Types.h>
#include <memory>
namespace GameEngine
{
class GuiTextElement;
class IGuiTextFactory
{
public:
virtual std::unique_ptr<GuiTextElement> Create(const std::string&, const std::string&, uint32, uint32) =0;
virtual ~IGuiTextFactory() = default;
};
} // namespace GameEngine
| [
"wojciech.bach@nokia.com"
] | wojciech.bach@nokia.com |
e6e3efdc277306ba86e5afd8c7a87d9dfa5cc0aa | a68c444d56d0bb6b5e0bb8ccbb76bfb081ba6b07 | /CowNetControllerV2/CowZoneHardware.cpp | ea077d75f22eee24740c29bb361aebe37a59a114 | [] | no_license | fitzpatricksrus/Pinduino | 03040b99bdc27daecf6743a63a1a9a5d6f1b0a51 | 45bfdd5ca34163dc44ceb91380d36a7307c4f2df | refs/heads/master | 2020-04-06T07:05:09.429566 | 2016-06-30T02:23:51 | 2016-06-30T02:23:51 | 24,709,921 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | /*
* CowZoneHardware.cpp
*
* Created on: Mar 18, 2015
* Author: Dad
*/
#include "CowZoneHardware.h"
CowZoneHardware::CowZoneHardware() {
}
CowZoneHardware::~CowZoneHardware() {
}
static CowZoneHardware instance;
CowZoneHardware& CowZoneHardware::INSTANCE = instance;
| [
"junk@fitzpatircksr.us"
] | junk@fitzpatircksr.us |
48db1f607eb126ebb9425bb8bf58b702f88ab777 | df93ce63155a5ddfd054f8daba9653d1ad00eb24 | /applications/test/dynamicCreateProcPatch/cavity/system/blockMeshDict | 2b5104c537d7c90cf64f5bb12a67ffe836f4d762 | [] | no_license | mattijsjanssens/mattijs-extensions | d4fb837e329b3372689481e9ebaac597272e0ab9 | 27b62bf191f1db59b045ce5c89c859a4737033e4 | refs/heads/master | 2023-07-19T20:57:04.034831 | 2023-07-16T20:35:12 | 2023-07-16T20:35:12 | 57,304,835 | 8 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: dev
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object blockMeshDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
convertToMeters 0.1;
vertices
(
(0 0 0)
(1 0 0)
(1 1 0)
(0 1 0)
(0 0 0.1)
(1 0 0.1)
(1 1 0.1)
(0 1 0.1)
(1 0 0)
(2 0 0)
(2 1 0)
(1 1 0)
(1 0 0.1)
(2 0 0.1)
(2 1 0.1)
(1 1 0.1)
);
blocks
(
hex (0 1 2 3 4 5 6 7) (2 2 1) simpleGrading (1 1 1)
hex (8 9 10 11 12 13 14 15) (2 2 1) simpleGrading (1 1 1)
);
edges
(
);
boundary
(
movingWall
{
type wall;
faces
(
(3 7 6 2)
(11 15 14 10)
);
}
fixedWalls
{
type wall;
faces
(
(0 4 7 3)
(1 5 4 0)
(10 14 13 9)
(9 13 12 8)
);
}
matchPatch
{
type wall;
faces
(
(2 6 5 1)
(8 12 15 11)
);
}
frontAndBack
{
type empty;
faces
(
(0 3 2 1)
(4 5 6 7)
(8 11 10 9)
(12 13 14 15)
);
}
);
// ************************************************************************* //
| [
"mattijs.janssens@gmail.com"
] | mattijs.janssens@gmail.com | |
561e54c1d445bc7701e2a15b0de7b299ee70621a | d051be42048074231b049809aa5d43516537aa90 | /src/Script_Engine.h | 33f3578ee4ad5776dace94357dd3d9740da18263 | [] | no_license | MaciekGraWCKII/0C | 961559272f52741de7901f29fb28ba96eea1a6ce | cf3e81a5f72651ddef34dc14c9c924f85ec45b12 | refs/heads/master | 2016-09-05T21:09:09.526203 | 2014-07-18T16:05:40 | 2014-07-18T16:05:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | h | #ifndef SCRIPT_ENGINE_H
#define SCRIPT_ENGINE_H
#include <string>
#include "Script_Environment.h"
#include "Communicator.h"
class Function;
class Script_Engine
{
public:
Script_Engine();
Script_Engine(Communicator* communicator);
void parse(std::string& line_of_code);
void parse_test_regex_with_expression(std::string& line_of_code);
void parse_test_regex(std::string& line_of_code);
void parse_preprocessed(std::string& line_of_code);
//assumes code is prepared for execution after one operation: split
//Data example: "int a = 5 * 8 ;"
//will be split into "int", "a", "=", "5", "*", "8", ";" and executed
bool add_function(const std::string& name, Function* fun);
~Script_Engine();
private:
class Default_Communicator : public Communicator
{
public:
void write(const std::string& line) const;
~Default_Communicator();
};
Script_Environment environment;
Communicator* comms;
};
#endif
| [
"nieokrzesana1wanna@gmail"
] | nieokrzesana1wanna@gmail |
633f2a9632c4f045b12da6af51832cfb66f60f4a | 0333e9616277bbf6bdc9eb036c92cb49809e066d | /code/ardrone_track/src/ardrone.cpp | c7ed06424891bf02dbe51b9ee1cc7b37b8e52375 | [] | no_license | mohbattharani/EKF-Pose-and-Trajectory-Estimation | 149b36b6dae55f91b3f109420d7d95ec44b99c0d | d032a1fb1c29cc14e2663752bcd0ad06ddd508de | refs/heads/master | 2020-05-02T19:38:14.503960 | 2019-03-29T04:42:06 | 2019-03-29T04:42:06 | 178,164,353 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,583 | cpp | /*
*
*
*/
#include "ardrone.h"
ardrone::ardrone (){
// =========== allocate memory ================
vKF.initKalmanFilter(18, 6, 1e-5, 1e-4);
O3 = Matrix (3,3).setZero();
I3 = Matrix (3,3).setIdentity();
omega = Matrix (4,4).setZero();
w = Matrix (3,1);
q = Matrix (4,1);
p = Matrix (3,1);
v = Matrix (3,1);
bg = Matrix (3,1).setRandom();
ba = Matrix (3,1).setRandom();
am = Matrix (3,1);
wm = Matrix (3,1);
wx = Matrix (3,3);
ax = Matrix (3,3);
n = Matrix (15,1);
q0 = Matrix (3,1);
q1 = Matrix (3,1);
M = Matrix (3,3);
M_a = Matrix (3,3);
gRi = Matrix(3,3).setIdentity(); //Rotation from IMU to global Frame
iRc = Matrix(3,3); //Rotation from camera to IMU Frame
Xerr = Matrix (totalStates,1);
Xest.p = Matrix (3,1).setZero ();
Xest.v = Matrix (3,1).setZero ();
Xest.bg = Matrix (3,1).setZero ();
Xest.ba = Matrix (3,1).setZero ();
Xest.g = Matrix (3,1).setZero ();
Xt.p = Matrix (3,1).setZero();
Vi = Matrix (3,3);
Ti = Matrix (3,3);
Ai = Matrix (3,3).setIdentity();
Gi = Matrix (3,3).setIdentity();
Hc = Matrix (2,3);
Ht = Matrix (3,3);
Hp = Matrix (3,3);
Hf = Matrix (3,3);
Fs = Matrix (15, 15);
Fx = Matrix (totalStates, totalStates).setZero();
Fi = Matrix (totalStates, 12).setZero ();
X = Matrix (totalStates, 1).setZero(); //State
Pimu = Matrix (totalStates, totalStates).setZero();
P = Matrix (totalStates, totalStates).setZero();
Q = Matrix (12, 12).setZero();
detector= new SiftFeatureDetector(
300, // nFeatures
4, // nOctaveLayers
0.1, // contrastThreshold
80, //edgeThreshold
0.5 //sigma
);
extractor = new SiftDescriptorExtractor();
opticalFlow = Mat::zeros(256, 256, CV_32F);
simulation = false;
cout<< "X:" << X <<endl;
cout<< "P:" << P <<endl;
cout<< "Q:" << Q <<endl;
}
// this destructor frees image viewing windows
ardrone::~ardrone()
{
cv::destroyWindow("view");
cv::destroyWindow("opticalFlow");
}
// =================== initialize ===========================
// all variables are initialized here
void ardrone::initialize()
{
previousTimeVis = Time::now().toSec(); //read time
previousTimeIMU = ros::Time::now().toSec();
iRc<< 0, -1, 0, 0, 0, -1, 1, 0, 1; //rotation camera to IMU
initReq = true;
Xest.g << 0, 0, -9.8; // gravity
Xest.q.w() = 1; //initialized quoternion
X(3,0) = 1; //
Fi << O3, O3, O3, O3,
I3, O3, O3, O3,
O3, I3, O3, O3,
O3, O3, I3, O3,
O3, O3, O3, I3,
O3, O3, O3, O3;
// Covariance
Vi << 0.0004, 0.0002, 0.0025,
0.0002, 0.0009, 0.0050,
0.0025, 0.0050, 0.0771;
Ti << 0.0679e-5, -0.0010e-5, 0.0014e-5,
-0.0010e-5, 0.0503e-5,-0.0015e-5,
0.0014e-5, -0.0015e-5, 0.1580e-5;
Q << Vi, O3, O3, O3,
O3, Ti, O3, O3,
O3, O3, Ai, O3,
O3, O3, O3, Gi;
if (simulation){ //V_REP simulation camera parameters
cam_matrix = (Mat_<double>(3, 3) <<
1, 0, 0,
0, 1, 0,
0, 0, 1);
dist_coeff = (Mat_<double>(1, 5) <<0, 0, 0, 0, 0);
}
else {
// ardrone_001 camera parameters
cam_matrix = (Mat_<double>(3, 3) <<
576.456375, 0, 335.080619,
0, 578.273149, 165.737041,
0, 0, 1);
dist_coeff = (Mat_<double>(1, 5) <<-0.554867, 0.356153, 0.000984, 0.003222, 0.000000);
}
initReq = false;
needtoinit = true;
ratio_ = 0.8;
N = 0;
cv::namedWindow("view");
cv::namedWindow("opticalFlow");
cv::startWindowThread();
}
// correction phase of Kalman filter
void ardrone::correction()
{
calResidual(); // Calculate residual
computeH(); // compute Jacobian
R = Matrix (H.rows(), H.rows()).setIdentity() *(1e-5);
cout<<"Size of R:"<<R.rows() <<" "<<R.cols()<<endl;
Si = H * P * H.transpose() + R;
cout <<"Gain:"<<Si.rows()<<" "<<Si.cols()<<endl;
Matrix K = P * H.transpose() * Si.inverse(); //Kalman Gain
cout <<"Kalman Gain:"<<K.rows()<<" "<<K.cols()<<endl;
X = X + K * r;
cout<<"State Vector:"<<X.rows()<<endl;
P = P - K * Si *K.transpose();
}
// prediction
void ardrone::prediction()
{
cout <<"prediction start... "<<endl;
// Update states in actual state vector
Matrix Pt(3,1);
Pt = Xest.q.vec();
X(0,0) = Pt(0,0);
X(1,0) = Pt(1,0);
X(2,0) = Pt(2,0);
Pt = Xest.v;
X(6,0) = Pt(0,0);
X(7,0) = Pt(1,0);
X(8,0) = Pt(2,0);
Pt = Xest.p;
X(12,0) = Pt(0,0);
X(13,0) = Pt(1,0);
X(14,0) = Pt(2,0);
//Calculate wx and ax - the sckew symmetric matrix
wx << 0, -(wm(2,0)-Xest.bg(2,0)), wm(1,0)-Xest.bg(1,0),
wm(2,0)-Xest.bg(2,0), 0, -(wm(0,0)-Xest.bg(0,0)),
-(wm(1,0)-Xest.bg(1,0)), wm(0,0)-Xest.bg(0,0), 0;
ax << 0, -(am(2,0)-Xest.ba(2,0)), am(1,0)-Xest.ba(1,0),
am(2,0)-Xest.ba(2,0), 0, -(am(0,0)-Xest.ba(0,0)),
-(am(1,0)-Xest.ba(1,0)), am(0,0)-Xest.ba(0,0), 0;
// Fx rerranged according to states
Fx << gRi.transpose()*(wx)*dT, -I3*dT, O3, O3, O3, O3,
O3, I3, O3, O3, O3, O3,
-gRi*(ax)*dT, O3, I3, -gRi*dT, O3, I3*dT,
O3, O3, O3, I3, O3, O3,
O3, O3, I3*dT, O3, I3, O3,
O3, O3, O3, O3, O3, I3;
/* I3, I3*dT, O3, O3, O3, O3,
* O3, I3, -gRi*(ax)*dT, -gRi*dT, O3, I3*dT,
* O3, O3, gRi.transpose()*(wx)*dT, O3, -I3*dT, O3,
* O3, O3, O3, I3, O3, O3,
* O3, O3, O3, O3, I3, O3,
* O3, O3, O3, O3, O3, I3;*/
Fi << O3, O3, O3, O3,
I3, O3, O3, O3,
O3, I3, O3, O3,
O3, O3, I3, O3,
O3, O3, O3, I3,
O3, O3, O3, O3;
// ntegrating the covariances of an, wn, aw and ww -> eq(246-248)
// rearranged as wn, ww, an, aw
Q << Ti*dT*dT, O3, O3, O3,
O3, Gi*dT, O3, O3,
O3, O3, Vi*dT*dT, O3,
O3, O3, O3, Ai*dT;
Pimu = Fx * Pimu * Fx.transpose() + Fi* Q * Fi.transpose(); //432
P.block (0,0,14,14) = Pimu.block(0,0,14,14); //Move imu Covariance into actual Covariance Matrix
}
// Intergrate IMU values to predict new state
void ardrone::callbackIMU(const sensor_msgs::ImuConstPtr imuData)
{
cout <<"State estimation running ..."<<endl;
double newTime = ros::Time::now().toSec();
dT = newTime - previousTimeIMU;
//tf::Quaternion q2;
if (initReq){
Xest.q.x() = imuData.get()->orientation.x;
Xest.q.y() = imuData.get()->orientation.y;
Xest.q.z() = imuData.get()->orientation.z;
Xest.q.w() = imuData.get()->orientation.w;
initReq = false;
previousTimeIMU = newTime;
return;
}
tf::Quaternion q2 = tf::createQuaternionFromRPY(X(0,0),X(1,0), X(2,0));
if (abs (X(0,0))<1e5 and abs(X(1,0)) < 1e5){ //
Xest.q.x() = q2.x();
Xest.q.y() = q2.y();
Xest.q.z() = q2.z();
Xest.q.w() = q2.w();
Xest.v(0,0) = X(6,0);
Xest.v(1,0) = X(7,0);
Xest.v(2,0) = X(8,0);
Xest.p(0,0) = X(12,0);
Xest.p(1,0) = X(13,0);
Xest.p(2,0) = X(14,0);
}
gRi = (Xest.q.toRotationMatrix()).transpose();
// cout <<"read meansurement"<<endl;
// read meansurement
am<< imuData.get()->linear_acceleration.x,imuData.get()->linear_acceleration.y,imuData.get()->linear_acceleration.z;
wm<< imuData.get()->angular_velocity.x, imuData.get()->angular_velocity.y, imuData.get()->angular_velocity.z;
// estimate noise
Xest.p += Xest.v * dT/100; //+ 0.5 *(gRi *am + Xest.g)*dT*dT; // update position
Xest.v += (gRi * am + Xest.g) * dT; // convert acceleration to intertial frame and integrate to compute velocity
// estimate states (Nominal states)
// ==== Add ab and wb in the equations**.
//q0 << Xest.q.vec();
double roll = q0(0,0), pitch = q0(1,0), yaw = q0(2,0);
omega <<0, wm(2,0), -wm(1,0), wm(0,0),
-wm(2,0), 0, wm(0,0), wm(1,0),
wm(1,0), -wm(0,0), 0, wm(2,0),
-wm(0,0), -wm(1,0), -wm(2,0), 0;
// Intergrate gyroscope;
M << 1, sin(roll)*tan(pitch), cos(roll)*tan(roll),
0, cos(roll) , -sin(roll),
0, sin(roll)/cos(pitch), cos(roll)/cos(pitch);
q1 = Xest.q.vec() + gRi.transpose()*(wm)*dT;
// body frame to intertial frame transformation Matrix
M_a << cos(yaw)*cos(pitch), cos(yaw)*sin(pitch)*sin(roll)-cos(roll)*sin(yaw), sin(roll)*sin(yaw)+cos(roll)*cos(yaw)*sin(pitch),
cos(pitch)*sin(yaw), cos(roll)*cos(yaw)+sin(roll)*sin(yaw)*sin(pitch), cos(roll)*sin(yaw)*sin(pitch)-cos(yaw)*cos(roll),
-sin(pitch), cos(pitch)*sin(roll), cos(roll)*cos(pitch);
q2 = tf::createQuaternionFromRPY(q1(0,0),q1(1,0), q1(2,0));
Xest.q.x() = alpha * imuData.get()->orientation.x + (1-alpha)* q2.x();
Xest.q.y() = alpha * imuData.get()->orientation.y + (1-alpha)* q2.y();
Xest.q.z() = alpha * imuData.get()->orientation.z + (1-alpha)* q2.z();
Xest.q.w() = alpha * imuData.get()->orientation.w + (1-alpha)* q2.w();
gRi = (Xest.q.toRotationMatrix()).transpose();
prediction();
previousTimeIMU = newTime;
}
// ***************************** VISION *********************************************
void ardrone::SfMKLT(const sensor_msgs::ImageConstPtr& msg)
{
TermCriteria termcrit (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03);
Size subPixWinSize (10,10), winSize(15,15);
int i, k;
double newTime = ros::Time::now().toSec();
dT = newTime - previousTimeVis;
vKF.prediction(); // predict camera orientation using linear Kalman Filter
cv_bridge::CvImagePtr cv_ptr;
// Bridge ros_image to opencv image
try
{
cv_ptr = cv_bridge::toCvCopy(msg, "bgr8" );
rgbFrame = cv_ptr->image;
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
// convert from brg to grayscale
cv::cvtColor(rgbFrame,grayFrameNew,CV_BGR2GRAY);
// image processing task
if (needtoinit){ // need to init by calculating features
detector->detect ( grayFrameNew, keypointsNew); //detect SIFT Features
for (int j =0; j<keypointsNew.size();j++){ // Convert features to points
pointsNew.push_back(keypointsNew[j].pt);
}
needInit_P = true;
cout<<"initialization completed... "<<endl;
needtoinit = false;
}
else {
calcOpticalFlowPyrLK(grayFrameOld, grayFrameNew, pointsOld ,pointsNew, status,err, winSize, 3, termcrit,0,0.001 );
cout <<"status: ";
if (plotPoints()<20) // If there is no motion then skip following steps
goto swaping;
removeOutliers(); // remove unmatched features and also update P and X sizes
if (needInit_P){ //P is initialized when we actually initialize features matrix
N = pointsNew.size();
P = Matrix (3*N+15, 3*N+15).setIdentity();
X.conservativeResize(3*N+15, 1); //resize state vector
needInit_P = false;
cout <<"P initialization ... "<<endl;
}
if (resized){
cout<<"After removing outliers RANSAC:"<<pointsNew.size()<<" "<<pointsOld.size()<<endl;
cout<<"After removing outliers P size:"<<P.rows()<<","<<P.cols()<<endl;
}
cout <<"After erasing outliers: "<<pointsNew.size()<<endl;
if (pointsNew.size() <10 or pointsNew.size()>500){
needtoinit =true;
}
else if(pointsOld.size()>3 and pointsNew.size()>3) { //If matched features more than 3 then recover camera pose
recoverCamPose();
vKF.correction(Rc_rec, Tc_rec, dT); // Correct camera pose predicted earlier using Linear KF
updateStateVision(); //
correction(); // correction phase of EKF
}
}
swaping:
swap(pointsOld, pointsNew);
swap(keypointsOld, keypointsNew);
grayFrameNew.copyTo(grayFrameOld);
//cout <<"State Estimated KF:" << vKF.X <<endl;
cout<<"Points after swaping: "<<pointsNew.size()<<" "<<pointsOld.size()<<endl;
cout<<"sawping completed.."<<endl;
previousTimeVis = newTime;
// visualize
try
{
imshow("view", rgbFrame);
imshow("opticalFlow", opticalFlow);
// cout<<points1<<endl;
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("Could not convert from '%s'.", e.what());
return;
}
}
void ardrone::recoverCamPose()
{
// **** recover 3D Points *****
Mat fundamental = findFundamentalMat( pointsOld, pointsNew, CV_FM_RANSAC, 1.0, 0.99 );
Mat essential = cam_matrix.t() * fundamental * cam_matrix;
/* Find the projection matrix between those two images */
SVD svd( essential );
static const Mat W = (Mat_<double>(3, 3) <<
0, -1, 0,
1, 0, 0,
0, 0, 1);
static const Mat W_inv = W.inv();
Mat_<double> R1 = svd.u * W * svd.vt;
Mat_<double> T1 = svd.u.col( 2 );
Mat_<double> R2 = svd.u * W_inv * svd.vt;
Mat_<double> T2 = -svd.u.col( 2 );
static const Mat P1 = Mat::eye(3, 4, CV_64FC1 );
Mat P2 =( Mat_<double>(3, 4) <<
R1(0, 0), R1(0, 1), R1(0, 2), T1(0),
R1(1, 0), R1(1, 1), R1(1, 2), T1(1),
R1(2, 0), R1(2, 1), R1(2, 2), T1(2));
/* Triangulate the points to find the 3D homogenous points in the world space
* Note that each column of the 'out' matrix corresponds to the 3d homogenous point
*/
gP3.empty();
triangulatePoints( P1, P2, pointsOld, pointsNew, gP3 );
/* Since it's homogenous (x, y, z, w) coord, divide by w to get (x, y, z, 1) */
vector<Mat> splitted;
splitted.push_back(gP3.row(0) / gP3.row(3));
splitted.push_back(gP3.row(1) / gP3.row(3));
splitted.push_back(gP3.row(2) / gP3.row(3));
gP3.empty();
merge( splitted, gP3 );
// estimate camera motion
// Mat rvec, tvec;
solvePnP(gP3, pointsNew, cam_matrix, dist_coeff, Rc_rec, Tc_rec);
cout<<"Rrec:" << Rc_rec<<endl;
cout<<"Trec: "<<Tc_rec<<endl;
//cout <<"3D points: "<< gP3.size() <<endl<<endl;
//cout <<"point 3D:" << gP3.col(0);
}
void ardrone::calResidual()
{
vector<cv::Point2f> pointsProj, pointsTrue;
pointsTrue = pointsNew;
int i, k;
Matrix pointTemp(3,1), point0;
cout<<"Errors: ";
projectPoints(gP3, Rc_rec, Tc_rec, cam_matrix, dist_coeff, pointsProj);
cout<< "size of 3D points: "<<gP3.size() <<endl;
cout <<"size of recovered:"<<pointsProj.size()<<endl;
r = Matrix (2*pointsTrue.size(), 1); //resize 'r' matrix double to total number of features.
k=0;
for (i=0; i<pointsProj.size(); i++){
r(k,0) = (pointsTrue[i].x - pointsProj[i].x); // Calculate residual and update in "r" matrix
r(k+1,0) = (pointsTrue[i].y - pointsProj[i].y);
k++;
}
cout <<endl;
}
// compute Camera meansurement Jacobian
void ardrone::computeH()
{
N = pointsNew.size();
H = Matrix(2*N, 3*N+15);
Matrix H1 (3,3*N+15);
double px, py, pz; //location of feature 'f' in IMU frame;
int i =0;
for (i=0; i<N; i++){
px = gP3.col(i).at<double>(0);
py = gP3.col(i).at<double>(1);
pz = gP3.col(i).at<double>(2);
Hc << 1/pz, 0 , -px/py, 0, 1/pz, -py/pz;
Ht << 0, -pz, py, p(2,0), 0, -pz, -py, px, 0;
Hp << -gRi.transpose();
Hf << gRi.transpose();
H1.block(0,0, 3, 3) = Ht;
H1.block(0,11, 3, 3) = -gRi.transpose();
H1.block(0,16+i, 3, 3) = gRi.transpose();
H.block(i, 0, 2, 3*N+15) = Hc * H1;
}
cout <<" Size of H:" <<H.rows()<<","<<H.cols();
cout <<" Size of P:" <<P.rows()<<","<<P.cols()<<endl;
}
// visualize features and motion on windows
double ardrone::plotPoints()
{
int i, k;
double dist =0;
cout<<"Start ploting ";
for (i=k=0; i<pointsOld.size(); i++){
//cout<<"Starting drawing arrow..."<<endl;
// cout<<points2<<endl;
if (pointsNew[i].x - pointsOld[i].y > 0){
line(rgbFrame,pointsNew[i], pointsOld[i], Scalar(0,0,255),1, 1, 0);
circle(rgbFrame,pointsNew[i], 2, Scalar(255,0,0),1, 1, 0);
line(opticalFlow,pointsNew[i], pointsOld[i], Scalar(0,0,255),1, 1, 0);
circle(opticalFlow,pointsNew[i], 1, Scalar(255,0,0),1, 1, 0);
}
else {
line(rgbFrame,pointsNew[i], pointsOld[i], Scalar(0,0,255),1, 1, 0);
circle(rgbFrame,pointsNew[i], 2, Scalar(255,0,0),1, 1, 0);
line(opticalFlow,pointsNew[i], pointsOld[i], Scalar(0,0,255),1, 1, 0);
circle(opticalFlow,pointsNew[i], 1, Scalar(255,0,0),1, 1, 0);
}
dist += distance(pointsNew[i].x, pointsOld[i].y, pointsOld[i].x, pointsOld[i].y);
}
cout <<"Total distance covered by features: "<<dist <<endl;
cout <<" done"<<endl;
return dist;
}
// remove unmatched and out of window features and update P & X
void ardrone::removeOutliers(){
float reprojectionThreshold =500;
Mat homography;
int indexCorrection = 0;
vector<cv::Point2f> srcPoints;
vector<cv::Point2f> dstPoints;
// Find homography matrix and get inliers mask
vector<unsigned char> inliersMask(keypointsNew.size());
homography = cv::findHomography(pointsNew, pointsOld,CV_FM_RANSAC, reprojectionThreshold, inliersMask);
cout<<"Before removing outliers RANSAC:"<<pointsNew.size()<<" "<<pointsOld.size()<<endl;
cout<<"Before removing outliers P size:"<<P.rows()<<","<<P.cols()<<endl;
resized = false;
for(int i=0; i<status.size(); i++){
Point2f pt = pointsOld.at(i- indexCorrection);
if ((status.at(i) == 0)||(pt.x<0)||(pt.y<0) or inliersMask[i]==0) {
if((pt.x<0)||(pt.y<0)) {
status.at(i) = 0;
}
resized = true;
pointsNew.erase (pointsNew.begin() + (i - indexCorrection));
pointsOld.erase (pointsOld.begin() + (i - indexCorrection));
// cout<<" "<<P.rows()<<endl;
if (!needInit_P){
resizeP (P, i-indexCorrection);
}
indexCorrection++;
}
}
}
// Pose estimated using Linear KF from recovered camera pose - NOT USED ANY WHERE
void ardrone::updateStateVision()
{
tf::Quaternion q2 = tf::createQuaternionFromRPY(vKF.X(0,0),vKF.X(1,0), vKF.X(2,0));
Xt.p(0,0) = vKF.X(0,0);
Xt.p(1,0) = vKF.X(1,0);
Xt.p(2,0) = vKF.X(2,0);
Xt.q.x() = q2.x();
Xt.q.y() = q2.y();
Xt.q.z() = q2.z();
Xt.q.w() = q2.w();
}
// resize Covariance "P" and state "X"
void ardrone::resizeP(Matrix& matrix, unsigned int idx)
{
unsigned int numRows = matrix.rows();
unsigned int numCols = matrix.cols();
unsigned int idxStart = idx*3;
unsigned int idxes = numRows-idxStart-3;
if (idxes <numRows and idxes <numCols){
matrix.block (idxStart,0, idxes,numCols) = matrix.block(idxStart+3, 0, idxes, numCols); //remove 3 rows
matrix.block (0, idxStart, numRows,idxes) = matrix.block(0, idxStart+3, numRows, idxes); //romove 3 colums
X.block (idxStart,0, idxes,0) = X.block (idxStart+3,0,idxes,0);
}
matrix.conservativeResize(numRows-3,numCols-3);
X.conservativeResize(numRows-3, 1);
}
void ardrone::removeRow(Matrix& matrix, unsigned int rowToRemove)
{
unsigned int numRows = matrix.rows()-1;
unsigned int numCols = matrix.cols();
// cout <<" "<<rowToRemove<<" "<< matrix.rows();
if( rowToRemove < numRows )
matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols);
matrix.conservativeResize(numRows,numCols);
// cout <<" "<<matrix.rows();
}
void ardrone::removeColumn(Matrix& matrix, unsigned int colToRemove)
{
unsigned int numRows = matrix.rows();
unsigned int numCols = matrix.cols()-1;
if( colToRemove < numCols )
matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove);
matrix.conservativeResize(numRows,numCols);
}
// Calculate Gaussian Probablity
float ardrone::gaussian(float mu, float sigma, float x)
{
float pi = 3.14;
float val = exp((-pow((x-mu),2))/(2*pow(sigma,2))) /sqrt(2*pi* pow (sigma,2)) ;
//std::cout<<val << " "<<mu<<" "<<sigma <<" " <<x << endl;
return val;
}
double ardrone::distance(double x1, double y1, double x2, double y2)
{
return sqrt(pow (x2-x1,2) + pow (y2-y1,2) );
}
| [
"mohbattharani1@gmail.com"
] | mohbattharani1@gmail.com |
987d44d0b6cf60b91e01632576e94d53ff1bb186 | 9bfe7d43598238b4a6712f334a4006c8e6f8f234 | /preparation_1/boolean_matrix.cpp | d56471b14de2d8273da739a8a4d4b684bda73a69 | [] | no_license | divyamdr/CPP_CODE_S | 9a244f401f3578ee8d3f49083d71199708266cc4 | 33258e898c80d6ddefc6608ece9ad2ddc4ff409d | refs/heads/master | 2022-11-14T21:10:22.486933 | 2020-07-10T05:34:28 | 2020-07-10T05:34:28 | 266,546,298 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 823 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int rows,cols;
cin>>rows>>cols;
int matrix[rows][cols];
int row[rows]={0},col[cols]={0};
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
int data;
cin>>data;
if(row[i]==1||col[j]==1||data==1)
matrix[i][j]=1;
else
{
matrix[i][j]=0;
}
if(data==1)
{
row[i]=1;
col[j]=1;
}
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(row[i]==1||col[j]==1)
cout<<'1'<<' ';
else
{
cout<<'0'<<' ';
}
}
cout<<endl;
}
} | [
"divyareddymdr753@gmail.com"
] | divyareddymdr753@gmail.com |
6406ee88c5485662e110b37ba1655a825cac8324 | d226f156129471f10c58bec90027aba6687ee1c3 | /lonely_integer/lonely_integer.cpp | bfc24df5d876464b6f942c5bef524210024267d5 | [] | no_license | frbaroni/hackerhank | b13f7fc9bede04dd239566bc452a6aea888d5ea3 | e242f65089bd415e29de901eaf09f400612e776c | refs/heads/master | 2021-01-20T08:30:02.583799 | 2017-08-08T04:09:22 | 2017-08-08T04:09:22 | 90,155,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | #include <iostream>
using namespace std;
int main() {
int a[100]{0};
int n, v;
cin >> n;
while(n-- > 0) {
cin >> v;
a[v]++;
}
for(int i = 0; i < 100; i++) {
if(a[i] == 1) {
cout << i << endl;
break;
}
}
return 0;
}
| [
"fernando@baroni.tech"
] | fernando@baroni.tech |
ad1b53f21f6a6a4f08390731d3e11d2bf798c46f | 5a60d60fca2c2b8b44d602aca7016afb625bc628 | /aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/CreateIntentResult.h | bb7658d123a54494b577c7d5e92eb46a51378beb | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | yuatpocketgems/aws-sdk-cpp | afaa0bb91b75082b63236cfc0126225c12771ed0 | a0dcbc69c6000577ff0e8171de998ccdc2159c88 | refs/heads/master | 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null | UTF-8 | C++ | false | false | 23,036 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/lexv2-models/LexModelsV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/lexv2-models/model/DialogCodeHookSettings.h>
#include <aws/lexv2-models/model/FulfillmentCodeHookSettings.h>
#include <aws/lexv2-models/model/IntentConfirmationSetting.h>
#include <aws/lexv2-models/model/IntentClosingSetting.h>
#include <aws/lexv2-models/model/KendraConfiguration.h>
#include <aws/core/utils/DateTime.h>
#include <aws/lexv2-models/model/InitialResponseSetting.h>
#include <aws/lexv2-models/model/SampleUtterance.h>
#include <aws/lexv2-models/model/InputContext.h>
#include <aws/lexv2-models/model/OutputContext.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace LexModelsV2
{
namespace Model
{
class CreateIntentResult
{
public:
AWS_LEXMODELSV2_API CreateIntentResult();
AWS_LEXMODELSV2_API CreateIntentResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AWS_LEXMODELSV2_API CreateIntentResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>A unique identifier for the intent.</p>
*/
inline const Aws::String& GetIntentId() const{ return m_intentId; }
/**
* <p>A unique identifier for the intent.</p>
*/
inline void SetIntentId(const Aws::String& value) { m_intentId = value; }
/**
* <p>A unique identifier for the intent.</p>
*/
inline void SetIntentId(Aws::String&& value) { m_intentId = std::move(value); }
/**
* <p>A unique identifier for the intent.</p>
*/
inline void SetIntentId(const char* value) { m_intentId.assign(value); }
/**
* <p>A unique identifier for the intent.</p>
*/
inline CreateIntentResult& WithIntentId(const Aws::String& value) { SetIntentId(value); return *this;}
/**
* <p>A unique identifier for the intent.</p>
*/
inline CreateIntentResult& WithIntentId(Aws::String&& value) { SetIntentId(std::move(value)); return *this;}
/**
* <p>A unique identifier for the intent.</p>
*/
inline CreateIntentResult& WithIntentId(const char* value) { SetIntentId(value); return *this;}
/**
* <p>The name specified for the intent.</p>
*/
inline const Aws::String& GetIntentName() const{ return m_intentName; }
/**
* <p>The name specified for the intent.</p>
*/
inline void SetIntentName(const Aws::String& value) { m_intentName = value; }
/**
* <p>The name specified for the intent.</p>
*/
inline void SetIntentName(Aws::String&& value) { m_intentName = std::move(value); }
/**
* <p>The name specified for the intent.</p>
*/
inline void SetIntentName(const char* value) { m_intentName.assign(value); }
/**
* <p>The name specified for the intent.</p>
*/
inline CreateIntentResult& WithIntentName(const Aws::String& value) { SetIntentName(value); return *this;}
/**
* <p>The name specified for the intent.</p>
*/
inline CreateIntentResult& WithIntentName(Aws::String&& value) { SetIntentName(std::move(value)); return *this;}
/**
* <p>The name specified for the intent.</p>
*/
inline CreateIntentResult& WithIntentName(const char* value) { SetIntentName(value); return *this;}
/**
* <p>The description specified for the intent.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>The description specified for the intent.</p>
*/
inline void SetDescription(const Aws::String& value) { m_description = value; }
/**
* <p>The description specified for the intent.</p>
*/
inline void SetDescription(Aws::String&& value) { m_description = std::move(value); }
/**
* <p>The description specified for the intent.</p>
*/
inline void SetDescription(const char* value) { m_description.assign(value); }
/**
* <p>The description specified for the intent.</p>
*/
inline CreateIntentResult& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>The description specified for the intent.</p>
*/
inline CreateIntentResult& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>The description specified for the intent.</p>
*/
inline CreateIntentResult& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>The signature of the parent intent specified for the intent.</p>
*/
inline const Aws::String& GetParentIntentSignature() const{ return m_parentIntentSignature; }
/**
* <p>The signature of the parent intent specified for the intent.</p>
*/
inline void SetParentIntentSignature(const Aws::String& value) { m_parentIntentSignature = value; }
/**
* <p>The signature of the parent intent specified for the intent.</p>
*/
inline void SetParentIntentSignature(Aws::String&& value) { m_parentIntentSignature = std::move(value); }
/**
* <p>The signature of the parent intent specified for the intent.</p>
*/
inline void SetParentIntentSignature(const char* value) { m_parentIntentSignature.assign(value); }
/**
* <p>The signature of the parent intent specified for the intent.</p>
*/
inline CreateIntentResult& WithParentIntentSignature(const Aws::String& value) { SetParentIntentSignature(value); return *this;}
/**
* <p>The signature of the parent intent specified for the intent.</p>
*/
inline CreateIntentResult& WithParentIntentSignature(Aws::String&& value) { SetParentIntentSignature(std::move(value)); return *this;}
/**
* <p>The signature of the parent intent specified for the intent.</p>
*/
inline CreateIntentResult& WithParentIntentSignature(const char* value) { SetParentIntentSignature(value); return *this;}
/**
* <p>The sample utterances specified for the intent.</p>
*/
inline const Aws::Vector<SampleUtterance>& GetSampleUtterances() const{ return m_sampleUtterances; }
/**
* <p>The sample utterances specified for the intent.</p>
*/
inline void SetSampleUtterances(const Aws::Vector<SampleUtterance>& value) { m_sampleUtterances = value; }
/**
* <p>The sample utterances specified for the intent.</p>
*/
inline void SetSampleUtterances(Aws::Vector<SampleUtterance>&& value) { m_sampleUtterances = std::move(value); }
/**
* <p>The sample utterances specified for the intent.</p>
*/
inline CreateIntentResult& WithSampleUtterances(const Aws::Vector<SampleUtterance>& value) { SetSampleUtterances(value); return *this;}
/**
* <p>The sample utterances specified for the intent.</p>
*/
inline CreateIntentResult& WithSampleUtterances(Aws::Vector<SampleUtterance>&& value) { SetSampleUtterances(std::move(value)); return *this;}
/**
* <p>The sample utterances specified for the intent.</p>
*/
inline CreateIntentResult& AddSampleUtterances(const SampleUtterance& value) { m_sampleUtterances.push_back(value); return *this; }
/**
* <p>The sample utterances specified for the intent.</p>
*/
inline CreateIntentResult& AddSampleUtterances(SampleUtterance&& value) { m_sampleUtterances.push_back(std::move(value)); return *this; }
/**
* <p>The dialog Lambda function specified for the intent.</p>
*/
inline const DialogCodeHookSettings& GetDialogCodeHook() const{ return m_dialogCodeHook; }
/**
* <p>The dialog Lambda function specified for the intent.</p>
*/
inline void SetDialogCodeHook(const DialogCodeHookSettings& value) { m_dialogCodeHook = value; }
/**
* <p>The dialog Lambda function specified for the intent.</p>
*/
inline void SetDialogCodeHook(DialogCodeHookSettings&& value) { m_dialogCodeHook = std::move(value); }
/**
* <p>The dialog Lambda function specified for the intent.</p>
*/
inline CreateIntentResult& WithDialogCodeHook(const DialogCodeHookSettings& value) { SetDialogCodeHook(value); return *this;}
/**
* <p>The dialog Lambda function specified for the intent.</p>
*/
inline CreateIntentResult& WithDialogCodeHook(DialogCodeHookSettings&& value) { SetDialogCodeHook(std::move(value)); return *this;}
/**
* <p>The fulfillment Lambda function specified for the intent.</p>
*/
inline const FulfillmentCodeHookSettings& GetFulfillmentCodeHook() const{ return m_fulfillmentCodeHook; }
/**
* <p>The fulfillment Lambda function specified for the intent.</p>
*/
inline void SetFulfillmentCodeHook(const FulfillmentCodeHookSettings& value) { m_fulfillmentCodeHook = value; }
/**
* <p>The fulfillment Lambda function specified for the intent.</p>
*/
inline void SetFulfillmentCodeHook(FulfillmentCodeHookSettings&& value) { m_fulfillmentCodeHook = std::move(value); }
/**
* <p>The fulfillment Lambda function specified for the intent.</p>
*/
inline CreateIntentResult& WithFulfillmentCodeHook(const FulfillmentCodeHookSettings& value) { SetFulfillmentCodeHook(value); return *this;}
/**
* <p>The fulfillment Lambda function specified for the intent.</p>
*/
inline CreateIntentResult& WithFulfillmentCodeHook(FulfillmentCodeHookSettings&& value) { SetFulfillmentCodeHook(std::move(value)); return *this;}
/**
* <p>The confirmation setting specified for the intent.</p>
*/
inline const IntentConfirmationSetting& GetIntentConfirmationSetting() const{ return m_intentConfirmationSetting; }
/**
* <p>The confirmation setting specified for the intent.</p>
*/
inline void SetIntentConfirmationSetting(const IntentConfirmationSetting& value) { m_intentConfirmationSetting = value; }
/**
* <p>The confirmation setting specified for the intent.</p>
*/
inline void SetIntentConfirmationSetting(IntentConfirmationSetting&& value) { m_intentConfirmationSetting = std::move(value); }
/**
* <p>The confirmation setting specified for the intent.</p>
*/
inline CreateIntentResult& WithIntentConfirmationSetting(const IntentConfirmationSetting& value) { SetIntentConfirmationSetting(value); return *this;}
/**
* <p>The confirmation setting specified for the intent.</p>
*/
inline CreateIntentResult& WithIntentConfirmationSetting(IntentConfirmationSetting&& value) { SetIntentConfirmationSetting(std::move(value)); return *this;}
/**
* <p>The closing setting specified for the intent.</p>
*/
inline const IntentClosingSetting& GetIntentClosingSetting() const{ return m_intentClosingSetting; }
/**
* <p>The closing setting specified for the intent.</p>
*/
inline void SetIntentClosingSetting(const IntentClosingSetting& value) { m_intentClosingSetting = value; }
/**
* <p>The closing setting specified for the intent.</p>
*/
inline void SetIntentClosingSetting(IntentClosingSetting&& value) { m_intentClosingSetting = std::move(value); }
/**
* <p>The closing setting specified for the intent.</p>
*/
inline CreateIntentResult& WithIntentClosingSetting(const IntentClosingSetting& value) { SetIntentClosingSetting(value); return *this;}
/**
* <p>The closing setting specified for the intent.</p>
*/
inline CreateIntentResult& WithIntentClosingSetting(IntentClosingSetting&& value) { SetIntentClosingSetting(std::move(value)); return *this;}
/**
* <p>The list of input contexts specified for the intent.</p>
*/
inline const Aws::Vector<InputContext>& GetInputContexts() const{ return m_inputContexts; }
/**
* <p>The list of input contexts specified for the intent.</p>
*/
inline void SetInputContexts(const Aws::Vector<InputContext>& value) { m_inputContexts = value; }
/**
* <p>The list of input contexts specified for the intent.</p>
*/
inline void SetInputContexts(Aws::Vector<InputContext>&& value) { m_inputContexts = std::move(value); }
/**
* <p>The list of input contexts specified for the intent.</p>
*/
inline CreateIntentResult& WithInputContexts(const Aws::Vector<InputContext>& value) { SetInputContexts(value); return *this;}
/**
* <p>The list of input contexts specified for the intent.</p>
*/
inline CreateIntentResult& WithInputContexts(Aws::Vector<InputContext>&& value) { SetInputContexts(std::move(value)); return *this;}
/**
* <p>The list of input contexts specified for the intent.</p>
*/
inline CreateIntentResult& AddInputContexts(const InputContext& value) { m_inputContexts.push_back(value); return *this; }
/**
* <p>The list of input contexts specified for the intent.</p>
*/
inline CreateIntentResult& AddInputContexts(InputContext&& value) { m_inputContexts.push_back(std::move(value)); return *this; }
/**
* <p>The list of output contexts specified for the intent.</p>
*/
inline const Aws::Vector<OutputContext>& GetOutputContexts() const{ return m_outputContexts; }
/**
* <p>The list of output contexts specified for the intent.</p>
*/
inline void SetOutputContexts(const Aws::Vector<OutputContext>& value) { m_outputContexts = value; }
/**
* <p>The list of output contexts specified for the intent.</p>
*/
inline void SetOutputContexts(Aws::Vector<OutputContext>&& value) { m_outputContexts = std::move(value); }
/**
* <p>The list of output contexts specified for the intent.</p>
*/
inline CreateIntentResult& WithOutputContexts(const Aws::Vector<OutputContext>& value) { SetOutputContexts(value); return *this;}
/**
* <p>The list of output contexts specified for the intent.</p>
*/
inline CreateIntentResult& WithOutputContexts(Aws::Vector<OutputContext>&& value) { SetOutputContexts(std::move(value)); return *this;}
/**
* <p>The list of output contexts specified for the intent.</p>
*/
inline CreateIntentResult& AddOutputContexts(const OutputContext& value) { m_outputContexts.push_back(value); return *this; }
/**
* <p>The list of output contexts specified for the intent.</p>
*/
inline CreateIntentResult& AddOutputContexts(OutputContext&& value) { m_outputContexts.push_back(std::move(value)); return *this; }
/**
* <p>Configuration for searching a Amazon Kendra index specified for the
* intent.</p>
*/
inline const KendraConfiguration& GetKendraConfiguration() const{ return m_kendraConfiguration; }
/**
* <p>Configuration for searching a Amazon Kendra index specified for the
* intent.</p>
*/
inline void SetKendraConfiguration(const KendraConfiguration& value) { m_kendraConfiguration = value; }
/**
* <p>Configuration for searching a Amazon Kendra index specified for the
* intent.</p>
*/
inline void SetKendraConfiguration(KendraConfiguration&& value) { m_kendraConfiguration = std::move(value); }
/**
* <p>Configuration for searching a Amazon Kendra index specified for the
* intent.</p>
*/
inline CreateIntentResult& WithKendraConfiguration(const KendraConfiguration& value) { SetKendraConfiguration(value); return *this;}
/**
* <p>Configuration for searching a Amazon Kendra index specified for the
* intent.</p>
*/
inline CreateIntentResult& WithKendraConfiguration(KendraConfiguration&& value) { SetKendraConfiguration(std::move(value)); return *this;}
/**
* <p>The identifier of the bot associated with the intent.</p>
*/
inline const Aws::String& GetBotId() const{ return m_botId; }
/**
* <p>The identifier of the bot associated with the intent.</p>
*/
inline void SetBotId(const Aws::String& value) { m_botId = value; }
/**
* <p>The identifier of the bot associated with the intent.</p>
*/
inline void SetBotId(Aws::String&& value) { m_botId = std::move(value); }
/**
* <p>The identifier of the bot associated with the intent.</p>
*/
inline void SetBotId(const char* value) { m_botId.assign(value); }
/**
* <p>The identifier of the bot associated with the intent.</p>
*/
inline CreateIntentResult& WithBotId(const Aws::String& value) { SetBotId(value); return *this;}
/**
* <p>The identifier of the bot associated with the intent.</p>
*/
inline CreateIntentResult& WithBotId(Aws::String&& value) { SetBotId(std::move(value)); return *this;}
/**
* <p>The identifier of the bot associated with the intent.</p>
*/
inline CreateIntentResult& WithBotId(const char* value) { SetBotId(value); return *this;}
/**
* <p>The identifier of the version of the bot associated with the intent.</p>
*/
inline const Aws::String& GetBotVersion() const{ return m_botVersion; }
/**
* <p>The identifier of the version of the bot associated with the intent.</p>
*/
inline void SetBotVersion(const Aws::String& value) { m_botVersion = value; }
/**
* <p>The identifier of the version of the bot associated with the intent.</p>
*/
inline void SetBotVersion(Aws::String&& value) { m_botVersion = std::move(value); }
/**
* <p>The identifier of the version of the bot associated with the intent.</p>
*/
inline void SetBotVersion(const char* value) { m_botVersion.assign(value); }
/**
* <p>The identifier of the version of the bot associated with the intent.</p>
*/
inline CreateIntentResult& WithBotVersion(const Aws::String& value) { SetBotVersion(value); return *this;}
/**
* <p>The identifier of the version of the bot associated with the intent.</p>
*/
inline CreateIntentResult& WithBotVersion(Aws::String&& value) { SetBotVersion(std::move(value)); return *this;}
/**
* <p>The identifier of the version of the bot associated with the intent.</p>
*/
inline CreateIntentResult& WithBotVersion(const char* value) { SetBotVersion(value); return *this;}
/**
* <p>The locale that the intent is specified to use.</p>
*/
inline const Aws::String& GetLocaleId() const{ return m_localeId; }
/**
* <p>The locale that the intent is specified to use.</p>
*/
inline void SetLocaleId(const Aws::String& value) { m_localeId = value; }
/**
* <p>The locale that the intent is specified to use.</p>
*/
inline void SetLocaleId(Aws::String&& value) { m_localeId = std::move(value); }
/**
* <p>The locale that the intent is specified to use.</p>
*/
inline void SetLocaleId(const char* value) { m_localeId.assign(value); }
/**
* <p>The locale that the intent is specified to use.</p>
*/
inline CreateIntentResult& WithLocaleId(const Aws::String& value) { SetLocaleId(value); return *this;}
/**
* <p>The locale that the intent is specified to use.</p>
*/
inline CreateIntentResult& WithLocaleId(Aws::String&& value) { SetLocaleId(std::move(value)); return *this;}
/**
* <p>The locale that the intent is specified to use.</p>
*/
inline CreateIntentResult& WithLocaleId(const char* value) { SetLocaleId(value); return *this;}
/**
* <p>A timestamp of the date and time that the intent was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreationDateTime() const{ return m_creationDateTime; }
/**
* <p>A timestamp of the date and time that the intent was created.</p>
*/
inline void SetCreationDateTime(const Aws::Utils::DateTime& value) { m_creationDateTime = value; }
/**
* <p>A timestamp of the date and time that the intent was created.</p>
*/
inline void SetCreationDateTime(Aws::Utils::DateTime&& value) { m_creationDateTime = std::move(value); }
/**
* <p>A timestamp of the date and time that the intent was created.</p>
*/
inline CreateIntentResult& WithCreationDateTime(const Aws::Utils::DateTime& value) { SetCreationDateTime(value); return *this;}
/**
* <p>A timestamp of the date and time that the intent was created.</p>
*/
inline CreateIntentResult& WithCreationDateTime(Aws::Utils::DateTime&& value) { SetCreationDateTime(std::move(value)); return *this;}
/**
* <p>Configuration settings for the response that is sent to the user at the
* beginning of a conversation, before eliciting slot values.</p>
*/
inline const InitialResponseSetting& GetInitialResponseSetting() const{ return m_initialResponseSetting; }
/**
* <p>Configuration settings for the response that is sent to the user at the
* beginning of a conversation, before eliciting slot values.</p>
*/
inline void SetInitialResponseSetting(const InitialResponseSetting& value) { m_initialResponseSetting = value; }
/**
* <p>Configuration settings for the response that is sent to the user at the
* beginning of a conversation, before eliciting slot values.</p>
*/
inline void SetInitialResponseSetting(InitialResponseSetting&& value) { m_initialResponseSetting = std::move(value); }
/**
* <p>Configuration settings for the response that is sent to the user at the
* beginning of a conversation, before eliciting slot values.</p>
*/
inline CreateIntentResult& WithInitialResponseSetting(const InitialResponseSetting& value) { SetInitialResponseSetting(value); return *this;}
/**
* <p>Configuration settings for the response that is sent to the user at the
* beginning of a conversation, before eliciting slot values.</p>
*/
inline CreateIntentResult& WithInitialResponseSetting(InitialResponseSetting&& value) { SetInitialResponseSetting(std::move(value)); return *this;}
private:
Aws::String m_intentId;
Aws::String m_intentName;
Aws::String m_description;
Aws::String m_parentIntentSignature;
Aws::Vector<SampleUtterance> m_sampleUtterances;
DialogCodeHookSettings m_dialogCodeHook;
FulfillmentCodeHookSettings m_fulfillmentCodeHook;
IntentConfirmationSetting m_intentConfirmationSetting;
IntentClosingSetting m_intentClosingSetting;
Aws::Vector<InputContext> m_inputContexts;
Aws::Vector<OutputContext> m_outputContexts;
KendraConfiguration m_kendraConfiguration;
Aws::String m_botId;
Aws::String m_botVersion;
Aws::String m_localeId;
Aws::Utils::DateTime m_creationDateTime;
InitialResponseSetting m_initialResponseSetting;
};
} // namespace Model
} // namespace LexModelsV2
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
bb830c4b396dd98311014f09dcaddf83ec410d12 | cc76719dcc72f6956c6f07ee19ad29d04c063f96 | /widgets/coloredcircleindicator.h | 177e58608325bbd553b31ff7e8899473f184f192 | [] | no_license | team751/Qt-FMS | 90136867d0c50ce55c8937ed957dbd2a2ccf643f | c4c764ae35f3ca4e40c59b7f9675adbdafcd192b | refs/heads/master | 2021-01-10T20:56:22.805094 | 2013-04-12T04:43:20 | 2013-04-12T04:43:20 | 9,365,369 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,084 | h | #ifndef COLOREDCIRCLEINDICATOR_H
#define COLOREDCIRCLEINDICATOR_H
#include "coloredcirclewidget.h"
namespace Ui {
class ColoredCircleIndicator;
}
/**
* @brief The ColoredCircleIndicator class is a type of ColoredCircleWidget
* that provides methods that map statuses to colors.
*/
class ColoredCircleIndicator : public ColoredCircleWidget
{
Q_OBJECT
public:
explicit ColoredCircleIndicator(QWidget *parent = 0);
~ColoredCircleIndicator();
/**
* @brief indicateError Display an error status
*/
void indicateError() {
//display red
ColoredCircleWidget::setCircleColor(Qt::red);
}
void indicateOK() {
//display green
ColoredCircleWidget::setCircleColor(Qt::green);
}
void indicateWarning() {
//display yellow
ColoredCircleWidget::setCircleColor(Qt::yellow);
}
void indicateOff() {
//display gray
ColoredCircleWidget::setCircleColor(Qt::gray);
}
private:
Ui::ColoredCircleIndicator *ui;
};
#endif // COLOREDCIRCLEINDICATOR_H
| [
"sp4.c.eatpie.info@gmail.com"
] | sp4.c.eatpie.info@gmail.com |
fa3fc7fb1df3680931229081d27f79bc02480d61 | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /chrome/browser/policy/browser_dm_token_storage_unittest.cc | 8a3944a12b1a9f81803c6e571aa43aaefa3f1408 | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 2,551 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/browser_dm_token_storage.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/policy/fake_browser_dm_token_storage.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::IsEmpty;
namespace policy {
namespace {
constexpr char kClientId1[] = "fake-client-id-1";
constexpr char kClientId2[] = "fake-client-id-2";
constexpr char kEnrollmentToken1[] = "fake-enrollment-token-1";
constexpr char kEnrollmentToken2[] = "fake-enrollment-token-2";
constexpr char kDMToken1[] = "fake-dm-token-1";
constexpr char kDMToken2[] = "fake-dm-token-2";
} // namespace
class BrowserDMTokenStorageTest : public testing::Test {
public:
BrowserDMTokenStorageTest()
: storage_(kClientId1, kEnrollmentToken1, kDMToken1, false) {}
FakeBrowserDMTokenStorage storage_;
private:
content::BrowserTaskEnvironment task_environment_;
};
TEST_F(BrowserDMTokenStorageTest, RetrieveClientId) {
EXPECT_EQ(kClientId1, storage_.RetrieveClientId());
// The client ID value should be cached in memory and not read from the system
// again.
storage_.SetClientId(kClientId2);
EXPECT_EQ(kClientId1, storage_.RetrieveClientId());
}
TEST_F(BrowserDMTokenStorageTest, RetrieveEnrollmentToken) {
EXPECT_EQ(kEnrollmentToken1, storage_.RetrieveEnrollmentToken());
// The enrollment token should be cached in memory and not read from the
// system again.
storage_.SetEnrollmentToken(kEnrollmentToken2);
EXPECT_EQ(kEnrollmentToken1, storage_.RetrieveEnrollmentToken());
}
TEST_F(BrowserDMTokenStorageTest, RetrieveDMToken) {
EXPECT_EQ(kDMToken1, storage_.RetrieveDMToken());
// The DM token should be cached in memory and not read from the system again.
storage_.SetDMToken(kDMToken2);
EXPECT_EQ(kDMToken1, storage_.RetrieveDMToken());
}
TEST_F(BrowserDMTokenStorageTest, ShouldDisplayErrorMessageOnFailure) {
EXPECT_FALSE(storage_.ShouldDisplayErrorMessageOnFailure());
// The error option should be cached in memory and not read from the system
// again.
storage_.SetEnrollmentErrorOption(true);
EXPECT_FALSE(storage_.ShouldDisplayErrorMessageOnFailure());
}
} // namespace policy
| [
"rjkroege@chromium.org"
] | rjkroege@chromium.org |
e910b37aea1c922ba28bd03e3bbbcebff8b6280a | 36c603cda8c3155e731559556f6d0272d0733f6c | /clash of basu/include/GiantCrad.h | a07f1de58a5ffa29bfd75e35538c0ed144b7022e | [] | no_license | sadeghhosseiny/Clash-of-Basu | a7a0115d0a0ade5da349ffd0b38086ff2211a131 | 66a244805635d3937b7e83b5b7d6a0c80d0950fc | refs/heads/master | 2020-12-05T11:52:54.428312 | 2020-02-01T19:27:55 | 2020-02-01T19:27:55 | 232,099,700 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | h | #ifndef GIANTCRAD_H
#define GIANTCRAD_H
#include "HeroCards.h"
class GiantCrad : public HeroCards
{
public:
GiantCrad();
virtual void DrawCard(sf::RenderWindow*);
virtual ~GiantCrad();
sf::Sprite& getspr();
private:
};
#endif // GIANTCRAD_H
| [
"sadeghmessi2015@gmail.com"
] | sadeghmessi2015@gmail.com |
9e6433fe142cc7617f4063bb396a45ddc031eb6a | 5636014eed0a98934ba21d2ed7057c7eae14ad33 | /unit-test/test_tree_height_reduction.cpp | b53ab0a78f41fdf08f1c8abcc5dafc0b13164aaa | [
"BSL-1.0"
] | permissive | keshavmat/ALADDIN | a4d9fb065e502390cf93b7426ef81030b4c0a9ec | a45516977b52a38803b9f7b883ac16205e523a78 | refs/heads/master | 2021-01-22T00:10:32.511477 | 2015-07-02T06:43:30 | 2015-07-02T06:43:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,473 | cpp | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "DDDG.h"
#include "file_func.h"
#include "Scratchpad.h"
#include "ScratchpadDatapath.h"
SCENARIO("Test treeHeightReduction w/ Reduction", "[reduction]") {
GIVEN("Test Reduction w/ Input Size 128") {
std::string bench("outputs/reduction-128");
std::string trace_file("inputs/reduction-128-trace.gz");
std::string config_file("inputs/config-reduction-p4-u4-P1");
ScratchpadDatapath* acc;
Scratchpad* spad;
acc = new ScratchpadDatapath(bench, trace_file, config_file);
acc->buildDddg();
acc->removeInductionDependence();
acc->removePhiNodes();
acc->initBaseAddress();
acc->scratchpadPartition();
acc->loopUnrolling();
WHEN("before treeHeightReduction()") {
THEN("Distance between the last sums in two unrolled iterations should "
"be 4.") {
REQUIRE(acc->shortestDistanceBetweenNodes(29, 61) == 4);
REQUIRE(acc->shortestDistanceBetweenNodes(61, 93) == 4);
REQUIRE(acc->shortestDistanceBetweenNodes(989, 1021) == 4);
}
}
WHEN("Test treeHeightReduction()") {
acc->treeHeightReduction();
THEN("Distance between the last sums in two unrolled iterations should "
"be 1.") {
REQUIRE(acc->shortestDistanceBetweenNodes(29, 61) == 1);
REQUIRE(acc->shortestDistanceBetweenNodes(61, 93) == 1);
REQUIRE(acc->shortestDistanceBetweenNodes(989, 1021) == 1);
}
}
}
}
| [
"shao@eecs.harvard.edu"
] | shao@eecs.harvard.edu |
68678620ad8a3ff72432365d4e4df799a250ef00 | 352f43aab0521dcdb4897298961daed575d457f6 | /BOCA/BK/src/checker.cpp | 26235a066a79cea77dcae409799b9d7ec80a3ea8 | [
"MIT"
] | permissive | danielsaad/PC1-IFB-CC | 012947dff72b55a1acb83fd1453102ff55dd2247 | 36b55e95373a5f022651545248d8cb66bac1cd3f | refs/heads/master | 2022-02-21T22:23:59.122236 | 2019-10-18T14:06:08 | 2019-10-18T14:06:08 | 100,300,073 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 885 | cpp | #include "testlib.h"
using namespace std;
int main(int argc, char *argv[]) {
setName("compare sequences of tokens");
registerTestlibCmd(argc, argv);
int n = 0;
string j, p;
while (!ans.seekEof() && !ouf.seekEof()) {
n++;
ans.readWordTo(j);
ouf.readWordTo(p);
if (j != p)
quitf(_wa, "%d%s words differ - expected: '%s', found: '%s'", n,
englishEnding(n).c_str(), compress(j).c_str(),
compress(p).c_str());
}
if (ans.seekEof() && ouf.seekEof()) {
if (n == 1)
quitf(_ok, "\"%s\"", compress(j).c_str());
else
quitf(_ok, "%d tokens", n);
} else {
if (ans.seekEof())
quitf(_wa, "Participant output contains extra tokens");
else
quitf(_wa, "Unexpected EOF in the participants output");
}
} | [
"daniel.saad.nunes@gmail.com"
] | daniel.saad.nunes@gmail.com |
bb70ffee88f8eb3d75177a9750d647a5e0e92177 | 3db023edb0af1dcf8a1da83434d219c3a96362ba | /windows_nt_3_5_source_code/NT-782/PRIVATE/NET/UI/COMMON/SRC/BLT/TESTAPPS/TESTER.CXX | d0eee6b3c1c9d9e40dbc9afc40bc5966ad67850a | [] | no_license | xiaoqgao/windows_nt_3_5_source_code | de30e9b95856bc09469d4008d76191f94379c884 | d2894c9125ff1c14028435ed1b21164f6b2b871a | refs/heads/master | 2022-12-23T17:58:33.768209 | 2020-09-28T20:20:18 | 2020-09-28T20:20:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,436 | cxx | /**********************************************************************/
/** Microsoft LAN Manager **/
/** Copyright(c) Microsoft Corp., 1990, 1991 **/
/**********************************************************************/
/*
tester.cxx
misc functions for the test application program
FILE HISTORY:
terryk 27-Mar-1991 Creation
terryk 27-Mar-1991 code review
*/
#include "tester.hxx"
/**********************************************************\
NAME: DIALOG_WINDOW_WITH_END::OnCommand
SYNOPSIS: Terminate the window on the END button
ENTRY: CID wParam - the information parameter
ULONG lParam - any information paramter
HISTORY:
terryk 27-Mar-1991 creation
\**********************************************************/
DIALOG_WINDOW_WITH_END::OnCommand( const CONTROL_EVENT & e )
{
switch (e.QueryWParam())
{
case IDD_END:
// If END button then terminate the dialog box.
Dismiss( TRUE );
return TRUE;
default:
return FALSE;
}
}
/**********************************************************\
NAME: NOT_IMPLEMENT_Tester
SYNOPSIS: display the "not implemented" message
ENTRY: HWND hwnd - current window handle
HISTORY:
terryk 27-Mar-1991 creation
\**********************************************************/
void NOT_IMPLEMENT_Tester( HWND hWnd )
{
DIALOG_WINDOW dlg( "D_NOT_IMPLEMENT", hWnd );
dlg.Process();
}
/**********************************************************\
NAME: PopupNoArg_Tester
SYNOPSIS: use the Msgpopup function without any argument
ENTRY: HWND hwnd - current window handle
HISTORY:
terryk 27-Mar-1991 creation
\**********************************************************/
void PopupNoArg_Tester( HWND hWnd )
{
MsgPopup( hWnd, IDS_MSGUP, MPSEV_INFO );
MsgPopup( hWnd, IDS_MSGUP_BUT, MPSEV_INFO, MP_OKCANCEL );
}
/**********************************************************\
NAME: Popup1Arg_Tester
SYNOPSIS: use the Msgpopup function with 1 argument
ENTRY: HWND hwnd - current window handle
HISTORY:
terryk 27-Mar-1991 creation
\**********************************************************/
void Popup1Arg_Tester( HWND hWnd )
{
MsgPopup( hWnd, IDS_MSGUP_1_BUT, MPSEV_INFO, MP_OKCANCEL, "String 1" );
}
/**********************************************************\
NAME: Popup2Arg_Tester
SYNOPSIS: use the Msgpopup function with 2 arguments
ENTRY: HWND hwnd - current window handle
HISTORY:
terryk 27-Mar-1991 creation
\**********************************************************/
void Popup2Arg_Tester( HWND hWnd )
{
MsgPopup( hWnd, IDS_MSGUP_2_BUT, MPSEV_INFO, MP_OKCANCEL, "String 1",
"String 2" );
}
/**********************************************************\
NAME: QUIT_Tester
SYNOPSIS: end the BLT applicaiton by sending a close message
ENTRY: HWND hwnd - current window handle
HISTORY:
terryk 27-Mar-1991 creation
\**********************************************************/
void QUIT_Tester( HWND hWnd )
{
SendMessage( hWnd, WM_CLOSE, 0, 0l );
}
/**********************************************************\
NAME: ResourceString
SYNOPSIS: given a resource string id and return a pointer to the string.
ENTRY: WORD id - resource string id
HISTORY:
terryk 27-Mar-1991 creation
\**********************************************************/
TCHAR *ResourceString ( WORD wID, SHORT n )
{
static TCHAR szBuffer[3][256]; //256 is just a big number
LoadString( ::QueryInst(), wID, szBuffer[n], 255 );
return szBuffer[n] ;
}
void SLN::SetNum( int n )
{
TCHAR achInteger[30]; // just pick the number 30 for the size
SetText( itoa( n, achInteger, 10 ));
}
SLN::SLN ( OWNER_WINDOW *powin, CID cid )
:SLT( powin, cid )
{
_iCount = 0;
}
void SLN::operator = ( int n )
{
_iCount = n;
SetNum( _iCount );
}
void SLN::operator ++ ( void )
{
_iCount ++ ;
SetNum( _iCount );
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
7896adef7dc02f9a96f47af29291bd7b725035b1 | d038bde7c966fe1b3cef8f2dbb3fe6ef40182385 | /Sandbox/threadTest/joystickData.h | fac84cd92111720f47caeb380196dc03723af862 | [] | no_license | platvlad/RoboCP | 50d14185ac3b35f92406e4733ab0dc9c3fac895c | 7f103b8032be67a042eb552d449879c2a603077c | refs/heads/master | 2021-01-15T09:46:34.961682 | 2015-07-06T09:18:53 | 2015-07-06T09:18:53 | 38,608,568 | 0 | 0 | null | 2015-07-06T09:07:30 | 2015-07-06T09:07:29 | C++ | UTF-8 | C++ | false | false | 165 | h | #pragma once
class joystickData{
joystickData(int a, int b, int c, int d) :rudder(a), gas(b), pitch(c), roll(d){};
int rudder;
int gas;
int pitch;
int roll;
}; | [
"egor.schavelev@gmail.com"
] | egor.schavelev@gmail.com |
aeb59af4a8badd5effdc3f81f735405bfb9a5c96 | 6cc293ac8950dff03408e9ab498889c895cf6f82 | /source/basic/decltype.cpp | a5c1b4f541360ca14c7f4a692402305a1e71d78e | [
"MIT"
] | permissive | JianboYan/cppthings-learning | 65de04683fd7b9dae931f7b1914ab7d3052dfd46 | 71c15213474786795fb09800efd3cf19ee562681 | refs/heads/main | 2022-12-22T03:13:58.111576 | 2020-10-02T14:08:17 | 2020-10-02T14:08:17 | 300,462,174 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,318 | cpp | //
// decltype.cpp
// CppThings
//
// Created by Ryan on 2020/10/2.
//
#include <iostream>
#include <vector>
namespace Decltype {
using namespace std;
int MAIN(){
// 1. 基本使用
// 1.1. 推导类型,类似typeof
int a = 4;
decltype(a) i = 2;
CTLLOG_1(i);
typeof(a) ti = 4;
CTLLOG_1(ti);
// 1.2 与using/typedef合用,用于定义类型
using size_t = decltype(sizeof(0));//sizeof(a)的返回值为size_t类型
__unused size_t s = 100;
using ptrdiff_t = decltype((int*)0 - (int*)0);
__unused ptrdiff_t p = 0;
using nullptr_t = decltype(nullptr);
__unused nullptr_t np = 0;
vector<int >vec;
typedef decltype(vec.begin()) vectype;
vec.push_back(1);
vec.push_back(2);
for (vectype vt = vec.begin(); vt != vec.end(); vt ++){
CTLLOG_1(*vt);
}
// 1.3 重用匿名类型
{
struct
{
int d ;
double b;
}as;
as.d = 2;
decltype(as) as2 ;//定义了一个上面匿名的结构体
CTLLOG_1(as.d); // as.d is 2
CTLLOG_1(as2.d); // as2.d is 0
}
return 0;
}
// 1.4 泛型编程中结合auto,用于追踪函数的返回值类型
template <typename T>
auto multiply(T x, T y)->decltype(x*y)
{
return x*y;
}
}
namespace DecltypeRegulations {
using namespace std;
int MAIN(){
// 2. 判别规则
int arr[5] = { 0 };
//规则一:推导为其类型
decltype (arr) var1; //int 标记符表达式
int *ptr = arr;
decltype (ptr) var2;//int * 标记符表达式
struct S{ double d; }s ;
decltype(s.d) var3;//double 成员访问表达式
void Overloaded(int);
void Overloaded(char);//重载的函数
//decltype(Overloaded) var4;//重载函数。编译错误。
//规则二:将亡值。推导为类型的右值引用。 int&&
int && RvalRef();
decltype (RvalRef()) var5 = 1;
//规则三:左值,推导为类型的引用。
int i = 4;
decltype ((i))var6 = i; //int&, 注意是((i))
var6 = 6;
CTLLOG_1(i); // i is 6
decltype (true ? i : i) var7 = i; //int& 条件表达式返回左值。
var7 = 7;
CTLLOG_1(i); // i is 7
decltype (++i) var8 = i; //int& ++i返回i的左值。
var8 = 8;
CTLLOG_1(i); // i is 8
decltype(arr[5]) var9 = i;//int&. []操作返回左值
var9 = 9;
CTLLOG_1(i); // i is 9
decltype(*ptr)var10 = i;//int& *操作返回左值
var10 = 10;
CTLLOG_1(i); // i is 10
decltype("hello")var11 = "hello"; //const char(&)[9] 字符串字面常量为左值,且为const左值。
// var11[0] = 'H'; // error: Cannot assign to variable 'var11' with const-qualified type 'decltype("hello")' (aka 'const char (&)[6]')
//规则四:以上都不是,则推导为本类型
decltype(1) var12; // FIX: const int ==> int
// var12 = "hello"; // error: Assigning to 'decltype(1)' (aka 'int') from incompatible type 'const char [6]'
const bool Func(int);
decltype(Func(1)) var13=true;// FIX: const bool ==> bool
var13 = false;
decltype(i++) var14 = i;//int i++返回右值
var14 = 14; //
CTLLOG_1(i); // i is 10, 并不是饮用
return 0;
}
}
| [
"jianbo.yjb@alibaba-inc.com"
] | jianbo.yjb@alibaba-inc.com |
8dc0d63bbe22524e03092a6ae6a460bd79323984 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /content/browser/web_package/signed_exchange_certificate_chain_unittest.cc | 0d93a8ebc390c5955568e1a2dbf6bbf7a6804d50 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 9,339 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/web_package/signed_exchange_certificate_chain.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/optional.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "components/cbor/values.h"
#include "components/cbor/writer.h"
#include "content/browser/web_package/signed_exchange_test_utils.h"
#include "content/public/common/content_paths.h"
#include "net/cert/x509_util.h"
#include "net/test/cert_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
cbor::Value CBORByteString(base::StringPiece str) {
return cbor::Value(str, cbor::Value::Type::BYTE_STRING);
}
scoped_refptr<net::X509Certificate> LoadCertificate(
const std::string& cert_file) {
base::FilePath dir_path;
base::PathService::Get(content::DIR_TEST_DATA, &dir_path);
dir_path = dir_path.AppendASCII("sxg");
return net::CreateCertificateChainFromFile(
dir_path, cert_file, net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
}
} // namespace
TEST(SignedExchangeCertificateParseTest, Empty) {
auto parsed = SignedExchangeCertificateChain::Parse(
base::span<const uint8_t>(), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseTest, EmptyChain) {
cbor::Value::ArrayValue cbor_array;
cbor_array.push_back(cbor::Value(u8"\U0001F4DC\u26D3"));
auto serialized = cbor::Writer::Write(cbor::Value(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseTest, MissingCert) {
cbor::Value::MapValue cbor_map;
cbor_map[cbor::Value("sct")] = CBORByteString("SCT");
cbor_map[cbor::Value("ocsp")] = CBORByteString("OCSP");
cbor::Value::ArrayValue cbor_array;
cbor_array.push_back(cbor::Value(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::Value(std::move(cbor_map)));
auto serialized = cbor::Writer::Write(cbor::Value(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseTest, OneCert) {
net::CertificateList certs;
ASSERT_TRUE(
net::LoadCertificateFiles({"subjectAltName_sanity_check.pem"}, &certs));
ASSERT_EQ(1U, certs.size());
base::StringPiece cert_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
cbor::Value::MapValue cbor_map;
cbor_map[cbor::Value("sct")] = CBORByteString("SCT");
cbor_map[cbor::Value("cert")] = CBORByteString(cert_der);
cbor_map[cbor::Value("ocsp")] = CBORByteString("OCSP");
cbor::Value::ArrayValue cbor_array;
cbor_array.push_back(cbor::Value(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::Value(std::move(cbor_map)));
auto serialized = cbor::Writer::Write(cbor::Value(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
base::make_span(*serialized), nullptr);
ASSERT_TRUE(parsed);
EXPECT_EQ(cert_der, net::x509_util::CryptoBufferAsStringPiece(
parsed->cert()->cert_buffer()));
ASSERT_EQ(0U, parsed->cert()->intermediate_buffers().size());
EXPECT_EQ(parsed->ocsp(), base::make_optional<std::string>("OCSP"));
EXPECT_EQ(parsed->sct(), base::make_optional<std::string>("SCT"));
}
TEST(SignedExchangeCertificateParseTest, MissingOCSPInFirstCert) {
net::CertificateList certs;
ASSERT_TRUE(
net::LoadCertificateFiles({"subjectAltName_sanity_check.pem"}, &certs));
ASSERT_EQ(1U, certs.size());
base::StringPiece cert_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
cbor::Value::MapValue cbor_map;
cbor_map[cbor::Value("sct")] = CBORByteString("SCT");
cbor_map[cbor::Value("cert")] = CBORByteString(cert_der);
cbor::Value::ArrayValue cbor_array;
cbor_array.push_back(cbor::Value(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::Value(std::move(cbor_map)));
auto serialized = cbor::Writer::Write(cbor::Value(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseTest, TwoCerts) {
net::CertificateList certs;
ASSERT_TRUE(net::LoadCertificateFiles(
{"subjectAltName_sanity_check.pem", "root_ca_cert.pem"}, &certs));
ASSERT_EQ(2U, certs.size());
base::StringPiece cert1_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
base::StringPiece cert2_der =
net::x509_util::CryptoBufferAsStringPiece(certs[1]->cert_buffer());
cbor::Value::MapValue cbor_map1;
cbor_map1[cbor::Value("sct")] = CBORByteString("SCT");
cbor_map1[cbor::Value("cert")] = CBORByteString(cert1_der);
cbor_map1[cbor::Value("ocsp")] = CBORByteString("OCSP");
cbor::Value::MapValue cbor_map2;
cbor_map2[cbor::Value("cert")] = CBORByteString(cert2_der);
cbor::Value::ArrayValue cbor_array;
cbor_array.push_back(cbor::Value(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::Value(std::move(cbor_map1)));
cbor_array.push_back(cbor::Value(std::move(cbor_map2)));
auto serialized = cbor::Writer::Write(cbor::Value(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
base::make_span(*serialized), nullptr);
ASSERT_TRUE(parsed);
EXPECT_EQ(cert1_der, net::x509_util::CryptoBufferAsStringPiece(
parsed->cert()->cert_buffer()));
ASSERT_EQ(1U, parsed->cert()->intermediate_buffers().size());
EXPECT_EQ(cert2_der, net::x509_util::CryptoBufferAsStringPiece(
parsed->cert()->intermediate_buffers()[0].get()));
EXPECT_EQ(parsed->ocsp(), base::make_optional<std::string>("OCSP"));
EXPECT_EQ(parsed->sct(), base::make_optional<std::string>("SCT"));
}
TEST(SignedExchangeCertificateParseTest, HavingOCSPInSecondCert) {
net::CertificateList certs;
ASSERT_TRUE(net::LoadCertificateFiles(
{"subjectAltName_sanity_check.pem", "root_ca_cert.pem"}, &certs));
ASSERT_EQ(2U, certs.size());
base::StringPiece cert1_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
base::StringPiece cert2_der =
net::x509_util::CryptoBufferAsStringPiece(certs[1]->cert_buffer());
cbor::Value::MapValue cbor_map1;
cbor_map1[cbor::Value("sct")] = CBORByteString("SCT");
cbor_map1[cbor::Value("cert")] = CBORByteString(cert1_der);
cbor_map1[cbor::Value("ocsp")] = CBORByteString("OCSP1");
cbor::Value::MapValue cbor_map2;
cbor_map2[cbor::Value("cert")] = CBORByteString(cert2_der);
cbor_map2[cbor::Value("ocsp")] = CBORByteString("OCSP2");
cbor::Value::ArrayValue cbor_array;
cbor_array.push_back(cbor::Value(u8"\U0001F4DC\u26D3"));
cbor_array.push_back(cbor::Value(std::move(cbor_map1)));
cbor_array.push_back(cbor::Value(std::move(cbor_map2)));
auto serialized = cbor::Writer::Write(cbor::Value(std::move(cbor_array)));
ASSERT_TRUE(serialized.has_value());
auto parsed = SignedExchangeCertificateChain::Parse(
base::make_span(*serialized), nullptr);
EXPECT_FALSE(parsed);
}
TEST(SignedExchangeCertificateParseTest, ParseGoldenFile) {
base::FilePath path;
base::PathService::Get(content::DIR_TEST_DATA, &path);
path =
path.AppendASCII("sxg").AppendASCII("test.example.org.public.pem.cbor");
std::string contents;
ASSERT_TRUE(base::ReadFileToString(path, &contents));
auto parsed = SignedExchangeCertificateChain::Parse(
base::as_bytes(base::make_span(contents)), nullptr);
ASSERT_TRUE(parsed);
}
TEST(SignedExchangeCertificateChainTest, IgnoreErrorsSPKIList) {
SignedExchangeCertificateChain::IgnoreErrorsSPKIList ignore_nothing("");
SignedExchangeCertificateChain::IgnoreErrorsSPKIList ignore_ecdsap256(
kPEMECDSAP256SPKIHash);
SignedExchangeCertificateChain::IgnoreErrorsSPKIList ignore_ecdsap384(
kPEMECDSAP384SPKIHash);
SignedExchangeCertificateChain::IgnoreErrorsSPKIList ignore_both(
std::string(kPEMECDSAP256SPKIHash) + "," + kPEMECDSAP384SPKIHash);
scoped_refptr<net::X509Certificate> cert_ecdsap256 =
LoadCertificate("prime256v1-sha256.public.pem");
scoped_refptr<net::X509Certificate> cert_ecdsap384 =
LoadCertificate("secp384r1-sha256.public.pem");
EXPECT_FALSE(ignore_nothing.ShouldIgnoreErrorsInternal(cert_ecdsap256));
EXPECT_FALSE(ignore_nothing.ShouldIgnoreErrorsInternal(cert_ecdsap384));
EXPECT_TRUE(ignore_ecdsap256.ShouldIgnoreErrorsInternal(cert_ecdsap256));
EXPECT_FALSE(ignore_ecdsap256.ShouldIgnoreErrorsInternal(cert_ecdsap384));
EXPECT_FALSE(ignore_ecdsap384.ShouldIgnoreErrorsInternal(cert_ecdsap256));
EXPECT_TRUE(ignore_ecdsap384.ShouldIgnoreErrorsInternal(cert_ecdsap384));
EXPECT_TRUE(ignore_both.ShouldIgnoreErrorsInternal(cert_ecdsap256));
EXPECT_TRUE(ignore_both.ShouldIgnoreErrorsInternal(cert_ecdsap384));
}
} // namespace content
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.