blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
88be0f0c3eef5a6db8f32e4780b4a00b442828dd | 8a052790c03592314dd4e1a102e39a997166a726 | /WindHorn/WH3DInit.h | f12e78763e77aa072ba15e81a6515b87a485fbbf | [] | no_license | samshine/M2_ClientVC | 4369bb095ebc80939bb1edfd4cf9d90f26541a11 | b2babc931d8f9a95d0d6fb78be3ea5cb9833539d | refs/heads/master | 2021-08-23T08:28:56.859247 | 2017-12-04T09:18:36 | 2017-12-04T09:18:36 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,250 | h | /******************************************************************************************************************
모듈명:
작성자:
작성일:
[일자][수정자] : 수정 내용
*******************************************************************************************************************/
#ifndef _C3DINIT_H
#define _C3DINIT_H
class C3DInit
{
//1: Constructor/Destructor
public:
C3DInit();
~C3DInit();
private:
LPDIRECT3DDEVICE9 m_pd3dDevice;
protected:
D3DMATRIX m_matWorld;
D3DMATRIX m_matView;
D3DMATRIX m_matProj;
D3DMATERIAL9 m_mtrl;
public:
HRESULT InitDeviceObjects();
__inline static C3DInit* GetObj() { return m_px3DInit; }
__inline static VOID SetObj(C3DInit* pxObj) { m_px3DInit = pxObj; }
protected:
static C3DInit* m_px3DInit;
};
#endif //_C3DINIT_H | [
"394383649@qq.com"
] | 394383649@qq.com |
276fc5556794cb06bb18a877b70017425e8dc521 | 674cdaccfd2e8ef02dc119155d6e530ed949cca5 | /HMI_example/tuatorial1/Nextion_Tutorial1/Nextion_Tutorial1.ino | 8a86f5f76b1bfb43ded723b44d3d501509f38bb0 | [] | no_license | phamvanphuckks/Do-An | 01170940effddc25fce56691fbacf2387c93257c | e1cc3e3fd6f32824c38138bc091ddbcfa0324200 | refs/heads/master | 2023-08-08T14:30:25.986430 | 2020-09-06T15:07:00 | 2020-09-06T15:07:00 | 289,403,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,026 | ino | /*
The following sketch is an example of how to send data to the Nextion display without any library.
The data can be text, numbers, or any other atribute of an object.
You can also send System Variables to change settings on the display like: brightness, serial baud rate, etc.
Connection with Arduino Uno/Nano:
* +5V = 5V
* TX = none
* RX = pin 1 (TX)
* GND = GND
This sketch was made for my 1st video tutorial shown here: https://www.youtube.com/watch?v=wIWxSLVAAQE
Made by InterlinkKnight
Last update: 02/04/2018
*/
int variable1 = 0; // This is a simple variable to keep increasing a number to have something dynamic to show on the display.
void setup() { // Put your setup code here, to run once:
Serial.begin(9600); // Start serial comunication at baud=9600. For Arduino mega you would have to add a
// number (example: "Serial1.begin(9600);").
// If you use an Arduino mega, you have to also edit everything on this sketch that
// says "Serial" and replace it with "Serial1" (or whatever number you are using).
/*
// I am going to change the Serial baud to a faster rate (optional):
delay(500); // This dalay is just in case the nextion display didn't start yet, to be sure it will receive the following command.
Serial.print("baud=38400"); // Set new baud rate of nextion to 38400, but is temporal. Next time nextion is
// power on, it will retore to default baud of 9600.
// To take effect, make sure to reboot the arduino (reseting arduino is not enough).
// If you want to change the default baud, send the command as "bauds=38400", instead of "baud=38400".
// If you change default, everytime the nextion is power on is going to have that baud rate.
Serial.write(0xff); // We always have to send this three lines after each command sent to nextion.
Serial.write(0xff);
Serial.write(0xff);
Serial.end(); // End the serial comunication of baud=9600.
Serial.begin(38400); // Start serial comunication at baud=38400.
*/
} // End of setup
void loop() { // Put your main code here, to run repeatedly:
variable1++; // Increase the value of the variable by 1.
if(variable1 == 201){ // If the variable reach 201...
variable1 = 0; // Set the variable to 0 so it starts over again.
}
// We are going to send the variable value to the object called n0:
// After the name of the object you need to put the dot val because val is the atribute we want to change on that object.
Serial.print("n0.val="); // This is sent to the nextion display to set what object name (before the dot) and what atribute (after the dot) are you going to change.
Serial.print(variable1); // This is the value you want to send to that object and atribute mention before.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
// We are going to update the progress bar to show the value of the variable.
// The progress bar range goes from 0 to 100, so when the variable is greater than 100, the progress bar will keep showing full (100%).
Serial.print("j0.val="); // This is sent to the nextion display to set what object name (before the dot) and what atribute (after the dot) are you going to change.
Serial.print(variable1); // This is the value you want to send to that object and atribute mention before.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
// We are going to update the gauge to show the value of the variable.
// But instead of updating the gauge directly, we are going to send the value to a variable called va0 on the nextion display.
// On the nextion display we have a code on the timer (tm0) that compares the variable value and the gauge value, and updates the gauge only when they are different.
// The gauge range goes from 0 (pointing to the left) to 359.
Serial.print("va0.val="); // This is sent to the nextion display to set what object name (before the dot) and what atribute (after the dot) are you going to change.
Serial.print(variable1); // This is the value you want to send to that object and atribute mention before.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
// We are going to update the text to show "Hot!" when the variable is greater than 99, and show "Normal" when variable is below 100.
if(variable1 > 99){ // If the variable is greater than 99...
Serial.print("t0.txt="); // This is sent to the nextion display to set what object name (before the dot) and what atribute (after the dot) are you going to change.
Serial.print("\""); // Since we are sending text we need to send double quotes before and after the actual text.
Serial.print("Hot!"); // This is the text we want to send to that object and atribute mention before.
Serial.print("\""); // Since we are sending text we need to send double quotes before and after the actual text.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
}else{ // Since condition was false, do the following:
Serial.print("t0.txt="); // This is sent to the nextion display to set what object name (before the dot) and what atribute (after the dot) are you going to change.
Serial.print("\""); // Since we are sending text we need to send double quotes before and after the actual text.
Serial.print("Normal"); // This is the text we want to send to that object and atribute mention before.
Serial.print("\""); // Since we are sending text we need to send double quotes before and after the actual text.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
}
// We are going to hide the progress bar if the variable is greater than 119:
if(variable1 > 119){ // If the variable is greater than 119...
Serial.print("vis j0,0"); // This is to hide or show an object. The name of the object comes before the comma, and after the comma goes a 0 to hide or 1 to show.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
}else{ // Since condition was false, do the following:
Serial.print("vis j0,1"); // This is to hide or show an object. The name of the object comes before the comma, and after the comma goes a 0 to hide or 1 to show. Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
}
// We are going to change the color of the progress bar to red if the variable is greater than 49, and change to green if is below 50:
if(variable1 > 49){ // If the variable is greater than 49...
Serial.print("j0.pco=63488"); // Change color of the progress bar to red.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
}else{ // Since condition was false, do the following:
Serial.print("j0.pco=1024"); // Change color of the progress bar to green.
Serial.write(0xff); // We always have to send this three lines after each command sent to the nextion display.
Serial.write(0xff);
Serial.write(0xff);
}
} // End of loop
| [
"vietnam9094@gmail.com"
] | vietnam9094@gmail.com |
855b3d93ec9a971f01e08752668b45f9965b04c8 | 039ce45435f59e6e2301d4012facf279a5fbf1d5 | /Wurd/StudentUndo.cpp | 64eaf83ecec0eec2d8495eccbe62295ec145b1f5 | [] | no_license | justinHe123/Wurd | 8093fd10bfee1e1148f8b6e5d493f1ba8824b6b6 | 557242084f38d40bcd5c23ac901f787d14b92bc9 | refs/heads/master | 2023-03-22T22:07:27.300630 | 2021-03-12T03:53:51 | 2021-03-12T03:53:51 | 345,287,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,010 | cpp | #include "StudentUndo.h"
#include <cctype>
Undo* createUndo()
{
return new StudentUndo;
}
void StudentUndo::submit(const Action action, int row, int col, char ch) {
// Stack is empty, nothing to batch
if (m_actions.empty()) {
Item item(action, row, col, ch);
m_actions.push(item);
}
else {
Item prev = m_actions.top();
// Check if curr delete, prev del (previous delete was the same position)
if (action == Action::DELETE && prev.action == Action::DELETE && prev.row == row && prev.col == col) {
m_actions.top().text += ch;
}
// Check if curr delete, prev backspace (previous delete was same row, col + 1)
else if (action == Action::DELETE && prev.action == Action::DELETE && prev.row == row && prev.col == col + 1) {
m_actions.top().text = ch + prev.text;
m_actions.top().col = col;
}
// Check if curr insert, prev insert (previous insert was same row, col - 1)
else if (action == Action::INSERT && prev.action == Action::INSERT && prev.row == row && prev.col == col - 1) {
m_actions.top().text += ch;
m_actions.top().col = col;
}
// Not a batchable operation
else {
Item item(action, row, col, ch);
m_actions.push(item);
}
}
}
StudentUndo::Action StudentUndo::get(int &row, int &col, int& count, std::string& text) {
if (m_actions.empty()) return Action::ERROR; // TODO
Item item = m_actions.top();
m_actions.pop();
row = item.row;
col = item.col;
count = 1;
text = "";
Action action = item.action;
// send the opposite action back
switch (action) {
case Action::INSERT:
count = item.text.size();
col -= count; // decrement col by count to get to start of where to delete
return Action::DELETE;
break;
case Action::SPLIT:
return Action::JOIN;
break;
case Action::DELETE:
text = item.text;
return Action::INSERT;
break;
case Action::JOIN:
return Action::SPLIT;
break;
default:
return Action::ERROR;
break;
}
}
void StudentUndo::clear() {
while (!m_actions.empty()) m_actions.pop(); // clear the stack
}
| [
"justinme100@gmail.com"
] | justinme100@gmail.com |
2cd3c479a8a2099c41517a52bcfaa93f70dd536d | 52c3095196f510f5a90f9187785425cec7fdc202 | /JMath/Matrix.h | d0fbcc94d36391f8f1af9f9c31c6dcd4af910d1e | [] | no_license | Yaboi-Gengarboi/Misc | f06fb5b2e337358e1e791d7d9c65ca58970d404a | 01c0e508d15aef7b7beb686c9d2f163f67c35744 | refs/heads/master | 2021-06-25T17:47:47.962223 | 2021-02-26T00:03:16 | 2021-02-26T00:03:16 | 207,950,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,398 | h | // Matrix.h
// Justyn Durnford
// Created on 2020-08-30
// Last updated on 2020-08-30
// Header file for Matrix class
// This program is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What The Fuck You Want
// To Public License, Version 2, as published by Sam Hocevar. See
// http://www.wtfpl.net/ for more details.
#ifndef MATRIX_H
#define MATRIX_H
#include <string>
#include <vector>
class Matrix
{
std::vector<std::vector<double>> _matrix;
// Automatic Constructors
Matrix() = default;
Matrix(const Matrix & m) = default;
Matrix& operator = (const Matrix & m) = default;
Matrix(Matrix && m) = default;
Matrix& operator = (Matrix && m) = default;
// Manual Constructors
Matrix(const std::size_t& row, const std::size_t& col);
Matrix(const std::size_t& row, const std::size_t& col, double init_val);
// Destructor
~Matrix() = default;
// Returns _matrix[_row][_col]
double at(const std::size_t& row, const std::size_t& col) const;
// Sets _matrix[_row][_col] to val
void set(const std::size_t& row, const std::size_t& col, double val);
// Returns _matrix.size()
std::size_t rows() const;
// Returns _matrix[0].size()
std::size_t cols() const;
// Returns a std::string representation of the Matrix
std::string toString() const;
};
#endif // MATRIX_H | [
"jpdurnford@alaska.edu"
] | jpdurnford@alaska.edu |
44f81e806d9674bfb983e5c456c6c0e527ff2461 | 1bf8b46afad5402fe6fa74293b464e1ca5ee5fd7 | /SDK/wgt_OrbRingMeter_functions.cpp | 6022d2acf305973f40508efc062b6dc7b31d0531 | [] | no_license | LemonHaze420/ShenmueIIISDK | a4857eebefc7e66dba9f667efa43301c5efcdb62 | 47a433b5e94f171bbf5256e3ff4471dcec2c7d7e | refs/heads/master | 2021-06-30T17:33:06.034662 | 2021-01-19T20:33:33 | 2021-01-19T20:33:33 | 214,824,713 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,595 | cpp |
#include "../SDK.h"
// Name: Shenmue3SDK, Version: 1.4.1
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.SetForegroundVisible
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool Visible (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void Uwgt_OrbRingMeter_C::SetForegroundVisible(bool Visible)
{
static auto fn = UObject::FindObject<UFunction>("Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.SetForegroundVisible");
Uwgt_OrbRingMeter_C_SetForegroundVisible_Params params;
params.Visible = Visible;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.SetColorByEnum
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// TEnumAsByte<EHealthOrbColor> Color (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void Uwgt_OrbRingMeter_C::SetColorByEnum(TEnumAsByte<EHealthOrbColor> Color)
{
static auto fn = UObject::FindObject<UFunction>("Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.SetColorByEnum");
Uwgt_OrbRingMeter_C_SetColorByEnum_Params params;
params.Color = Color;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.SetBackgroundTexture
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UTexture2D* Background (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void Uwgt_OrbRingMeter_C::SetBackgroundTexture(class UTexture2D* Background)
{
static auto fn = UObject::FindObject<UFunction>("Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.SetBackgroundTexture");
Uwgt_OrbRingMeter_C_SetBackgroundTexture_Params params;
params.Background = Background;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.PreConstruct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// bool IsDesignTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void Uwgt_OrbRingMeter_C::PreConstruct(bool IsDesignTime)
{
static auto fn = UObject::FindObject<UFunction>("Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.PreConstruct");
Uwgt_OrbRingMeter_C_PreConstruct_Params params;
params.IsDesignTime = IsDesignTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.ExecuteUbergraph_wgt_OrbRingMeter
// ()
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void Uwgt_OrbRingMeter_C::ExecuteUbergraph_wgt_OrbRingMeter(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function wgt_OrbRingMeter.wgt_OrbRingMeter_C.ExecuteUbergraph_wgt_OrbRingMeter");
Uwgt_OrbRingMeter_C_ExecuteUbergraph_wgt_OrbRingMeter_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"35783139+LemonHaze420@users.noreply.github.com"
] | 35783139+LemonHaze420@users.noreply.github.com |
98b76eacba25a449fa13bfb8eb5ac1f59b3f7a6a | 290f6833a94095177b77dbe7dffd1d7c37014f11 | /dict/main.cpp | 3421c31af8cc0196b7888483ba3bafda2af4a953 | [] | no_license | Owlcuty/katya | 7a274fdedd236c8e78d2cdfb9f6c6651ed27997a | 64e3e1acd1a07f99724df70c53b6362c516db9e6 | refs/heads/master | 2023-02-15T01:08:30.240497 | 2021-01-06T11:56:55 | 2021-01-06T11:56:55 | 327,297,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | #include <iostream>
#include <fstream>
#include <cerrno>
#include <map>
#include <string.h>
#include "freq.h"
int main(int argc, char **argv)
{
char *text = getTextNew("text.txt");
if (text == NULL)
{
perror("fail: ");
return -1;
}
FrequencyMap_t freq = setFrequencyWords(text, strlen(text));
std::ofstream out("res.txt", std::ios::out);
for (auto it = freq.begin(); it != freq.end(); ++it)
{
out << "{" << it->first << "}: " << it->second << std::endl;
}
delete[] text;
return 0;
}
| [
"taje.chi.i@gmail.com"
] | taje.chi.i@gmail.com |
b50dd40e5ba50b869a5129ba13b9dba798b2c887 | 1c46aeebbc12cbb2865b9ebf7771ef3ffb11a0f9 | /Pointers of structures program 1.cpp | 92b8037f7b445794e55cb9463a5eb41fb1f6d429 | [] | no_license | gokulmuvvala/My-C-codes | 84ce1b67f9bb1c6b3f968eff3a12f209645425e0 | c9b79111b4925559616f2cb84a39ba28e4241a06 | refs/heads/main | 2023-04-03T06:33:39.761428 | 2021-04-03T18:55:00 | 2021-04-03T18:55:00 | 330,347,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | cpp | #include<stdio.h>
// Declaring structure
struct student
{
int rollnumber; // bt18ece584
char name[20]; // gokul
float percentage; // 96.2
};
int main()
{
struct student s1,*ptr; // calling structure and declaring the strcture pointer we can also declare stucture pointer in next line also like stuct student *ptr
ptr=&s1; // pointing pointer to address of s1
printf("Enter roll number\n");
scanf("%d",&s1.rollnumber);
printf("Enter your name:\n");
scanf("%s",s1.name); // as it is name no need of &
printf("Enter the percentage\n");
scanf("%f",&s1.percentage);
printf("\tRoll number=%d\n",ptr->rollnumber); // accessing members of structures using pointers
printf("\tName=%s\n",ptr->name);
printf("\tPercentage=%f\n",ptr->percentage);
}
| [
"gokulmuvvla@gmail.com"
] | gokulmuvvla@gmail.com |
3131e30b5f8aed72f3af3acc0db08e4fbfe631e5 | 5431502adf171a94aa16f742428bab8ad8340c75 | /esp8266-doorkeeper/src/filesys.cpp | f546046ee775a6ef2ee38b1a8a3ce0ee6eba6a19 | [] | no_license | mxyue/platformIO-demo | 4dcf1c89c7c06886ea763f870d68077a2164672f | 8dd4cf3f49a07487a2f7915ce42953378d3ee673 | refs/heads/master | 2022-11-19T11:31:19.386069 | 2020-07-15T06:36:27 | 2020-07-15T06:36:27 | 279,757,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | cpp | #include <FS.h>
#include "filesys.h"
String nullStr = "";
// 获取文件内容
String Filesys::GetContent(char filepath[]){
bool exist = SPIFFS.exists(filepath);
if (!exist) {
Serial.print(filepath);
Serial.println(" --- file not present");
return nullStr;
}
File f = SPIFFS.open(filepath, "r");
if (!f) {
Serial.printf("%s file open failed \n", filepath);
return nullStr;
}
String content = f.readString();
f.close();
Serial.printf("[%s]-->size(%d)\n", filepath, f.size());
return content;
}
// 设置文件内容
void Filesys::SetContent(char filepath[], String content){
File f = SPIFFS.open(filepath, "w");
f.print(content);
f.close();
}
void Filesys::Setup(){
bool fsok = SPIFFS.begin();
if (fsok) {
Serial.println("FS ok");
}
}
| [
"basicbox@126.com"
] | basicbox@126.com |
3bbcc3c587315d5247e859accecd9c9607d96a72 | 95f654c92b297e8d4a6e9026e44d6c21bc60b1d6 | /DSBoard.cpp | 50716e5b7f2015d5aff4ee873a5628b2ce1b1c23 | [] | no_license | mjkreul/DoubleShutter | 3eeca095ada82718fa8593c3b46bde73d6f75501 | a02f9a54a898e36c2495f2bb5adfa27ed95d4fce | refs/heads/main | 2023-03-07T21:30:09.742106 | 2021-02-16T18:09:04 | 2021-02-16T18:09:04 | 321,552,950 | 1 | 0 | null | 2021-02-16T18:09:05 | 2020-12-15T04:31:01 | C++ | UTF-8 | C++ | false | false | 5,378 | cpp | //
// Created by Matt Kreul on 12/14/20.
//
#include "DSBoard.h"
using namespace std;
/**
* This initializes the vectors containing both of the tiles
*/
DSBoard::DSBoard() {
for(int i = 0; i < 9; i++){
front_tile.push_back(i + 1);
back_tile.push_back(9 - i);
}
}
/**
* This is the main function for each turn. After the dice are rolled, this can be played. The inputs are for which
* tile parameter to hit and which number for each. As are the rules for the standard game, the back tiles cannot be
* knocked down until the front tile at that specific index is knocked down. Attempting to doing so will return from
* the function early with a false boolean.
*
* The checks for a valid move set is in the private helper method "checkValidMove".
*
* @param choice
* the choice of front or back tile
* @param tile
* the tile number to knock over
* @return
* true or false if a valid move set was input
*/
bool DSBoard::hitTile(const vector<tile>& choice, const vector<int>& tile) {
return checkValidMove(choice, tile);
}
/**
* This is the valid move checker. It copies over the current board and then simulates the move set entered by
* the user. If the simulated game is invalid, then it will return false. If it runs through the game without any
* issues, then it will copy the simulated board to the instance variables and return true.
*
* @param choice
* @param tile
* @return
*/
bool DSBoard::checkValidMove(const vector<tile> & choice, const vector<int> & tile) {
//TODO there has to be an easier method
vector<int> tempFront(this->front_tile.size());
vector<int> tempBack(this->back_tile.size());
for(int i = 0; i < this->front_tile.size(); i ++){
tempFront[i] = this->front_tile[i];
tempBack[i] = this->back_tile[i];
}
int sum = 0;
for(int i : tile){
sum += i;
}
if(sum != (die1 + die2)){
return false;
}
else{
for(int i = 0; i < tile.size(); i++){
tile_e tempChoice = choice[i];//for some reason this won't let me do just "tile" idk
int tempNum = tile[i];
if(tempChoice == back){
if(tempFront[9 - tempNum] == 0 && tempBack[9 - tempNum] != 0) tempBack[9 - tempNum] = 0;
else return false;
}
else{
if(tempFront[tempNum - 1] != 0) tempFront[tempNum - 1] = 0;
else return false;
}
}
}
//TODO change this to pointers so you can just make the instance variables equal to the temp board values
for(int i = 0; i < this->front_tile.size(); i ++){
this->front_tile[i] = tempFront[i];
this->back_tile[i] = tempBack[i];
}
return true;
}
/**
* This rolls the dice. This function must be run for each turn.
*/
void DSBoard::roll() {
die1 = this->r()%6 + 1;
die2 = this->r()%6 + 1;
//TODO check for if any valid move can be played. If not game is finished and the game is lost.
//TODO make this so that if the total number of tiles are less than 6 then only one die can be cast
//TODO make this so that there is score being kept
}
/**
* Returns whether the game can still be played or not.
*
* @return
*/
bool DSBoard::gameFinished() {
return this->gameStatus;
}
/**
*
*/
void DSBoard::printBoard() {
cout << "\t=== Game Board ===" << endl;
cout << "Tiles: " << endl;
printTiles();
cout << "Die: " << endl;
printDie();
}
/**
*
*/
void DSBoard::printTiles() {
//TODO change this
cout << " ";
for(int i : back_tile){
if(i != 0 ) cout << "|" << i << "| ";
else cout << "|X| ";
}
cout << endl;
for(int i : front_tile){
if(i != 0 ) cout << "|" << i << "| ";
else cout << "|X| ";
}
cout << endl;
}
/**
* This function prints the die to the console
*/
void DSBoard::printDie() {
//TODO this can be made more concise
string line11, line21, line31, line12, line22, line32;
if(die1%2 == 1){
line21 = "| o |";
}
if(die1 == 1){
line11 = "| |";
line31 = "| |";
}
else if (die1 > 1 && die1 < 4){
line11 = "| o |";
line31 = "| o |";
if(die1 == 2){
line21 = "| |";
}
}
else if(die1 > 3){
line11 = "| o o |";
line31 = "| o o |";
if(die1%2 == 0){
if(die1 == 4){
line21 = "| |";
}
else{
line21 = "| o o |";
}
}
}
if(die2%2 == 1){
line22 = "| o |";
}
if(die2 == 1){
line12 = "| |";
line32 = "| |";
}
else if (die2 > 1 && die2 < 4){
line12 = "| o |";
line32 = "| o |";
if(die2 == 2){
line22 = "| |";
}
}
else if(die2 > 3){
line12 = "| o o |";
line32 = "| o o |";
if(die2%2 == 0){
if(die2 == 4){
line22 = "| |";
}
else{
line22 = "| o o |";
}
}
}
cout << line11 << " " << line12 << endl;
cout << line21 << " " << line22 << endl;
cout << line31 << " " << line32 << endl;
}
DSBoard::~DSBoard() {
// delete front_tile;
}
/**
*
*
* @return
*/
bool DSBoard::gameWon() {
for(int i = 0; i < front_tile.size(); i++){
int temp1 = front_tile[i];
int temp2 = back_tile[i];
if(temp1 != 0 || temp2 != 0) return false;
}
return true;
}
const DSBoard &DSBoard::operator=(const DSBoard & rhs) {
if(this != &rhs){
delete this;
this->die1 = rhs.die1;
this->die2 = rhs.die2;
this->front_tile = rhs.front_tile;
this->back_tile = rhs.back_tile;
this->gameStatus = rhs.gameStatus;
this->winStatus = rhs.winStatus;
}
return *this;
}
void DSBoard::printDieTS() {
cout << "Die1: " << this->die1 << " Die2: " << this->die2 << endl;
}
| [
"mjkreul@iastate.edu"
] | mjkreul@iastate.edu |
45193a7d4288c2b8f9520de60f9468ecac8dc9ea | ac71111a4a9657fc60b2151ac7ce1933a7374637 | /src/wt/TPSCamController.cpp | d10221279657cc16004a69599dc39b5aaa027fba | [] | no_license | spiricn/Wt | 931a49140761b510a86bea4f1c53f8bd535aa35f | e77589d766d54ff46617b0f117acd2372f99ff66 | refs/heads/master | 2016-09-06T04:06:17.206685 | 2014-04-18T13:57:43 | 2014-04-18T13:57:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,890 | cpp | #include "wt/stdafx.h"
#include "wt/TPSCamController.h"
#define TD_TRACE_TAG "TPSCamController"
namespace wt
{
namespace math
{
TPSCameraControler::TPSCameraControler(Camera* camera, const ATransformable* target) : mCamera(camera),
mMouseSensitivity(0.001f), mDistance(3.0f),
mTheta(0.0f), mRho(PI/2.0f), mTarget(target){
}
void TPSCameraControler::setCamera(math::Camera* camera){
mCamera = camera;
}
void TPSCameraControler::setTarget(const ATransformable* target){
mTarget = target;
//updateCam();
}
void TPSCameraControler::zoomIn(float dt){
if(dt==0.0f){
return;
}
mDistance -= 3.0f*dt;
if(mDistance < 0.0f){
mDistance=0.01f;
}
//updateCam();
}
void TPSCameraControler::handle(float dt, AGameInput* input){
lookHorizontal(input->getMouseDeltaX());
lookVertical(input->getMouseDeltaY());
if(input->isKeyDown(KEY_u)){
zoomIn(dt);
}
else if(input->isKeyDown(KEY_i)){
zoomOut(dt);
}
if(input->isKeyDown(KEY_a)){
lookHorizontal(dt*-2000);
}
else if(input->isKeyDown(KEY_d)){
lookHorizontal(dt*2000);
}
if(input->isKeyDown(KEY_c)){
lookVertical(dt*-1000);
}
else if(input->isKeyDown(KEY_SPACE)){
lookVertical(dt*1000);
}
updateCam();
}
void TPSCameraControler::zoomOut(float dt){
if(dt==0.0f){
return;
}
mDistance += 3.0f*dt;
//updateCam();
}
void TPSCameraControler::lookHorizontal(float dx){
if(dx==0.0f){
return;
}
mTheta = fmod((mTheta + dx*mMouseSensitivity), 2*PI);
//updateCam();
}
void TPSCameraControler::lookVertical(float dy){
if(dy==0.0f){
return;
}
mRho += -dy*mMouseSensitivity;
if(mRho < 0.01f){
mRho = 0.01f;
}
else if(mRho >= math::PI){
mRho = math::PI-0.01f;
}
//updateCam();
}
void TPSCameraControler::updateCam(){
glm::vec3 pos;
if(mTarget != NULL){
mTarget->getTranslation(pos);
pos.y += 5;
}
mCamera->orbit(mDistance, mTheta, mRho, pos);
}
} // </math>
} // </wt>
| [
"nikola.spiric.ns@gmail.com"
] | nikola.spiric.ns@gmail.com |
1df5cea4469c114d04b2e7c7459412020525263c | b8d457b9ce160911e6eba460e69c72d9d31ed260 | /ArxRle/Filer/ArxRleDwgFiler.h | 246e0f652801c0b3e76addc29c8ed41d9403b6de | [] | no_license | inbei/AutoDesk-ArxRle-2018 | b91659a34a73727987513356bfcd1bff9fe09ee3 | 3c8d4a34f586467685c0f9bce7c3693233e43308 | refs/heads/master | 2023-01-19T08:27:38.231533 | 2020-11-25T00:52:13 | 2020-11-25T00:52:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,843 | h | //
//////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
//
#ifndef ARXRLEDWGFILER_H
#define ARXRLEDWGFILER_H
/****************************************************************************
**
** CLASS ArxRleDwgFiler:
**
** **jma
**
*************************************/
#include "dbfiler.h"
class ArxRleDwgFiler: public AcDbDwgFiler {
public:
ACRX_DECLARE_MEMBERS(ArxRleDwgFiler);
ArxRleDwgFiler();
virtual ~ArxRleDwgFiler();
virtual Acad::ErrorStatus filerStatus() const;
virtual AcDb::FilerType filerType() const;
virtual void setFilerStatus(Acad::ErrorStatus);
virtual void resetFilerStatus();
virtual Acad::ErrorStatus readHardOwnershipId(AcDbHardOwnershipId*);
virtual Acad::ErrorStatus writeHardOwnershipId(const AcDbHardOwnershipId&);
virtual Acad::ErrorStatus readSoftOwnershipId(AcDbSoftOwnershipId*);
virtual Acad::ErrorStatus writeSoftOwnershipId(const AcDbSoftOwnershipId&);
virtual Acad::ErrorStatus readHardPointerId(AcDbHardPointerId*) ;
virtual Acad::ErrorStatus writeHardPointerId(const AcDbHardPointerId&);
virtual Acad::ErrorStatus readSoftPointerId(AcDbSoftPointerId*) ;
virtual Acad::ErrorStatus writeSoftPointerId(const AcDbSoftPointerId&);
virtual Acad::ErrorStatus readString(ACHAR **);
virtual Acad::ErrorStatus writeString(const ACHAR *);
virtual Acad::ErrorStatus readString(AcString &);
virtual Acad::ErrorStatus writeString(const AcString &);
virtual Acad::ErrorStatus readBChunk(ads_binary*);
virtual Acad::ErrorStatus writeBChunk(const ads_binary&);
virtual Acad::ErrorStatus readAcDbHandle(AcDbHandle*);
virtual Acad::ErrorStatus writeAcDbHandle(const AcDbHandle&);
virtual Acad::ErrorStatus readInt64(Adesk::Int64*);
virtual Acad::ErrorStatus writeInt64(Adesk::Int64);
virtual Acad::ErrorStatus readInt32(Adesk::Int32*);
virtual Acad::ErrorStatus writeInt32(Adesk::Int32);
virtual Acad::ErrorStatus readInt16(Adesk::Int16*);
virtual Acad::ErrorStatus writeInt16(Adesk::Int16);
virtual Acad::ErrorStatus readInt8(Adesk::Int8 *);
virtual Acad::ErrorStatus writeInt8(Adesk::Int8);
virtual Acad::ErrorStatus readUInt64(Adesk::UInt64*);
virtual Acad::ErrorStatus writeUInt64(Adesk::UInt64);
virtual Acad::ErrorStatus readUInt32(Adesk::UInt32*);
virtual Acad::ErrorStatus writeUInt32(Adesk::UInt32);
virtual Acad::ErrorStatus readUInt16(Adesk::UInt16*);
virtual Acad::ErrorStatus writeUInt16(Adesk::UInt16);
virtual Acad::ErrorStatus readUInt8(Adesk::UInt8*);
virtual Acad::ErrorStatus writeUInt8(Adesk::UInt8);
virtual Acad::ErrorStatus readBoolean(Adesk::Boolean*);
virtual Acad::ErrorStatus writeBoolean(Adesk::Boolean);
virtual Acad::ErrorStatus readBool(bool*);
virtual Acad::ErrorStatus writeBool(bool);
virtual Acad::ErrorStatus readDouble(double*);
virtual Acad::ErrorStatus writeDouble(double);
virtual Acad::ErrorStatus readPoint2d(AcGePoint2d*);
virtual Acad::ErrorStatus writePoint2d(const AcGePoint2d&);
virtual Acad::ErrorStatus readPoint3d(AcGePoint3d*);
virtual Acad::ErrorStatus writePoint3d(const AcGePoint3d&);
virtual Acad::ErrorStatus readVector2d(AcGeVector2d*);
virtual Acad::ErrorStatus writeVector2d(const AcGeVector2d&);
virtual Acad::ErrorStatus readVector3d(AcGeVector3d*);
virtual Acad::ErrorStatus writeVector3d(const AcGeVector3d&);
virtual Acad::ErrorStatus readScale3d(AcGeScale3d*);
virtual Acad::ErrorStatus writeScale3d(const AcGeScale3d&);
virtual Acad::ErrorStatus readBytes(void*, Adesk::UIntPtr);
virtual Acad::ErrorStatus writeBytes(const void*, Adesk::UIntPtr);
virtual Acad::ErrorStatus readAddress(void**);
virtual Acad::ErrorStatus writeAddress(const void*);
virtual Acad::ErrorStatus seek(Adesk::Int64 nOffset, int nMethod);
virtual Adesk::Int64 tell() const;
void setFilerType(AcDb::FilerType newType) { m_filerType = newType; }
private:
Acad::ErrorStatus m_stat;
CString m_str;
AcDb::FilerType m_filerType;
// helper functions
void printIt(LPCTSTR labelStr);
void objIdToStr(const AcDbObjectId& objId, CString& str);
};
#endif // ARXRLEDWGFILER_H
| [
"fb19801101@126.com"
] | fb19801101@126.com |
a3556f42cc3395e73cfd3a5d137f477518a68eed | ec68c973b7cd3821dd70ed6787497a0f808e18e1 | /Cpp/SDK/Mod_SporeShot_parameters.h | 17dde3ce8e153ea012a80398335f4fb16ac5e89e | [] | no_license | Hengle/zRemnant-SDK | 05be5801567a8cf67e8b03c50010f590d4e2599d | be2d99fb54f44a09ca52abc5f898e665964a24cb | refs/heads/main | 2023-07-16T04:44:43.113226 | 2021-08-27T14:26:40 | 2021-08-27T14:26:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | h | #pragma once
// Name: Remnant, Version: 1.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function Mod_SporeShot.Mod_SporeShot_C.GetSporeCloudDuration
struct AMod_SporeShot_C_GetSporeCloudDuration_Params
{
};
// Function Mod_SporeShot.Mod_SporeShot_C.GetDotDamage
struct AMod_SporeShot_C_GetDotDamage_Params
{
};
// Function Mod_SporeShot.Mod_SporeShot_C.GetDamageScalar
struct AMod_SporeShot_C_GetDamageScalar_Params
{
};
// Function Mod_SporeShot.Mod_SporeShot_C.ModifyInspectInfo
struct AMod_SporeShot_C_ModifyInspectInfo_Params
{
};
// Function Mod_SporeShot.Mod_SporeShot_C.ModifyDamage
struct AMod_SporeShot_C_ModifyDamage_Params
{
};
// Function Mod_SporeShot.Mod_SporeShot_C.OnFire
struct AMod_SporeShot_C_OnFire_Params
{
};
// Function Mod_SporeShot.Mod_SporeShot_C.ExecuteUbergraph_Mod_SporeShot
struct AMod_SporeShot_C_ExecuteUbergraph_Mod_SporeShot_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
5a3a20a0402fc0980bc59bd9896359eaa5c0a2b9 | e2171ad810384af43f7b5a88bfb6bdfd2ee20bea | /Technology-Challenge/【董章晔队】AgoraWithWaterMaskAndroid/AgoraWithWaterMaskAndroid/agora-watermask/src/main/cpp/plugin_source_code/rapidjson/prettywriter.h | b4a57f0fd1a65a90e8c4196f07c0c4e83b68bdcc | [
"MIT"
] | permissive | AgoraIO-Community/RTE-2021-Innovation-Challenge | 249965c82697d1b248f39fbf2df6a3cbd6de6c78 | 558c96cf0f029fb02188ca83f60920c89afd210f | refs/heads/master | 2022-07-25T12:27:17.937730 | 2022-01-21T12:58:11 | 2022-01-21T12:58:11 | 355,093,340 | 36 | 128 | null | 2021-11-07T17:13:28 | 2021-04-06T07:12:11 | C++ | UTF-8 | C++ | false | false | 9,856 | h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#ifndef RAPIDJSON_PRETTYWRITER_H_
#define RAPIDJSON_PRETTYWRITER_H_
#include "writer.h"
#ifdef __GNUC__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Combination of PrettyWriter format flags.
/*! \see PrettyWriter::SetFormatOptions
*/
enum PrettyFormatOptions {
kFormatDefault = 0, //!< Default pretty formatting.
kFormatSingleLineArray = 1 //!< Format arrays on a single line.
};
//! Writer with indentation and spacing.
/*!
\tparam OutputStream Type of ouptut os.
\tparam SourceEncoding Encoding of source string.
\tparam TargetEncoding Encoding of output stream.
\tparam StackAllocator Type of allocator for allocating memory of stack.
*/
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> {
public:
typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator> Base;
typedef typename Base::Ch Ch;
//! Constructor
/*! \param os Output stream.
\param allocator User supplied allocator. If it is null, it will create a private one.
\param levelDepth Initial capacity of stack.
*/
explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {}
explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {}
//! Set custom indentation.
/*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r').
\param indentCharCount Number of indent characters for each indentation level.
\note The default indentation is 4 spaces.
*/
PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) {
RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r');
indentChar_ = indentChar;
indentCharCount_ = indentCharCount;
return *this;
}
//! Set pretty writer formatting options.
/*! \param options Formatting options.
*/
PrettyWriter& SetFormatOptions(PrettyFormatOptions options) {
formatOptions_ = options;
return *this;
}
/*! @name Implementation of Handler
\see Handler
*/
//@{
bool Null() { PrettyPrefix(kNullType); return Base::WriteNull(); }
bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::WriteBool(b); }
bool Int(int i) { PrettyPrefix(kNumberType); return Base::WriteInt(i); }
bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::WriteUint(u); }
bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::WriteInt64(i64); }
bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::WriteUint64(u64); }
bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); }
bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
(void)copy;
PrettyPrefix(kNumberType);
return Base::WriteString(str, length);
}
bool String(const Ch* str, SizeType length, bool copy = false) {
(void)copy;
PrettyPrefix(kStringType);
return Base::WriteString(str, length);
}
#if RAPIDJSON_HAS_STDSTRING
bool String(const std::basic_string<Ch>& str) {
return String(str.data(), SizeType(str.size()));
}
#endif
bool StartObject() {
PrettyPrefix(kObjectType);
new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(false);
return Base::WriteStartObject();
}
bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
#if RAPIDJSON_HAS_STDSTRING
bool Key(const std::basic_string<Ch>& str) {
return Key(str.data(), SizeType(str.size()));
}
#endif
bool EndObject(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray);
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
if (!empty) {
Base::os_->Put('\n');
WriteIndent();
}
bool ret = Base::WriteEndObject();
(void)ret;
RAPIDJSON_ASSERT(ret == true);
if (Base::level_stack_.Empty()) // end of json text
Base::os_->Flush();
return true;
}
bool StartArray() {
PrettyPrefix(kArrayType);
new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(true);
return Base::WriteStartArray();
}
bool EndArray(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
RAPIDJSON_ASSERT(Base::level_stack_.template Top<typename Base::Level>()->inArray);
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
if (!empty && !(formatOptions_ & kFormatSingleLineArray)) {
Base::os_->Put('\n');
WriteIndent();
}
bool ret = Base::WriteEndArray();
(void)ret;
RAPIDJSON_ASSERT(ret == true);
if (Base::level_stack_.Empty()) // end of json text
Base::os_->Flush();
return true;
}
//@}
/*! @name Convenience extensions */
//@{
//! Simpler but slower overload.
bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
//@}
//! Write a raw JSON value.
/*!
For user to write a stringified JSON as a value.
\param json A well-formed JSON value. It should not contain null character within [0, length - 1] range.
\param length Length of the json.
\param type Type of the root of json.
\note When using PrettyWriter::RawValue(), the result json may not be indented correctly.
*/
bool RawValue(const Ch* json, size_t length, Type type) { PrettyPrefix(type); return Base::WriteRawValue(json, length); }
protected:
void PrettyPrefix(Type type) {
(void)type;
if (Base::level_stack_.GetSize() != 0) { // this value is not at root
typename Base::Level* level = Base::level_stack_.template Top<typename Base::Level>();
if (level->inArray) {
if (level->valueCount > 0) {
Base::os_->Put(','); // add comma if it is not the first element in array
if (formatOptions_ & kFormatSingleLineArray)
Base::os_->Put(' ');
}
if (!(formatOptions_ & kFormatSingleLineArray)) {
Base::os_->Put('\n');
WriteIndent();
}
}
else { // in object
if (level->valueCount > 0) {
if (level->valueCount % 2 == 0) {
Base::os_->Put(',');
Base::os_->Put('\n');
}
else {
Base::os_->Put(':');
Base::os_->Put(' ');
}
}
else
Base::os_->Put('\n');
if (level->valueCount % 2 == 0)
WriteIndent();
}
if (!level->inArray && level->valueCount % 2 == 0)
RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
level->valueCount++;
}
else {
RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root.
Base::hasRoot_ = true;
}
}
void WriteIndent() {
size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
PutN(*Base::os_, static_cast<typename TargetEncoding::Ch>(indentChar_), count);
}
Ch indentChar_;
unsigned indentCharCount_;
PrettyFormatOptions formatOptions_;
private:
// Prohibit copy constructor & assignment operator.
PrettyWriter(const PrettyWriter&);
PrettyWriter& operator=(const PrettyWriter&);
};
RAPIDJSON_NAMESPACE_END
#ifdef __GNUC__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_RAPIDJSON_H_
| [
"dongzy08@163.com"
] | dongzy08@163.com |
56f2b8a2d3d20763559a628d7f0a24425ae23b3b | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/admin/hmonitor/snapin/actioncmdlinepage.cpp | df0d63f12ef260867cedb6d14c78aec7177f3621 | [] | 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 | 9,164 | cpp | // ActionCmdLinePage.cpp : implementation file
//
// 03/05/00 v-marfin bug 59643 : Make this the default starting page.
// 03/28/00 v-marfin 61030 Change Browse for file dialog to fix default extension
#include "stdafx.h"
#include "snapin.h"
#include "ActionCmdLinePage.h"
#include "Action.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CActionCmdLinePage property page
IMPLEMENT_DYNCREATE(CActionCmdLinePage, CHMPropertyPage)
CActionCmdLinePage::CActionCmdLinePage() : CHMPropertyPage(CActionCmdLinePage::IDD)
{
//{{AFX_DATA_INIT(CActionCmdLinePage)
m_sCommandLine = _T("");
m_sFileName = _T("");
m_iTimeout = 0;
m_sWorkingDirectory = _T("");
m_bWindowed = FALSE;
//}}AFX_DATA_INIT
m_sHelpTopic = _T("HMon21.chm::/dcommact.htm");
}
CActionCmdLinePage::~CActionCmdLinePage()
{
}
void CActionCmdLinePage::DoDataExchange(CDataExchange* pDX)
{
CHMPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CActionCmdLinePage)
DDX_Control(pDX, IDC_EDIT_COMMAND_LINE, m_CmdLineWnd);
DDX_Control(pDX, IDC_COMBO_TIMEOUT_UNITS, m_TimeoutUnits);
DDX_Text(pDX, IDC_EDIT_COMMAND_LINE, m_sCommandLine);
DDV_MaxChars(pDX, m_sCommandLine, 1024);
DDX_Text(pDX, IDC_EDIT_FILE_NAME, m_sFileName);
DDV_MaxChars(pDX, m_sFileName, 1024);
DDX_Text(pDX, IDC_EDIT_PROCESS_TIMEOUT, m_iTimeout);
DDX_Text(pDX, IDC_EDIT_WORKING_DIR, m_sWorkingDirectory);
DDX_Check(pDX, IDC_CHECK_WINDOWED, m_bWindowed);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CActionCmdLinePage, CHMPropertyPage)
//{{AFX_MSG_MAP(CActionCmdLinePage)
ON_WM_DESTROY()
ON_BN_CLICKED(IDC_BUTTON_ADVANCED, OnButtonAdvanced)
ON_BN_CLICKED(IDC_BUTTON_BROWSE_DIRECTORY, OnButtonBrowseDirectory)
ON_BN_CLICKED(IDC_BUTTON_BROWSE_FILE, OnButtonBrowseFile)
ON_EN_CHANGE(IDC_EDIT_COMMAND_LINE, OnChangeEditCommandLine)
ON_EN_CHANGE(IDC_EDIT_FILE_NAME, OnChangeEditFileName)
ON_EN_CHANGE(IDC_EDIT_PROCESS_TIMEOUT, OnChangeEditProcessTimeout)
ON_EN_CHANGE(IDC_EDIT_WORKING_DIR, OnChangeEditWorkingDir)
ON_CBN_SELENDOK(IDC_COMBO_TIMEOUT_UNITS, OnSelendokComboTimeoutUnits)
ON_BN_CLICKED(IDC_BUTTON_INSERTION, OnButtonInsertion)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CActionCmdLinePage message handlers
BOOL CActionCmdLinePage::OnInitDialog()
{
// v-marfin : bug 59643 : This will be the default starting page for the property
// sheet so call CnxPropertyPageCreate() to unmarshal the
// connection for this thread. This function must be called
// by the first page of the property sheet. It used to
// be called by the "General" page and its call still remains
// there as well in case the general page is loaded by a
// different code path that does not also load this page.
// The CnxPropertyPageCreate function has been safeguarded
// to simply return if the required call has already been made.
// CnxPropertyPageDestory() must be called from this page's
// OnDestroy function.
// unmarshal connmgr
CnxPropertyPageCreate();
CHMPropertyPage::OnInitDialog();
if( ! m_InsertionMenu.Create(&m_CmdLineWnd,GetObjectPtr(),false) )
{
GetDlgItem(IDC_BUTTON_INSERTION)->EnableWindow(FALSE);
}
CWbemClassObject* pConsumerObject = ((CAction*)GetObjectPtr())->GetConsumerClassObject();
if( pConsumerObject )
{
pConsumerObject->GetProperty(_T("CommandLineTemplate"),m_sCommandLine);
pConsumerObject->GetProperty(_T("ExecutablePath"),m_sFileName);
if( ! m_sFileName.CompareNoCase(_T("NOOP")) )
{
m_sFileName.Empty();
}
pConsumerObject->GetProperty(_T("KillTimeout"),m_iTimeout);
m_TimeoutUnits.SetCurSel(0);
pConsumerObject->GetProperty(_T("WorkingDirectory"),m_sWorkingDirectory);
int iShowWindow = SW_SHOW;
pConsumerObject->GetProperty(_T("ShowWindowCommand"),iShowWindow);
m_bWindowed = iShowWindow == 1;
delete pConsumerObject;
}
SendDlgItemMessage(IDC_SPIN2,UDM_SETRANGE32,0,99999);
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL CActionCmdLinePage::OnApply()
{
if( ! CHMPropertyPage::OnApply() )
{
return FALSE;
}
UpdateData();
int iOldTimeout = m_iTimeout;
switch( m_TimeoutUnits.GetCurSel() )
{
case 1: // minutes
{
m_iTimeout *= 60;
}
break;
case 2: // hours
{
m_iTimeout *= 360;
}
break;
}
CWbemClassObject* pConsumerObject = ((CAction*)GetObjectPtr())->GetConsumerClassObject();
if( pConsumerObject )
{
pConsumerObject->SetProperty(_T("CommandLineTemplate"),m_sCommandLine);
pConsumerObject->SetProperty(_T("ExecutablePath"),m_sFileName);
pConsumerObject->SetProperty(_T("KillTimeout"),m_iTimeout);
pConsumerObject->SetProperty(_T("WorkingDirectory"),m_sWorkingDirectory);
pConsumerObject->SetProperty(_T("RunInteractively"),true);
pConsumerObject->SetProperty(_T("ShowWindowCommand"),m_bWindowed);
pConsumerObject->SaveAllProperties();
delete pConsumerObject;
}
m_iTimeout = iOldTimeout;
SetModified(FALSE);
return TRUE;
}
void CActionCmdLinePage::OnDestroy()
{
CHMPropertyPage::OnDestroy();
// v-marfin : bug 59643 : CnxPropertyPageDestory() must be called from this page's
// OnDestroy function.
CnxPropertyPageDestroy();
}
void CActionCmdLinePage::OnButtonAdvanced()
{
// TODO: Add your control notification handler code here
}
void CActionCmdLinePage::OnButtonBrowseDirectory()
{
UpdateData(TRUE);
LPMALLOC pMalloc;
if( ::SHGetMalloc(&pMalloc) == NOERROR )
{
BROWSEINFO bi;
TCHAR szBuffer[MAX_PATH];
LPITEMIDLIST pidlDesktop;
LPITEMIDLIST pidl;
if( ::SHGetSpecialFolderLocation(GetSafeHwnd(),CSIDL_DESKTOP,&pidlDesktop) != NOERROR )
return;
CString sResString;
sResString.LoadString(IDS_STRING_BROWSE_FOLDER);
bi.hwndOwner = GetSafeHwnd();
bi.pidlRoot = pidlDesktop;
bi.pszDisplayName = szBuffer;
bi.lpszTitle = LPCTSTR(sResString);
bi.ulFlags = BIF_RETURNONLYFSDIRS;
bi.lpfn = NULL;
bi.lParam = 0;
if( (pidl = ::SHBrowseForFolder(&bi)) != NULL )
{
if (SUCCEEDED(::SHGetPathFromIDList(pidl, szBuffer)))
{
m_sWorkingDirectory = szBuffer;
UpdateData(FALSE);
}
pMalloc->Free(pidl);
}
pMalloc->Free(pidlDesktop);
pMalloc->Release();
}
}
void CActionCmdLinePage::OnButtonBrowseFile()
{
UpdateData(TRUE);
CString sFilter;
CString sTitle;
sFilter.LoadString(IDS_STRING_FILTER);
sTitle.LoadString(IDS_STRING_BROWSE_FILE);
// v-marfin 61030 Change Browse for file dialog to fix default extension
// CFileDialog fdlg(TRUE,_T("*.*"),NULL,OFN_FILEMUSTEXIST|OFN_SHAREAWARE|OFN_HIDEREADONLY,sFilter);
CFileDialog fdlg(TRUE, // Is FILEOPEN dialog?
NULL, // default extension if no extension provided
NULL, // initial filename
OFN_FILEMUSTEXIST|OFN_SHAREAWARE|OFN_HIDEREADONLY, // flags
sFilter); // filter
fdlg.m_ofn.lpstrTitle = sTitle;
if( fdlg.DoModal() == IDOK )
{
m_sFileName = fdlg.GetPathName();
UpdateData(FALSE);
}
}
void CActionCmdLinePage::OnChangeEditCommandLine()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CHMPropertyPage::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
SetModified();
}
void CActionCmdLinePage::OnChangeEditFileName()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CHMPropertyPage::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
SetModified();
}
void CActionCmdLinePage::OnChangeEditProcessTimeout()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CHMPropertyPage::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
SetModified();
}
void CActionCmdLinePage::OnChangeEditWorkingDir()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CHMPropertyPage::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
SetModified();
}
void CActionCmdLinePage::OnSelendokComboTimeoutUnits()
{
SetModified();
}
void CActionCmdLinePage::OnButtonInsertion()
{
CPoint pt;
GetCursorPos(&pt);
m_InsertionMenu.DisplayMenu(pt);
UpdateData();
SetModified();
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
e003f2c44a8c56f1685a3633a5f914785973bc74 | 1b19b6455ac4d8fc47a118c718845e06a2191e73 | /include/produkti.h | 65ba1fcba4b77362ac8b62d5057972e5481fbe69 | [] | no_license | PonomarenkoDeniss/Hesburger | aacb8016e8a9c268c15941c861b55217b9d402f8 | 38f855867565d307de5de18509b8008fc5984ca2 | refs/heads/master | 2020-03-20T21:07:16.359231 | 2018-06-18T18:51:20 | 2018-06-18T18:51:20 | 137,724,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | h | #ifndef PRODUKTI_H
#define PRODUKTI_H
#include "Lietotajs.h"
class produkti:Lietotajs{
public:
produkti();
virtual ~produkti();
protected:
private:
};
#endif // PRODUKTI_H
| [
"62DDPonomarenko@rvt.lv"
] | 62DDPonomarenko@rvt.lv |
a56441c77228d567bb60d6681595c9cfaefaa940 | 02d7a9515f85095019ffdf764ccec3ee138dc4b2 | /ButtonCode/ButtonCode.ino | 01c1326323846c8066788bcebd2758acb62699c3 | [] | no_license | tnovak-olin/POE-Lab1 | a82e5937af76bcc9b6f6da8b303aa6495f2ec16d | 1e7c0bfb6b3e0f9dc8f65dfbbae406627871011d | refs/heads/master | 2020-07-14T22:19:13.387411 | 2019-09-06T15:24:04 | 2019-09-06T15:24:04 | 205,415,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,906 | ino | /*
Blink
Turns an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
the correct LED pin independent of which board is used.
If you want to know what pin the on-board LED is connected to on your Arduino
model, check the Technical Specs of your board at:
https://www.arduino.cc/en/Main/Products
modified 8 May 2014
by Scott Fitzgerald
modified 2 Sep 2016
by Arturo Guadalupi
modified 8 Sep 2016
by Colby Newman
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Blink
*/
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int ledState = 0;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 11-13 as outputs.
pinMode(13, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
// initalize pin 2 as an input from the button
pinMode(2, INPUT);
//start text ouput
Serial.begin(9600);
}
// the loop function runs over and over again forever
void loop() {
Serial.println("---------------------------------");
Serial.print("button: ");
Serial.println(buttonState);
Serial.print ("LED: ");
Serial.println(ledState);
//MARK: Sense
// read the state of the pushbutton value:
buttonState = digitalRead(2);
//MARK: Think
//Change state
switch (ledState) {
case 0 :
Serial.println("running case 0");
//all on
//turn on leds
digitalWrite(13, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
break;
case 1 :
Serial.println("running case 1");
//all off
//turn off leds
digitalWrite(13, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
break;
case 2 :
Serial.println("running case 2");
//all blinking
//leds on
digitalWrite(13, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
//wait
delay(1000);
//leds off
digitalWrite(13, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
//wait
delay(1000);
break;
default :
Serial.println("case 3 default");
//reset button state
ledState = 0;
break;
}
if (buttonState == HIGH) {
Serial.println("incremented");
ledState += 1;
}
/*digitalWrite(13, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);// turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);// turn the LED off by making the voltage LOW
delay(1000); */
}
| [
"tnovak@olin.edu"
] | tnovak@olin.edu |
3e843e9cf05f55d2501be4150cf5ea7109357f1f | 5968edb9f60f42689294b545dabd47204252ffd6 | /old/old/Action.h | bec29b10351eb71f9c13c8d15db5bd5573e1e4b0 | [] | no_license | Gownta/Hanabi | 2cb2c4b66c9e363f19e19a0cfc5e757d4832c5cc | 9b1af7e38effc969c4c0d6edced4231fd6e34624 | refs/heads/master | 2022-12-22T21:33:27.191551 | 2022-12-14T01:04:18 | 2022-12-14T01:04:18 | 48,763,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | h | #pragma once
#include <array>
#include <chrono>
#include <variant>
#include "Cards.h"
// Decisions are what players decide to do
// Actions are what ends up happening
struct PlayDecision {
int pos;
};
struct DiscardDecision {
int pos;
};
struct ColourHintDecision {
int player;
Colour colour;
};
struct ValueHintDecision {
int player;
Value value;
};
using Decision = std::variant<
PlayDecision,
DiscardDecision,
ColourHintDecision,
ValueHintDecision>;
struct PlayAction {
int actor;
int pos;
Card card;
};
struct DiscardAction {
int actor;
int pos;
Card card;
};
struct ColourHintAction {
int actor;
int hintee;
Colour colour;
std::array<bool, 4> positions;
};
struct ValueHintAction {
int actor;
int hintee;
Value value;
std::array<bool, 4> positions;
};
using Action =
std::variant<PlayAction, DiscardAction, ColourHintAction, ValueHintAction>;
template <class... Ts>
struct overloaded : Ts... {
using Ts::operator()...;
};
template <class... Ts>
overloaded(Ts...)->overloaded<Ts...>;
| [
"njormrod@fb.com"
] | njormrod@fb.com |
1debc00e42a987f128df6738dbe26588e898949d | 78918391a7809832dc486f68b90455c72e95cdda | /boost_lib/boost/variant/detail/apply_visitor_delayed.hpp | 34ec51760472695f26a44a759100e35fc3bbd510 | [
"MIT"
] | permissive | kyx0r/FA_Patcher | 50681e3e8bb04745bba44a71b5fd04e1004c3845 | 3f539686955249004b4483001a9e49e63c4856ff | refs/heads/master | 2022-03-28T10:03:28.419352 | 2020-01-02T09:16:30 | 2020-01-02T09:16:30 | 141,066,396 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,338 | hpp | //-----------------------------------------------------------------------------
// boost variant/detail/apply_visitor_delayed.hpp header file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2002-2003
// Eric Friedman
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_VARIANT_DETAIL_APPLY_VISITOR_DELAYED_HPP
#define BOOST_VARIANT_DETAIL_APPLY_VISITOR_DELAYED_HPP
#include <boost/variant/detail/generic_result_type.hpp>
#include <boost/variant/detail/apply_visitor_unary.hpp>
#include <boost/variant/detail/apply_visitor_binary.hpp>
#include <boost/variant/variant_fwd.hpp> // for BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES
#include <boost/variant/detail/has_result_type.hpp>
#include <boost/core/enable_if.hpp>
namespace boost
{
//////////////////////////////////////////////////////////////////////////
// function template apply_visitor(visitor)
//
// Returns a function object, overloaded for unary and binary usage, that
// visits its arguments using visitor (or a copy of visitor) via
// * apply_visitor( visitor, [argument] )
// under unary invocation, or
// * apply_visitor( visitor, [argument1], [argument2] )
// under binary invocation.
//
// NOTE: Unlike other apply_visitor forms, the visitor object must be
// non-const; this prevents user from giving temporary, to disastrous
// effect (i.e., returned function object would have dead reference).
//
template <typename Visitor>
class apply_visitor_delayed_t
{
public: // visitor typedefs
typedef typename Visitor::result_type
result_type;
private: // representation
Visitor& visitor_;
public: // structors
explicit apply_visitor_delayed_t(Visitor& visitor) BOOST_NOEXCEPT
:
visitor_(visitor)
{
}
#if !defined(BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES)
public: // N-ary visitor interface
template <typename... Visitables>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
operator()(Visitables&... visitables) const
{
return apply_visitor(visitor_, visitables...);
}
#else // !defined(BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES)
public: // unary visitor interface
template <typename Visitable>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
operator()(Visitable& visitable) const
{
return apply_visitor(visitor_, visitable);
}
public: // binary visitor interface
template <typename Visitable1, typename Visitable2>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
operator()(Visitable1& visitable1, Visitable2& visitable2) const
{
return apply_visitor(visitor_, visitable1, visitable2);
}
#endif // !defined(BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES)
private:
apply_visitor_delayed_t& operator=(const apply_visitor_delayed_t&);
};
template <typename Visitor>
inline typename boost::enable_if<
boost::detail::variant::has_result_type<Visitor>,
apply_visitor_delayed_t<Visitor>
>::type apply_visitor(Visitor& visitor)
{
return apply_visitor_delayed_t<Visitor>(visitor);
}
#if !defined(BOOST_NO_CXX14_DECLTYPE_AUTO) && !defined(BOOST_NO_CXX11_DECLTYPE_N3276) \
&& !defined(BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES)
template <typename Visitor>
class apply_visitor_delayed_cpp14_t
{
private: // representation
Visitor& visitor_;
public: // structors
explicit apply_visitor_delayed_cpp14_t(Visitor& visitor) BOOST_NOEXCEPT
:
visitor_(visitor)
{
}
public: // N-ary visitor interface
template <typename... Visitables>
decltype(auto) operator()(Visitables&... visitables) const
{
return apply_visitor(visitor_, visitables...);
}
private:
apply_visitor_delayed_cpp14_t& operator=(const apply_visitor_delayed_cpp14_t&);
};
template <typename Visitor>
inline typename boost::disable_if<
boost::detail::variant::has_result_type<Visitor>,
apply_visitor_delayed_cpp14_t<Visitor>
>::type apply_visitor(Visitor& visitor)
{
return apply_visitor_delayed_cpp14_t<Visitor>(visitor);
}
#endif // !defined(BOOST_NO_CXX14_DECLTYPE_AUTO) && !defined(BOOST_NO_CXX11_DECLTYPE_N3276)
// && !defined(BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES)
} // namespace boost
#endif // BOOST_VARIANT_DETAIL_APPLY_VISITOR_DELAYED_HPP
| [
"k.melekhin@gmail.com"
] | k.melekhin@gmail.com |
6b16d400138c1cf0babe5b2ebb51a10a27baccce | 9409843250b71099ec1a8e82a33d0cf3a33b14fb | /hw3/validator.cc | 899cbd95d4185ecc805b5e96ea38864cc21a88da | [] | no_license | VillainLouis/Parallel-Computing | 12a3bd3c0e6f888474c60b87b0caccb3d575a6c4 | 6dc5bae68ddd21310f9de196f3aa3a54e00a8985 | refs/heads/master | 2023-09-01T05:17:16.252534 | 2021-01-31T03:37:40 | 2021-01-31T03:37:40 | 680,186,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | cc | #include <cstdarg>
#include <cstdio>
#include <fstream>
#include <stdexcept>
#include <chrono>
#include <vector>
std::runtime_error reprintf(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
char* c_str;
vasprintf(&c_str, fmt, ap);
va_end(ap);
std::runtime_error re(c_str);
free(c_str);
return re;
}
class Timer {
std::chrono::steady_clock::time_point t0;
public:
Timer(): t0(std::chrono::steady_clock::now()) {}
~Timer() {
std::chrono::duration<double> dt = std::chrono::steady_clock::now() - t0;
printf("validation took %gs\n", dt.count());
}
};
int main(int argc, char** argv) {
Timer t;
if (argc != 2) {
throw reprintf("must provide exactly 1 argument");
}
std::ifstream f(argv[1]);
if (not f) {
throw reprintf("failed to open file: %s", argv[1]);
}
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
f.seekg(0, std::ios_base::end);
ssize_t fsize = f.tellg();
if (fsize % sizeof(int)) {
throw reprintf("file size %zd is not a multiple of sizeof(int) %zu", fsize, sizeof(int));
}
f.seekg(0, std::ios_base::beg);
int V;
int E;
f.read((char*)&V, sizeof V);
printf("V = %d\n", V);
if (V < 2 or V > 6000) {
throw reprintf("2 <= V <= 6000 failed");
}
f.read((char*)&E, sizeof E);
printf("E = %d\n", E);
if (E < 0 or E > V * (V - 1)) {
throw reprintf("0 <= E <= V * (V - 1) failed");
}
size_t efsize = sizeof(int) * (2 + E * 3);
if (fsize != efsize) {
throw reprintf("Expected file size %zd but got %zd", efsize, fsize);
}
std::vector<int> edges(V * V);
int exitcode = 0;
for (int i = 0; i < E; i++) {
int e[3];
f.read((char*)e, sizeof e);
if (e[0] < 0 or e[0] >= V) {
throw reprintf("src[%d] = %d is out of range", i, e[0]);
}
if (e[1] < 0 or e[1] >= V) {
throw reprintf("dst[%d] = %d is out of range", i, e[1]);
}
if (e[0] == e[1]) {
throw reprintf("src[%d] = dst[%d] = %d invalid", i, i, e[0]);
}
if (e[2] < 0 or e[2] > 1000) {
throw reprintf("w[%d] = %d is out of range", i, e[2]);
}
auto map_key = e[0] * V + e[1];
if (edges[map_key]) {
int j = edges[map_key] - 1;
throw reprintf("src[%d] = src[%d] = %d and dst[%d] = dst[%d] = %d invalid", j, i, e[0],
j, i, e[1]);
}
edges[map_key] = i + 1;
}
printf("Graph seems OK.\n");
}
| [
"louis@9dynamics.com.tw"
] | louis@9dynamics.com.tw |
420b4fdec86cf70f842e20af9c4d4c16df29b504 | 8936b221578b69066a84c7052a00c59e97fa1218 | /lab_05/edgetablewidget.h | e9b08fd8be8a4c7f4c666a2baf4edc60a35f02a6 | [
"MIT"
] | permissive | paulnopaul/computer-graphics | bc7964c96482dcbc1220b793f9ebcb421a8c6c94 | b0a92a9253cebc75f50e87b5370763a38de48f67 | refs/heads/master | 2022-09-11T20:38:33.280358 | 2020-06-03T16:51:50 | 2020-06-03T16:51:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | h | #ifndef EDGETABLEWIDGET_H
#define EDGETABLEWIDGET_H
#include <QListWidget>
#include "polygonwidget.h"
class EdgeTableWidget : public QListWidget
{
Q_OBJECT
public:
explicit EdgeTableWidget(QWidget *parent = nullptr);
public slots:
void clearEdges();
void addNewEdge(const QLine &);
private:
int pointLen = 10;
QList<QSharedPointer<QListWidgetItem>> itemList;
};
#endif // EDGETABLEWIDGET_H
| [
"tscheklin@gmail.com"
] | tscheklin@gmail.com |
837514df0017bff29f6b6d7480c2f53a1866bc82 | 5f924c87a3d0516ae8382c4ee36b4824384d1c0c | /code/misc/starting_code/princess0.cpp | fd2f77261ca83a5bee05393df78ce8ae32c6a566 | [] | no_license | arfaouiGit/OOP2 | c239e9b5d075fdaa5867867f4fe4c438266ca9b3 | 7378a85f0932d869993760f664541be7a0932474 | refs/heads/master | 2022-07-10T23:35:32.874904 | 2020-05-11T20:19:28 | 2020-05-11T20:19:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | #include "princess.h"
#include "frog.h"
using namespace std;
void Princess::marries(amphib::Frog* fp) {
spouse = fp;
fp->spouse = this;
}
ostream& operator<<(ostream& os, const Princess& princess) {
string marital_status = (princess.spouse ?
"married to " + princess.spouse->get_name()
: "unmarried");
os << "Princess: " << princess.name << " is " << marital_status << endl;
return os;
}
| [
"gcallah@mac.com"
] | gcallah@mac.com |
3e5e864fb91455c23603aa3dafd30ba2d679896a | e072d34d3e7471e7ad0722db2e7782e00b5f8e7b | /protobuf-2.0.3/src/google/protobuf/unittest_optimize_for.pb.cc | a9a708f87ec6c04a44960906afb9f8c874fe748f | [
"Apache-2.0",
"LicenseRef-scancode-protobuf"
] | permissive | runt18/metasyntactic | 4f18fd4644300ec8e97af885e0f0070e420d197c | 908ea84b51fcaead0a9051235d4967ccec0fb066 | refs/heads/master | 2021-01-10T04:32:55.077423 | 2016-03-22T18:40:13 | 2016-03-22T18:40:13 | 49,944,612 | 0 | 0 | null | 2016-03-22T18:40:14 | 2016-01-19T10:19:06 | C++ | UTF-8 | C++ | false | true | 12,624 | cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
#include "google/protobuf/unittest_optimize_for.pb.h"
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format_inl.h>
namespace protobuf_unittest {
namespace {
const ::google::protobuf::Descriptor* TestOptimizedForSize_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestOptimizedForSize_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestRequiredOptimizedForSize_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestRequiredOptimizedForSize_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestOptionalOptimizedForSize_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestOptionalOptimizedForSize_reflection_ = NULL;
} // namespace
void protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto_AssignGlobalDescriptors(const ::google::protobuf::FileDescriptor* file) {
TestOptimizedForSize_descriptor_ = file->message_type(0);
TestOptimizedForSize::default_instance_ = new TestOptimizedForSize();
static const int TestOptimizedForSize_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptimizedForSize, i_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptimizedForSize, msg_),
};
TestOptimizedForSize_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
TestOptimizedForSize_descriptor_,
TestOptimizedForSize::default_instance_,
TestOptimizedForSize_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptimizedForSize, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptimizedForSize, _unknown_fields_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptimizedForSize, _extensions_),
::google::protobuf::DescriptorPool::generated_pool(),
sizeof(TestOptimizedForSize));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestOptimizedForSize_descriptor_, TestOptimizedForSize::default_instance_);
TestRequiredOptimizedForSize_descriptor_ = file->message_type(1);
TestRequiredOptimizedForSize::default_instance_ = new TestRequiredOptimizedForSize();
static const int TestRequiredOptimizedForSize_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRequiredOptimizedForSize, x_),
};
TestRequiredOptimizedForSize_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
TestRequiredOptimizedForSize_descriptor_,
TestRequiredOptimizedForSize::default_instance_,
TestRequiredOptimizedForSize_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRequiredOptimizedForSize, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRequiredOptimizedForSize, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
sizeof(TestRequiredOptimizedForSize));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestRequiredOptimizedForSize_descriptor_, TestRequiredOptimizedForSize::default_instance_);
TestOptionalOptimizedForSize_descriptor_ = file->message_type(2);
TestOptionalOptimizedForSize::default_instance_ = new TestOptionalOptimizedForSize();
static const int TestOptionalOptimizedForSize_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptionalOptimizedForSize, o_),
};
TestOptionalOptimizedForSize_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
TestOptionalOptimizedForSize_descriptor_,
TestOptionalOptimizedForSize::default_instance_,
TestOptionalOptimizedForSize_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptionalOptimizedForSize, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestOptionalOptimizedForSize, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
sizeof(TestOptionalOptimizedForSize));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestOptionalOptimizedForSize_descriptor_, TestOptionalOptimizedForSize::default_instance_);
TestOptimizedForSize::default_instance_->InitAsDefaultInstance();
TestRequiredOptimizedForSize::default_instance_->InitAsDefaultInstance();
TestOptionalOptimizedForSize::default_instance_->InitAsDefaultInstance();
}
void protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool* pool =
::google::protobuf::DescriptorPool::internal_generated_pool();
::protobuf_unittest::protobuf_BuildDesc_google_2fprotobuf_2funittest_2eproto();
pool->InternalBuildGeneratedFile(
"\n+google/protobuf/unittest_optimize_for."
"proto\022\021protobuf_unittest\032\036google/protobu"
"f/unittest.proto\"\222\002\n\024TestOptimizedForSiz"
"e\022\t\n\001i\030\001 \001(\005\022.\n\003msg\030\023 \001(\0132!.protobuf_uni"
"ttest.ForeignMessage*\t\010\350\007\020\200\200\200\200\0022@\n\016test_"
"extension\022\'.protobuf_unittest.TestOptimi"
"zedForSize\030\322\t \001(\0052r\n\017test_extension2\022\'.p"
"rotobuf_unittest.TestOptimizedForSize\030\323\t"
" \001(\0132/.protobuf_unittest.TestRequiredOpt"
"imizedForSize\")\n\034TestRequiredOptimizedFo"
"rSize\022\t\n\001x\030\001 \002(\005\"Z\n\034TestOptionalOptimize"
"dForSize\022:\n\001o\030\001 \001(\0132/.protobuf_unittest."
"TestRequiredOptimizedForSizeB\002H\002", 512,
&protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto_AssignGlobalDescriptors);
}
// Force BuildDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto() {
protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
}
} static_descriptor_initializer_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto_;
// ===================================================================
::google::protobuf::internal::ExtensionIdentifier< ::protobuf_unittest::TestOptimizedForSize,
::google::protobuf::internal::PrimitiveTypeTraits< ::google::protobuf::int32 > > TestOptimizedForSize::test_extension(1234);
::google::protobuf::internal::ExtensionIdentifier< ::protobuf_unittest::TestOptimizedForSize,
::google::protobuf::internal::MessageTypeTraits< ::protobuf_unittest::TestRequiredOptimizedForSize > > TestOptimizedForSize::test_extension2(1235);
TestOptimizedForSize::TestOptimizedForSize()
: ::google::protobuf::Message(),
_extensions_(&TestOptimizedForSize_descriptor_,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory()),
_cached_size_(0),
i_(0),
msg_(NULL) {
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
void TestOptimizedForSize::InitAsDefaultInstance() { msg_ = const_cast< ::protobuf_unittest::ForeignMessage*>(&::protobuf_unittest::ForeignMessage::default_instance());
}
TestOptimizedForSize::TestOptimizedForSize(const TestOptimizedForSize& from)
: ::google::protobuf::Message(),
_extensions_(&TestOptimizedForSize_descriptor_,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory()),
_cached_size_(0),
i_(0),
msg_(NULL) {
::memset(_has_bits_, 0, sizeof(_has_bits_));
MergeFrom(from);
}
TestOptimizedForSize::~TestOptimizedForSize() {
if (this != default_instance_) {
delete msg_;
}
}
const ::google::protobuf::Descriptor* TestOptimizedForSize::descriptor() {
if (TestOptimizedForSize_descriptor_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return TestOptimizedForSize_descriptor_;
}
const TestOptimizedForSize& TestOptimizedForSize::default_instance() {
if (default_instance_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return *default_instance_;
}
TestOptimizedForSize* TestOptimizedForSize::default_instance_ = NULL;
TestOptimizedForSize* TestOptimizedForSize::New() const {
return new TestOptimizedForSize;
}
const ::google::protobuf::Descriptor* TestOptimizedForSize::GetDescriptor() const {
return descriptor();
}
const ::google::protobuf::Reflection* TestOptimizedForSize::GetReflection() const {
if (TestOptimizedForSize_reflection_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return TestOptimizedForSize_reflection_;
}
// ===================================================================
TestRequiredOptimizedForSize::TestRequiredOptimizedForSize()
: ::google::protobuf::Message(),
_cached_size_(0),
x_(0) {
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
void TestRequiredOptimizedForSize::InitAsDefaultInstance() {}
TestRequiredOptimizedForSize::TestRequiredOptimizedForSize(const TestRequiredOptimizedForSize& from)
: ::google::protobuf::Message(),
_cached_size_(0),
x_(0) {
::memset(_has_bits_, 0, sizeof(_has_bits_));
MergeFrom(from);
}
TestRequiredOptimizedForSize::~TestRequiredOptimizedForSize() {
if (this != default_instance_) {
}
}
const ::google::protobuf::Descriptor* TestRequiredOptimizedForSize::descriptor() {
if (TestRequiredOptimizedForSize_descriptor_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return TestRequiredOptimizedForSize_descriptor_;
}
const TestRequiredOptimizedForSize& TestRequiredOptimizedForSize::default_instance() {
if (default_instance_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return *default_instance_;
}
TestRequiredOptimizedForSize* TestRequiredOptimizedForSize::default_instance_ = NULL;
TestRequiredOptimizedForSize* TestRequiredOptimizedForSize::New() const {
return new TestRequiredOptimizedForSize;
}
const ::google::protobuf::Descriptor* TestRequiredOptimizedForSize::GetDescriptor() const {
return descriptor();
}
const ::google::protobuf::Reflection* TestRequiredOptimizedForSize::GetReflection() const {
if (TestRequiredOptimizedForSize_reflection_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return TestRequiredOptimizedForSize_reflection_;
}
// ===================================================================
TestOptionalOptimizedForSize::TestOptionalOptimizedForSize()
: ::google::protobuf::Message(),
_cached_size_(0),
o_(NULL) {
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
void TestOptionalOptimizedForSize::InitAsDefaultInstance() { o_ = const_cast< ::protobuf_unittest::TestRequiredOptimizedForSize*>(&::protobuf_unittest::TestRequiredOptimizedForSize::default_instance());
}
TestOptionalOptimizedForSize::TestOptionalOptimizedForSize(const TestOptionalOptimizedForSize& from)
: ::google::protobuf::Message(),
_cached_size_(0),
o_(NULL) {
::memset(_has_bits_, 0, sizeof(_has_bits_));
MergeFrom(from);
}
TestOptionalOptimizedForSize::~TestOptionalOptimizedForSize() {
if (this != default_instance_) {
delete o_;
}
}
const ::google::protobuf::Descriptor* TestOptionalOptimizedForSize::descriptor() {
if (TestOptionalOptimizedForSize_descriptor_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return TestOptionalOptimizedForSize_descriptor_;
}
const TestOptionalOptimizedForSize& TestOptionalOptimizedForSize::default_instance() {
if (default_instance_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return *default_instance_;
}
TestOptionalOptimizedForSize* TestOptionalOptimizedForSize::default_instance_ = NULL;
TestOptionalOptimizedForSize* TestOptionalOptimizedForSize::New() const {
return new TestOptionalOptimizedForSize;
}
const ::google::protobuf::Descriptor* TestOptionalOptimizedForSize::GetDescriptor() const {
return descriptor();
}
const ::google::protobuf::Reflection* TestOptionalOptimizedForSize::GetReflection() const {
if (TestOptionalOptimizedForSize_reflection_ == NULL) protobuf_BuildDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
return TestOptionalOptimizedForSize_reflection_;
}
} // namespace protobuf_unittest
| [
"cyrus.najmabadi@d0982328-d147-0410-9e64-db1d7fe6b3aa"
] | cyrus.najmabadi@d0982328-d147-0410-9e64-db1d7fe6b3aa |
c3d296bee233d9059d57029ccdce9a086378ef1e | bc77dd3023cb8655d82af3ad4320d2f9e5f9532a | /SourceCode/Chapter02/CountChars/CountChars.cpp | ea49f5ad9703601d9545bcb2ac61583695e64e5c | [] | no_license | timothyshull/modern_x86_assembly | de28cbbc877a12c5f6f493b9ced5c1883f682bfa | ead24367c106143b90934812a4a781ba46683ad5 | refs/heads/master | 2021-01-19T14:48:45.405342 | 2017-04-09T16:26:37 | 2017-04-09T16:26:37 | 86,637,835 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 972 | cpp |
extern "C" int CountChars_(wchar_t *s, wchar_t c);
int main(int argc, char *argv[])
{
wchar_t c;
wchar_t *s;
s = L"Four score and seven seconds ago, ...";
wprintf(L"\nTest string: %s\n", s);
c = L's';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
c = L'F';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
c = L'o';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
c = L'z';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
s = L"Red Green Blue Cyan Magenta Yellow";
wprintf(L"\nTest string: %s\n", s);
c = L'e';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
c = L'w';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
c = L'Q';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
c = L'l';
wprintf(L" SearchChar: %c Count: %d\n", c, CountChars_(s, c));
return 0;
}
| [
"timothyshull@gmail.com"
] | timothyshull@gmail.com |
7e34ab4a4d82860a51c9228c4e01d8d764a17e94 | 03f037d0f6371856ede958f0c9d02771d5402baf | /graphics/VTK-7.0.0/Wrapping/PythonCore/PyVTKMutableObject.cxx | f4f2cfc9d5c292d5f0012fb49d8cc86e2f124a7a | [
"BSD-3-Clause"
] | permissive | hlzz/dotfiles | b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb | 0591f71230c919c827ba569099eb3b75897e163e | refs/heads/master | 2021-01-10T10:06:31.018179 | 2016-09-27T08:13:18 | 2016-09-27T08:13:18 | 55,040,954 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,371 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: PyVTKMutableObject.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-----------------------------------------------------------------------
The PyVTKMutableObject was created in Sep 2010 by David Gobbi.
This class is a proxy for immutable python objects like int, float,
and string. It allows these objects to be passed to VTK methods that
require a ref.
-----------------------------------------------------------------------*/
#include "PyVTKMutableObject.h"
#include "vtkPythonUtil.h"
// Silence warning like
// "dereferencing type-punned pointer will break strict-aliasing rules"
// it happens because this kind of expression: (long *)&ptr
#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
//--------------------------------------------------------------------
static const char *PyVTKMutableObject_Doc =
"A mutable wrapper for immutable objects.\n\n"
"This wrapper class is needed when a VTK method returns a value\n"
"in an argument that has been passed by reference. By calling\n"
"\"m = vtk.mutable(a)\" on a value, you can create a mutable proxy\n"
"to that value. The value can be changed by calling \"m.set(b)\".\n";
//--------------------------------------------------------------------
// helper method: make sure than an object is usable
static PyObject *PyVTKMutableObject_CompatibleObject(PyObject *opn)
{
PyNumberMethods *nb = Py_TYPE(opn)->tp_as_number;
if (PyFloat_Check(opn) ||
PyLong_Check(opn) ||
#ifndef VTK_PY3K
PyInt_Check(opn) ||
#endif
#ifdef Py_USING_UNICODE
PyUnicode_Check(opn) ||
#endif
PyBytes_Check(opn))
{
Py_INCREF(opn);
}
else if (PyVTKMutableObject_Check(opn))
{
opn = ((PyVTKMutableObject *)opn)->value;
Py_INCREF(opn);
}
else if (nb && nb->nb_index)
{
opn = nb->nb_index(opn);
if (opn == 0 || (!PyLong_Check(opn)
#ifndef VTK_PY3K
&& !PyInt_Check(opn)
#endif
))
{
PyErr_SetString(PyExc_TypeError,
"nb_index should return integer object");
return NULL;
}
}
else if (nb && nb->nb_float)
{
opn = nb->nb_float(opn);
if (opn == 0 || !PyFloat_Check(opn))
{
PyErr_SetString(PyExc_TypeError,
"nb_float should return float object");
return NULL;
}
}
else
{
PyErr_SetString(PyExc_TypeError,
"a numeric or string object is required");
return NULL;
}
return opn;
}
//--------------------------------------------------------------------
// methods from C
PyObject *PyVTKMutableObject_GetValue(PyObject *self)
{
if (PyVTKMutableObject_Check(self))
{
return ((PyVTKMutableObject *)self)->value;
}
else
{
PyErr_SetString(PyExc_TypeError, "a vtk.mutable() object is required");
}
return NULL;
}
int PyVTKMutableObject_SetValue(PyObject *self, PyObject *val)
{
if (PyVTKMutableObject_Check(self))
{
PyObject **op = &((PyVTKMutableObject *)self)->value;
if (PyFloat_Check(val) ||
#ifndef VTK_PY3K
PyInt_Check(val) ||
#endif
PyLong_Check(val))
{
if (PyFloat_Check(*op) ||
#ifndef VTK_PY3K
PyInt_Check(*op) ||
#endif
PyLong_Check(*op))
{
Py_DECREF(*op);
*op = val;
return 0;
}
PyErr_SetString(PyExc_TypeError,
"cannot set a string mutable to a numeric value");
}
else if (
#ifdef Py_USING_UNICODE
PyUnicode_Check(val) ||
#endif
PyBytes_Check(val))
{
if (
#ifdef Py_USING_UNICODE
PyUnicode_Check(*op) ||
#endif
PyBytes_Check(*op))
{
Py_DECREF(*op);
*op = val;
return 0;
}
PyErr_SetString(PyExc_TypeError,
"cannot set a numeric mutable to a string value");
}
else
{
PyErr_SetString(PyExc_TypeError,
"a float, long, int, or string is required");
}
}
else
{
PyErr_SetString(PyExc_TypeError, "a vtk.mutable() object is required");
}
return -1;
}
//--------------------------------------------------------------------
// methods from python
static PyObject *PyVTKMutableObject_Get(PyObject *self, PyObject *args)
{
if (PyArg_ParseTuple(args, ":get"))
{
PyObject *ob = PyVTKMutableObject_GetValue(self);
Py_INCREF(ob);
return ob;
}
return NULL;
}
static PyObject *PyVTKMutableObject_Set(PyObject *self, PyObject *args)
{
PyObject *opn;
if (PyArg_ParseTuple(args, "O:set", &opn))
{
opn = PyVTKMutableObject_CompatibleObject(opn);
if (opn)
{
if (PyVTKMutableObject_SetValue(self, opn) == 0)
{
Py_INCREF(Py_None);
return Py_None;
}
}
}
return NULL;
}
#ifdef VTK_PY3K
static PyObject *PyVTKMutableObject_Trunc(PyObject *self, PyObject *args)
{
PyObject *opn;
if (PyArg_ParseTuple(args, ":__trunc__", &opn))
{
PyObject *attr = PyUnicode_InternFromString("__trunc__");
PyObject *ob = PyVTKMutableObject_GetValue(self);
PyObject *meth = _PyType_Lookup(Py_TYPE(ob), attr);
if (meth == NULL)
{
PyErr_Format(PyExc_TypeError,
"type %.100s doesn't define __trunc__ method",
Py_TYPE(ob)->tp_name);
return NULL;
}
return PyObject_CallFunction(meth, (char *)"O", ob);
}
return NULL;
}
static PyObject *PyVTKMutableObject_Round(PyObject *self, PyObject *args)
{
PyObject *opn;
if (PyArg_ParseTuple(args, "|O:__round__", &opn))
{
PyObject *attr = PyUnicode_InternFromString("__round__");
PyObject *ob = PyVTKMutableObject_GetValue(self);
PyObject *meth = _PyType_Lookup(Py_TYPE(ob), attr);
if (meth == NULL)
{
PyErr_Format(PyExc_TypeError,
"type %.100s doesn't define __round__ method",
Py_TYPE(ob)->tp_name);
return NULL;
}
if (opn)
{
return PyObject_CallFunction(meth, (char *)"OO", ob, opn);
}
return PyObject_CallFunction(meth, (char *)"O", ob);
}
return NULL;
}
#endif
static PyMethodDef PyVTKMutableObject_Methods[] = {
{"get", PyVTKMutableObject_Get, METH_VARARGS, "Get the stored value."},
{"set", PyVTKMutableObject_Set, METH_VARARGS, "Set the stored value."},
#ifdef VTK_PY3K
{"__trunc__", PyVTKMutableObject_Trunc, METH_VARARGS,
"Returns the Integral closest to x between 0 and x."},
{"__round__", PyVTKMutableObject_Round, METH_VARARGS,
"Returns the Integral closest to x, rounding half toward even.\n"},
#endif
{ NULL, NULL, 0, NULL }
};
//--------------------------------------------------------------------
// Macros used for defining protocol methods
#define REFOBJECT_INTFUNC(prot, op) \
static int PyVTKMutableObject_##op(PyObject *ob) \
{ \
ob = ((PyVTKMutableObject *)ob)->value; \
return Py##prot##_##op(ob); \
}
#define REFOBJECT_SIZEFUNC(prot, op) \
static Py_ssize_t PyVTKMutableObject_##op(PyObject *ob) \
{ \
ob = ((PyVTKMutableObject *)ob)->value; \
return Py##prot##_##op(ob); \
}
#define REFOBJECT_INDEXFUNC(prot, op) \
static PyObject *PyVTKMutableObject_##op(PyObject *ob, Py_ssize_t i) \
{ \
ob = ((PyVTKMutableObject *)ob)->value; \
return Py##prot##_##op(ob, i); \
}
#define REFOBJECT_INDEXSETFUNC(prot, op) \
static int PyVTKMutableObject_##op(PyObject *ob, Py_ssize_t i, PyObject *o) \
{ \
ob = ((PyVTKMutableObject *)ob)->value; \
return Py##prot##_##op(ob, i, o); \
}
#define REFOBJECT_SLICEFUNC(prot, op) \
static PyObject *PyVTKMutableObject_##op(PyObject *ob, Py_ssize_t i, Py_ssize_t j) \
{ \
ob = ((PyVTKMutableObject *)ob)->value; \
return Py##prot##_##op(ob, i, j); \
}
#define REFOBJECT_SLICESETFUNC(prot, op) \
static int PyVTKMutableObject_##op(PyObject *ob, Py_ssize_t i, Py_ssize_t j, PyObject *o) \
{ \
ob = ((PyVTKMutableObject *)ob)->value; \
return Py##prot##_##op(ob, i, j, o); \
}
#define REFOBJECT_UNARYFUNC(prot, op) \
static PyObject *PyVTKMutableObject_##op(PyObject *ob) \
{ \
ob = ((PyVTKMutableObject *)ob)->value; \
return Py##prot##_##op(ob); \
}
#define REFOBJECT_BINARYFUNC(prot, op) \
static PyObject *PyVTKMutableObject_##op(PyObject *ob1, PyObject *ob2) \
{ \
if (PyVTKMutableObject_Check(ob1)) \
{ \
ob1 = ((PyVTKMutableObject *)ob1)->value; \
} \
if (PyVTKMutableObject_Check(ob2)) \
{ \
ob2 = ((PyVTKMutableObject *)ob2)->value; \
} \
return Py##prot##_##op(ob1, ob2); \
}
#define REFOBJECT_INPLACEFUNC(prot, op) \
static PyObject *PyVTKMutableObject_InPlace##op(PyObject *ob1, PyObject *ob2) \
{ \
PyVTKMutableObject *ob = (PyVTKMutableObject *)ob1; \
PyObject *obn;\
ob1 = ob->value; \
if (PyVTKMutableObject_Check(ob2)) \
{ \
ob2 = ((PyVTKMutableObject *)ob2)->value; \
} \
obn = Py##prot##_##op(ob1, ob2); \
if (obn) \
{ \
ob->value = obn; \
Py_DECREF(ob1); \
Py_INCREF(ob); \
return (PyObject *)ob; \
} \
return 0; \
}
#define REFOBJECT_INPLACEIFUNC(prot, op) \
static PyObject *PyVTKMutableObject_InPlace##op(PyObject *ob1, Py_ssize_t i) \
{ \
PyVTKMutableObject *ob = (PyVTKMutableObject *)ob1; \
PyObject *obn;\
ob1 = ob->value; \
obn = Py##prot##_##op(ob1, i); \
if (obn) \
{ \
ob->value = obn; \
Py_DECREF(ob1); \
Py_INCREF(ob); \
return (PyObject *)ob; \
} \
return 0; \
}
#define REFOBJECT_TERNARYFUNC(prot, op) \
static PyObject *PyVTKMutableObject_##op(PyObject *ob1, PyObject *ob2, PyObject *ob3) \
{ \
if (PyVTKMutableObject_Check(ob1)) \
{ \
ob1 = ((PyVTKMutableObject *)ob1)->value; \
} \
if (PyVTKMutableObject_Check(ob2)) \
{ \
ob2 = ((PyVTKMutableObject *)ob2)->value; \
} \
if (PyVTKMutableObject_Check(ob2)) \
{ \
ob3 = ((PyVTKMutableObject *)ob3)->value; \
} \
return Py##prot##_##op(ob1, ob2, ob3); \
}
#define REFOBJECT_INPLACETFUNC(prot, op) \
static PyObject *PyVTKMutableObject_InPlace##op(PyObject *ob1, PyObject *ob2, PyObject *ob3) \
{ \
PyVTKMutableObject *ob = (PyVTKMutableObject *)ob1; \
PyObject *obn; \
ob1 = ob->value; \
if (PyVTKMutableObject_Check(ob2)) \
{ \
ob2 = ((PyVTKMutableObject *)ob2)->value; \
} \
if (PyVTKMutableObject_Check(ob3)) \
{ \
ob3 = ((PyVTKMutableObject *)ob3)->value; \
} \
obn = Py##prot##_##op(ob1, ob2, ob3); \
if (obn) \
{ \
ob->value = obn; \
Py_DECREF(ob1); \
Py_INCREF(ob); \
return (PyObject *)ob; \
} \
return 0; \
}
//--------------------------------------------------------------------
// Number protocol
static int PyVTKMutableObject_NonZero(PyObject *ob)
{
ob = ((PyVTKMutableObject *)ob)->value;
return PyObject_IsTrue(ob);
}
#ifndef VTK_PY3K
static int PyVTKMutableObject_Coerce(PyObject **ob1, PyObject **ob2)
{
*ob1 = ((PyVTKMutableObject *)*ob1)->value;
if (PyVTKMutableObject_Check(*ob2))
{
*ob2 = ((PyVTKMutableObject *)*ob2)->value;
}
return PyNumber_CoerceEx(ob1, ob2);
}
static PyObject *PyVTKMutableObject_Hex(PyObject *ob)
{
ob = ((PyVTKMutableObject *)ob)->value;
#if PY_VERSION_HEX >= 0x02060000
return PyNumber_ToBase(ob, 16);
#else
if (Py_TYPE(ob)->tp_as_number &&
Py_TYPE(ob)->tp_as_number->nb_hex)
{
return Py_TYPE(ob)->tp_as_number->nb_hex(ob);
}
PyErr_SetString(PyExc_TypeError,
"hex() argument can't be converted to hex");
return NULL;
#endif
}
static PyObject *PyVTKMutableObject_Oct(PyObject *ob)
{
ob = ((PyVTKMutableObject *)ob)->value;
#if PY_VERSION_HEX >= 0x02060000
return PyNumber_ToBase(ob, 8);
#else
if (Py_TYPE(ob)->tp_as_number &&
Py_TYPE(ob)->tp_as_number->nb_oct)
{
return Py_TYPE(ob)->tp_as_number->nb_oct(ob);
}
PyErr_SetString(PyExc_TypeError,
"oct() argument can't be converted to oct");
return NULL;
#endif
}
#endif
REFOBJECT_BINARYFUNC(Number,Add)
REFOBJECT_BINARYFUNC(Number,Subtract)
REFOBJECT_BINARYFUNC(Number,Multiply)
#ifndef VTK_PY3K
REFOBJECT_BINARYFUNC(Number,Divide)
#endif
REFOBJECT_BINARYFUNC(Number,Remainder)
REFOBJECT_BINARYFUNC(Number,Divmod)
REFOBJECT_TERNARYFUNC(Number,Power)
REFOBJECT_UNARYFUNC(Number,Negative)
REFOBJECT_UNARYFUNC(Number,Positive)
REFOBJECT_UNARYFUNC(Number,Absolute)
// NonZero
REFOBJECT_UNARYFUNC(Number,Invert)
REFOBJECT_BINARYFUNC(Number,Lshift)
REFOBJECT_BINARYFUNC(Number,Rshift)
REFOBJECT_BINARYFUNC(Number,And)
REFOBJECT_BINARYFUNC(Number,Or)
REFOBJECT_BINARYFUNC(Number,Xor)
// Coerce
#ifndef VTK_PY3K
REFOBJECT_UNARYFUNC(Number,Int)
#endif
REFOBJECT_UNARYFUNC(Number,Long)
REFOBJECT_UNARYFUNC(Number,Float)
REFOBJECT_INPLACEFUNC(Number,Add)
REFOBJECT_INPLACEFUNC(Number,Subtract)
REFOBJECT_INPLACEFUNC(Number,Multiply)
#ifndef VTK_PY3K
REFOBJECT_INPLACEFUNC(Number,Divide)
#endif
REFOBJECT_INPLACEFUNC(Number,Remainder)
REFOBJECT_INPLACETFUNC(Number,Power)
REFOBJECT_INPLACEFUNC(Number,Lshift)
REFOBJECT_INPLACEFUNC(Number,Rshift)
REFOBJECT_INPLACEFUNC(Number,And)
REFOBJECT_INPLACEFUNC(Number,Or)
REFOBJECT_INPLACEFUNC(Number,Xor)
REFOBJECT_BINARYFUNC(Number,FloorDivide)
REFOBJECT_BINARYFUNC(Number,TrueDivide)
REFOBJECT_INPLACEFUNC(Number,FloorDivide)
REFOBJECT_INPLACEFUNC(Number,TrueDivide)
REFOBJECT_UNARYFUNC(Number,Index)
//--------------------------------------------------------------------
static PyNumberMethods PyVTKMutableObject_AsNumber = {
PyVTKMutableObject_Add, // nb_add
PyVTKMutableObject_Subtract, // nb_subtract
PyVTKMutableObject_Multiply, // nb_multiply
#ifndef VTK_PY3K
PyVTKMutableObject_Divide, // nb_divide
#endif
PyVTKMutableObject_Remainder, // nb_remainder
PyVTKMutableObject_Divmod, // nb_divmod
PyVTKMutableObject_Power, // nb_power
PyVTKMutableObject_Negative, // nb_negative
PyVTKMutableObject_Positive, // nb_positive
PyVTKMutableObject_Absolute, // nb_absolute
PyVTKMutableObject_NonZero, // nb_nonzero
PyVTKMutableObject_Invert, // nb_invert
PyVTKMutableObject_Lshift, // nb_lshift
PyVTKMutableObject_Rshift, // nb_rshift
PyVTKMutableObject_And, // nb_and
PyVTKMutableObject_Xor, // nb_xor
PyVTKMutableObject_Or, // nb_or
#ifndef VTK_PY3K
PyVTKMutableObject_Coerce, // nb_coerce
PyVTKMutableObject_Int, // nb_int
PyVTKMutableObject_Long, // nb_long
#else
PyVTKMutableObject_Long, // nb_int
NULL, // nb_reserved
#endif
PyVTKMutableObject_Float, // nb_float
#ifndef VTK_PY3K
PyVTKMutableObject_Oct, // nb_oct
PyVTKMutableObject_Hex, // nb_hex
#endif
PyVTKMutableObject_InPlaceAdd, // nb_inplace_add
PyVTKMutableObject_InPlaceSubtract, // nb_inplace_subtract
PyVTKMutableObject_InPlaceMultiply, // nb_inplace_multiply
#ifndef VTK_PY3K
PyVTKMutableObject_InPlaceDivide, // nb_inplace_divide
#endif
PyVTKMutableObject_InPlaceRemainder, // nb_inplace_remainder
PyVTKMutableObject_InPlacePower, // nb_inplace_power
PyVTKMutableObject_InPlaceLshift, // nb_inplace_lshift
PyVTKMutableObject_InPlaceRshift, // nb_inplace_rshift
PyVTKMutableObject_InPlaceAnd, // nb_inplace_and
PyVTKMutableObject_InPlaceXor, // nb_inplace_xor
PyVTKMutableObject_InPlaceOr, // nb_inplace_or
PyVTKMutableObject_FloorDivide, // nb_floor_divide
PyVTKMutableObject_TrueDivide, // nb_true_divide
PyVTKMutableObject_InPlaceFloorDivide, // nb_inplace_floor_divide
PyVTKMutableObject_InPlaceTrueDivide, // nb_inplace_true_divide
PyVTKMutableObject_Index, // nb_index
#if PY_VERSION_HEX >= 0x03050000
0, // nb_matrix_multiply
0, // nb_inplace_matrix_multiply
#endif
};
// Disable sequence and mapping protocols until a subtype is made
#if 0
//--------------------------------------------------------------------
// Sequence protocol
REFOBJECT_SIZEFUNC(Sequence,Size)
REFOBJECT_BINARYFUNC(Sequence,Concat)
REFOBJECT_INDEXFUNC(Sequence,Repeat)
REFOBJECT_INDEXFUNC(Sequence,GetItem)
REFOBJECT_SLICEFUNC(Sequence,GetSlice)
REFOBJECT_INDEXSETFUNC(Sequence,SetItem)
REFOBJECT_SLICESETFUNC(Sequence,SetSlice)
REFOBJECT_INPLACEFUNC(Sequence,Concat)
REFOBJECT_INPLACEIFUNC(Sequence,Repeat)
//--------------------------------------------------------------------
static PySequenceMethods PyVTKMutableObject_AsSequence = {
PyVTKMutableObject_Size, // sq_length
PyVTKMutableObject_Concat, // sq_concat
PyVTKMutableObject_Repeat, // sq_repeat
PyVTKMutableObject_GetItem, // sq_item
PyVTKMutableObject_GetSlice, // sq_slice
PyVTKMutableObject_SetItem, // sq_ass_item
PyVTKMutableObject_SetSlice, // sq_ass_slice
0, // sq_contains
PyVTKMutableObject_InPlaceConcat, // sq_inplace_concat
PyVTKMutableObject_InPlaceRepeat, // sq_inplace_repeat
};
//--------------------------------------------------------------------
// Mapping protocol
static PyObject *
PyVTKMutableObject_GetMapItem(PyObject *ob, PyObject *key)
{
ob = ((PyVTKMutableObject *)ob)->value;
return PyObject_GetItem(ob, key);
}
static int
PyVTKMutableObject_SetMapItem(PyObject *ob, PyObject *key, PyObject *o)
{
ob = ((PyVTKMutableObject *)ob)->value;
return PyObject_SetItem(ob, key, o);
}
//--------------------------------------------------------------------
static PyMappingMethods PyVTKMutableObject_AsMapping = {
PyVTKMutableObject_Size, // mp_length
PyVTKMutableObject_GetMapItem, // mp_subscript
PyVTKMutableObject_SetMapItem, // mp_ass_subscript
};
#endif
//--------------------------------------------------------------------
// Buffer protocol
#ifndef VTK_PY3K
// old buffer protocol
static Py_ssize_t PyVTKMutableObject_GetReadBuf(
PyObject *op, Py_ssize_t segment, void **ptrptr)
{
char text[80];
PyBufferProcs *pb;
op = ((PyVTKMutableObject *)op)->value;
pb = Py_TYPE(op)->tp_as_buffer;
if (pb && pb->bf_getreadbuffer)
{
return Py_TYPE(op)->tp_as_buffer->bf_getreadbuffer(
op, segment, ptrptr);
}
sprintf(text, "type \'%.20s\' does not support readable buffer access",
Py_TYPE(op)->tp_name);
PyErr_SetString(PyExc_TypeError, text);
return -1;
}
static Py_ssize_t PyVTKMutableObject_GetWriteBuf(
PyObject *op, Py_ssize_t segment, void **ptrptr)
{
char text[80];
PyBufferProcs *pb;
op = ((PyVTKMutableObject *)op)->value;
pb = Py_TYPE(op)->tp_as_buffer;
if (pb && pb->bf_getwritebuffer)
{
return Py_TYPE(op)->tp_as_buffer->bf_getwritebuffer(
op, segment, ptrptr);
}
sprintf(text, "type \'%.20s\' does not support writeable buffer access",
Py_TYPE(op)->tp_name);
PyErr_SetString(PyExc_TypeError, text);
return -1;
}
static Py_ssize_t
PyVTKMutableObject_GetSegCount(PyObject *op, Py_ssize_t *lenp)
{
char text[80];
PyBufferProcs *pb;
op = ((PyVTKMutableObject *)op)->value;
pb = Py_TYPE(op)->tp_as_buffer;
if (pb && pb->bf_getsegcount)
{
return Py_TYPE(op)->tp_as_buffer->bf_getsegcount(op, lenp);
}
sprintf(text, "type \'%.20s\' does not support buffer access",
Py_TYPE(op)->tp_name);
PyErr_SetString(PyExc_TypeError, text);
return -1;
}
static Py_ssize_t PyVTKMutableObject_GetCharBuf(
PyObject *op, Py_ssize_t segment, char **ptrptr)
{
char text[80];
PyBufferProcs *pb;
op = ((PyVTKMutableObject *)op)->value;
pb = Py_TYPE(op)->tp_as_buffer;
if (pb && pb->bf_getcharbuffer)
{
return Py_TYPE(op)->tp_as_buffer->bf_getcharbuffer(
op, segment, ptrptr);
}
sprintf(text, "type \'%.20s\' does not support character buffer access",
Py_TYPE(op)->tp_name);
PyErr_SetString(PyExc_TypeError, text);
return -1;
}
#endif
#if PY_VERSION_HEX >= 0x02060000
// new buffer protocol
static int PyVTKMutableObject_GetBuffer(
PyObject *self, Py_buffer *view, int flags)
{
PyObject *obj = ((PyVTKMutableObject *)self)->value;
return PyObject_GetBuffer(obj, view, flags);
}
static void PyVTKMutableObject_ReleaseBuffer(
PyObject *, Py_buffer *view)
{
PyBuffer_Release(view);
}
#endif
static PyBufferProcs PyVTKMutableObject_AsBuffer = {
#ifndef VTK_PY3K
PyVTKMutableObject_GetReadBuf, // bf_getreadbuffer
PyVTKMutableObject_GetWriteBuf, // bf_getwritebuffer
PyVTKMutableObject_GetSegCount, // bf_getsegcount
PyVTKMutableObject_GetCharBuf, // bf_getcharbuffer
#endif
#if PY_VERSION_HEX >= 0x02060000
PyVTKMutableObject_GetBuffer, // bf_getbuffer
PyVTKMutableObject_ReleaseBuffer // bf_releasebuffer
#endif
};
//--------------------------------------------------------------------
// Object protocol
static void PyVTKMutableObject_Delete(PyObject *ob)
{
Py_DECREF(((PyVTKMutableObject *)ob)->value);
PyObject_Del(ob);
}
static PyObject *PyVTKMutableObject_Repr(PyObject *ob)
{
PyObject *r = 0;
const char *name = Py_TYPE(ob)->tp_name;
PyObject *s = PyObject_Repr(((PyVTKMutableObject *)ob)->value);
if (s)
{
#ifdef VTK_PY3K
r = PyUnicode_FromFormat("%s(%U)", name, s);
#else
char textspace[128];
const char *text = PyString_AsString(s);
size_t n = strlen(name) + strlen(text) + 3;
char *cp = textspace;
if (n > 128) { cp = (char *)malloc(n); }
sprintf(cp, "%s(%s)", name, text);
r = PyString_FromString(cp);
if (n > 128) { free(cp); }
#endif
Py_DECREF(s);
}
return r;
}
static PyObject *PyVTKMutableObject_Str(PyObject *ob)
{
return PyObject_Str(((PyVTKMutableObject *)ob)->value);
}
static PyObject *PyVTKMutableObject_RichCompare(
PyObject *ob1, PyObject *ob2, int opid)
{
if (PyVTKMutableObject_Check(ob1))
{
ob1 = ((PyVTKMutableObject *)ob1)->value;
}
if (PyVTKMutableObject_Check(ob2))
{
ob2 = ((PyVTKMutableObject *)ob2)->value;
}
return PyObject_RichCompare(ob1, ob2, opid);
}
static PyObject *PyVTKMutableObject_GetAttr(PyObject *self, PyObject *attr)
{
PyObject *a = PyObject_GenericGetAttr(self, attr);
if (a || !PyErr_ExceptionMatches(PyExc_AttributeError))
{
return a;
}
PyErr_Clear();
#ifndef VTK_PY3K
char *name = PyString_AsString(attr);
int firstchar = name[0];
#elif PY_VERSION_HEX >= 0x03030000
int firstchar = '\0';
if (PyUnicode_GetLength(attr) > 0)
{
firstchar = PyUnicode_ReadChar(attr, 0);
}
#else
int firstchar = '\0';
if (PyUnicode_Check(attr) && PyUnicode_GetSize(attr) > 0)
{
firstchar = PyUnicode_AS_UNICODE(attr)[0];
}
#endif
if (firstchar != '_')
{
a = PyObject_GetAttr(((PyVTKMutableObject *)self)->value, attr);
if (a || !PyErr_ExceptionMatches(PyExc_AttributeError))
{
return a;
}
PyErr_Clear();
}
#ifdef VTK_PY3K
PyErr_Format(PyExc_AttributeError,
"'%.50s' object has no attribute '%U'",
Py_TYPE(self)->tp_name, attr);
#else
PyErr_Format(PyExc_AttributeError,
"'%.50s' object has no attribute '%.80s'",
Py_TYPE(self)->tp_name, name);
#endif
return NULL;
}
static PyObject *PyVTKMutableObject_New(
PyTypeObject *, PyObject *args, PyObject *kwds)
{
PyObject *o;
if (kwds && PyDict_Size(kwds))
{
PyErr_SetString(PyExc_TypeError,
"mutable() does not take keyword arguments");
return NULL;
}
if (PyArg_ParseTuple(args, "O:mutable", &o))
{
o = PyVTKMutableObject_CompatibleObject(o);
if (o)
{
PyVTKMutableObject *self = PyObject_New(PyVTKMutableObject, &PyVTKMutableObject_Type);
self->value = o;
return (PyObject *)self;
}
}
return NULL;
}
//--------------------------------------------------------------------
PyTypeObject PyVTKMutableObject_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"vtkCommonCorePython.mutable", // tp_name
sizeof(PyVTKMutableObject), // tp_basicsize
0, // tp_itemsize
PyVTKMutableObject_Delete, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
PyVTKMutableObject_Repr, // tp_repr
&PyVTKMutableObject_AsNumber, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
#if PY_VERSION_HEX >= 0x02060000
PyObject_HashNotImplemented, // tp_hash
#else
0, // tp_hash
#endif
0, // tp_call
PyVTKMutableObject_Str, // tp_string
PyVTKMutableObject_GetAttr, // tp_getattro
0, // tp_setattro
&PyVTKMutableObject_AsBuffer, // tp_as_buffer
#ifndef VTK_PY3K
Py_TPFLAGS_CHECKTYPES |
#endif
Py_TPFLAGS_DEFAULT, // tp_flags
PyVTKMutableObject_Doc, // tp_doc
0, // tp_traverse
0, // tp_clear
PyVTKMutableObject_RichCompare, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
PyVTKMutableObject_Methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
PyVTKMutableObject_New, // tp_new
PyObject_Del, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0, // tp_weaklist
VTK_WRAP_PYTHON_SUPPRESS_UNINITIALIZED
};
| [
"shentianweipku@gmail.com"
] | shentianweipku@gmail.com |
f55d855c68014b6c71c89ce2199e52a804020fe7 | c0836a6ec5be644f39f134fa7632d9d6c6cfa0c9 | /Lab6/Task1/main.cpp | bb5329fc5d08046a95001352cfec58d68e23c259 | [] | no_license | igordevM/Assembler-stuffs | 27cdb1ff25b89f1eb4c9cf7e172c8e9282b3af14 | c965a9f2a6d99370d956cac4688b4f83f75dcef8 | refs/heads/master | 2023-02-05T22:36:46.171976 | 2020-12-24T18:49:10 | 2020-12-24T18:49:10 | 324,214,674 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | cpp | #include <iostream>
#include <stdio.h>
int main() {
int x = 1, y = 3, z, ans;
asm(
"clc \n"
"mov %[X], %[Z] \n"
"add %[Y], %[Z] \n"
"cmp $4, %[Z] \n"
"jl F1\n"
"add $2, %[Y] \n"
"mov %[Y], %[ANS] \n"
"jmp Exit\n"
"F1:\n"
"mov %[X], %[ANS]\n"
"Exit:"
:[X]"+r"(x), [Y]"+r"(y), [Z]"+r"(z), [ANS]"+r"(ans)
);
std::cout<< "x + y = " << z <<"\nAnswer: "<< ans << '\n';
return 0;
} | [
"igordevm@gmail.com"
] | igordevm@gmail.com |
ac9f4fbbb136c5d9c5d8e732d7d6df6a5296c6e1 | 860b600ee7f413d68fc6cf68a13e8a4759c72d31 | /Server/mainwindow.h | dc7c7f027636f256b57cd554d31c8fb1842a87fc | [] | no_license | holevi96/servertest | 883e82d39af5006c6eadf8aa64f82c3a44740df1 | 8e44a92d13e4470356f87f95d6f5338d00ab6492 | refs/heads/master | 2020-08-07T08:35:36.890219 | 2019-10-07T12:22:15 | 2019-10-07T12:22:15 | 213,374,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "HelloWorldServer.h"
namespace Ui {
class MainWindow;
}
class HelloWorldServer;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void addMessage(QString Msg);
HelloWorldServer* m_pBoxServer;
private slots:
void on_pushButtonStart_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"holevi96@gmail.com"
] | holevi96@gmail.com |
e196a9bd76a35e21a4890a1e3499d9422b896aa8 | 57610d90506f9b93d2097067bbe7658e7460c2e6 | /yoketoru-unity/Temp/StagingArea/Data/il2cppOutput/t1625657544.h | 5ffb397b6a412e61a50ceca467057b6ab720f43f | [] | no_license | GEhikachu/GEhikachu.github.io | 4c10b77020b9face4d27a50e1a9f4a1434f390c1 | b9d6627a3d1145325f2a7b9cf02712fe17c8f334 | refs/heads/master | 2020-07-01T08:16:40.998434 | 2016-12-09T01:22:35 | 2016-12-09T01:22:35 | 74,089,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,312 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
struct Type_t;
struct String_t;
#include "t1196035370.h"
#include "t157015895.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
struct t1625657544 : public t1196035370
{
public:
Type_t * f2;
String_t* f3;
int32_t f4;
public:
inline static int32_t fog2() { return static_cast<int32_t>(offsetof(t1625657544, f2)); }
inline Type_t * fg2() const { return f2; }
inline Type_t ** fag2() { return &f2; }
inline void fs2(Type_t * value)
{
f2 = value;
Il2CppCodeGenWriteBarrier(&f2, value);
}
inline static int32_t fog3() { return static_cast<int32_t>(offsetof(t1625657544, f3)); }
inline String_t* fg3() const { return f3; }
inline String_t** fag3() { return &f3; }
inline void fs3(String_t* value)
{
f3 = value;
Il2CppCodeGenWriteBarrier(&f3, value);
}
inline static int32_t fog4() { return static_cast<int32_t>(offsetof(t1625657544, f4)); }
inline int32_t fg4() const { return f4; }
inline int32_t* fag4() { return &f4; }
inline void fs4(int32_t value)
{
f4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"hikapika911@gmail.com"
] | hikapika911@gmail.com |
098d680b0d43f9023c14580a7ff4238831a63feb | b9177e965cd17301428b872ef7e1183eb5da1c8c | /Lisc.cpp | 5b4d5859b0fc1bf7e728a743c9b1d6ce90da168a | [] | no_license | Dzudit/LogicGatesCpp | c5f0ce2094c8dfc71f19a472b831c28e4448a15f | 4a458939b6d6c84e7f7efba37ddcbc6009004fe5 | refs/heads/master | 2020-03-20T05:36:36.255020 | 2018-06-15T15:07:26 | 2018-06-15T15:07:26 | 137,220,453 | 0 | 0 | null | 2018-06-15T15:07:27 | 2018-06-13T13:36:58 | C++ | UTF-8 | C++ | false | false | 584 | cpp | #include "Lisc.h"
#include <iostream>
Lisc::Lisc(bool value):q(value)
{
wartosci.push_back(nullptr);
};
bool Lisc::operacja()
{
return q;
};
void Lisc::Accept( Visitator *v)
{
v->operacja(this);
}
std::vector<std::shared_ptr<Komponent>> Lisc::getVector()
{
return wartosci;
};
void Lisc::setVectorValue(int i, bool value){
q=value;
}
bool Lisc::sprawdzCzyJestemLisciem()
{
return true;
}
std::shared_ptr<Komponent> Lisc::Klonuj()
{
return std::make_shared<Lisc>(operacja());
}
std::ostream& Lisc::print(std::ostream &wyjscie)
{
return wyjscie<<"{"<<q<<"}";
}
| [
"judyta.wis@eset.pl"
] | judyta.wis@eset.pl |
adaf4a3169e6ebf034aa17044e9b3b7e735da612 | 5137216db087c50aed394248cb6d10e1cf43b29c | /original/love2d072/src/modules/physics/box2d/Source/Collision/b2BroadPhase.h | aa3ea1bed03ede3e17be610b15ec170fbbfaf5f8 | [
"Zlib"
] | permissive | shuhaowu/nottetris2 | 0dc4ecae52bb58442293b35d44fe072c5c61c73e | 8a8e7fc3bbbe4e724fa6eb64c27011a0b6e1b089 | refs/heads/master | 2020-05-04T06:25:22.064594 | 2019-04-04T02:26:08 | 2019-04-04T02:26:08 | 179,005,443 | 0 | 0 | WTFPL | 2019-04-02T05:30:51 | 2019-04-02T05:30:50 | null | UTF-8 | C++ | false | false | 4,351 | h | /*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_BROAD_PHASE_H
#define B2_BROAD_PHASE_H
/*
This broad phase uses the Sweep and Prune algorithm as described in:
Collision Detection in Interactive 3D Environments by Gino van den Bergen
Also, some ideas, such as using integral values for fast compares comes from
Bullet (http:/www.bulletphysics.com).
*/
#include "../Common/b2Settings.h"
#include "b2Collision.h"
#include "b2PairManager.h"
#include <climits>
#ifdef TARGET_FLOAT32_IS_FIXED
#define B2BROADPHASE_MAX (USHRT_MAX/2)
#else
#define B2BROADPHASE_MAX USHRT_MAX
#endif
const uint16 b2_invalid = B2BROADPHASE_MAX;
const uint16 b2_nullEdge = B2BROADPHASE_MAX;
struct b2BoundValues;
struct b2Bound
{
bool IsLower() const { return (value & 1) == 0; }
bool IsUpper() const { return (value & 1) == 1; }
uint16 value;
uint16 proxyId;
uint16 stabbingCount;
};
struct b2Proxy
{
uint16 GetNext() const { return lowerBounds[0]; }
void SetNext(uint16 next) { lowerBounds[0] = next; }
bool IsValid() const { return overlapCount != b2_invalid; }
uint16 lowerBounds[2], upperBounds[2];
uint16 overlapCount;
uint16 timeStamp;
void* userData;
};
class b2BroadPhase
{
public:
b2BroadPhase(const b2AABB& worldAABB, b2PairCallback* callback);
~b2BroadPhase();
// Use this to see if your proxy is in range. If it is not in range,
// it should be destroyed. Otherwise you may get O(m^2) pairs, where m
// is the number of proxies that are out of range.
bool InRange(const b2AABB& aabb) const;
// Create and destroy proxies. These call Flush first.
uint16 CreateProxy(const b2AABB& aabb, void* userData);
void DestroyProxy(int32 proxyId);
// Call MoveProxy as many times as you like, then when you are done
// call Commit to finalized the proxy pairs (for your time step).
void MoveProxy(int32 proxyId, const b2AABB& aabb);
void Commit();
// Get a single proxy. Returns NULL if the id is invalid.
b2Proxy* GetProxy(int32 proxyId);
// Query an AABB for overlapping proxies, returns the user data and
// the count, up to the supplied maximum count.
int32 Query(const b2AABB& aabb, void** userData, int32 maxCount);
void Validate();
void ValidatePairs();
private:
void ComputeBounds(uint16* lowerValues, uint16* upperValues, const b2AABB& aabb);
bool TestOverlap(b2Proxy* p1, b2Proxy* p2);
bool TestOverlap(const b2BoundValues& b, b2Proxy* p);
void Query(int32* lowerIndex, int32* upperIndex, uint16 lowerValue, uint16 upperValue,
b2Bound* bounds, int32 boundCount, int32 axis);
void IncrementOverlapCount(int32 proxyId);
void IncrementTimeStamp();
public:
friend class b2PairManager;
b2PairManager m_pairManager;
b2Proxy m_proxyPool[b2_maxProxies];
uint16 m_freeProxy;
b2Bound m_bounds[2][2*b2_maxProxies];
uint16 m_queryResults[b2_maxProxies];
int32 m_queryResultCount;
b2AABB m_worldAABB;
b2Vec2 m_quantizationFactor;
int32 m_proxyCount;
uint16 m_timeStamp;
static bool s_validate;
};
inline bool b2BroadPhase::InRange(const b2AABB& aabb) const
{
b2Vec2 d = b2Max(aabb.lowerBound - m_worldAABB.upperBound, m_worldAABB.lowerBound - aabb.upperBound);
return b2Max(d.x, d.y) < 0.0f;
}
inline b2Proxy* b2BroadPhase::GetProxy(int32 proxyId)
{
if (proxyId == b2_nullProxy || m_proxyPool[proxyId].IsValid() == false)
{
return NULL;
}
return m_proxyPool + proxyId;
}
#endif
| [
"shuhao@shuhaowu.com"
] | shuhao@shuhaowu.com |
046891a6035448666d04e369d14ce4055bcd5b08 | 7f296c0247edd773640d75e43f59f671235f9115 | /M_Framework/Components/Camera.h | 49522a0a8487d1f0d16f26114a59f3f39b5265e9 | [] | no_license | alpenglow93/SGA | 43007ec9c8713465e69479d278bc5d93bfb29c43 | 265241b56f834fc7b0ee4f7f830877c6a7eb7725 | refs/heads/master | 2020-03-28T04:04:14.756772 | 2019-02-11T13:56:01 | 2019-02-11T13:56:01 | 147,687,677 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,555 | h | #pragma once
#include "Component.h"
class Camera : public Component
{
public:
Camera(class Object* obj);
~Camera();
void Update();
void Render();
void SetViewOrhto(D3DXMATRIX* view, D3DXMATRIX* ortho = NULL);
D3DXMATRIX GetViewOrhto();
// Component을(를) 통해 상속됨
virtual void SetInsfector() override;
private:
struct ViewOrtho
{
ViewOrtho()
{
D3DXMatrixIdentity(&Data.View);
D3DXMatrixIdentity(&Data.Ortho);
D3D11_BUFFER_DESC bufferDesc = { 0 };
bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = sizeof(Struct);
DEVICE()->CreateBuffer(&bufferDesc, NULL, &Buffer);
}
void SetView(D3DXMATRIX view)
{
Data.View = view;
bChanged = true;
}
void SetOrtho(D3DXMATRIX ortho)
{
Data.Ortho = ortho;
bChanged = true;
}
void Change()
{
if (bChanged)
{
D3D11_MAPPED_SUBRESOURCE map;
Struct s;
D3DXMatrixTranspose(&s.View, &Data.View);
D3DXMatrixTranspose(&s.Ortho, &Data.Ortho);
DEVICECONTEXT()->Map(Buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
{
memcpy(map.pData, &s, sizeof(Struct));
}
DEVICECONTEXT()->Unmap(Buffer, 0);
}
DEVICECONTEXT()->VSSetConstantBuffers(0, 1, &Buffer);
}
D3DXMATRIX Get() { return Data.Ortho, Data.View; }
private:
struct Struct
{
D3DXMATRIX View;
D3DXMATRIX Ortho;
}Data;
ID3D11Buffer* Buffer;
bool bChanged = false;
}*Buffer;
class Transform* transform;
};
| [
"dktmzptm@gmail.com"
] | dktmzptm@gmail.com |
9b27be4deecb8054ccb6286c5187141d5edf280d | 68b0b87168151c98a48a597781405a76b4ee9ed7 | /src/rpc/rawtransaction.cpp | 0c3c7050b9254615452aedacfbf3867bb696e624 | [] | no_license | BitcoinAdultNg/BitcoinAdult | ef6aa3de57a503a3cd7eb986b3aacc81f03f075f | 19470e201df55b44586f6d4d7a8fe92b86ed7c20 | refs/heads/master | 2023-01-02T06:44:45.542108 | 2020-10-23T12:51:51 | 2020-10-23T12:51:51 | 287,327,470 | 0 | 0 | null | 2020-10-23T12:51:52 | 2020-08-13T16:21:13 | C++ | UTF-8 | C++ | false | false | 47,100 | cpp | // Copyright (c) 2019-2023 The BTAD developers
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The BITCOINADULT 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 "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "primitives/transaction.h"
#include "zpiv/deterministicmint.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "swifttx.h"
#include "uint256.h"
#include "utilmoneystr.h"
#include "zpivchain.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
std::vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
UniValue a(UniValue::VARR);
for (const CTxDestination& addr : addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
// Call into TxToUniv() in bitcoin-common to decode the transaction hex.
//
// Blockchain contextual information (confirmations and blocktime) is not
// available to code in bitcoin-common, so we query them here and push the
// data into the returned UniValue.
TxToUniv(tx, uint256(), entry);
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
UniValue getrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw std::runtime_error(
"getrawtransaction \"txid\" ( verbose \"blockhash\" )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
"If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
"3. \"blockhash\" (string, optional) The block in which to look for the transaction\n"
"\nResult (if verbose is not set or set to false):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose is set to true):\n"
"{\n"
" \"in_active_chain\": b, (bool) Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"size\" : n, (numeric) The serialized transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"BitcoinAdultaddress\" (string) BitcoinAdult address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" true")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"")
);
LOCK(cs_main);
bool in_active_chain = true;
uint256 hash = ParseHashV(params[0], "parameter 1");
CBlockIndex* blockindex = nullptr;
bool fVerbose = false;
if (!params[1].isNull()) {
fVerbose = params[1].isNum() ? (params[1].get_int() != 0) : params[1].get_bool();
}
if (!params[2].isNull()) {
uint256 blockhash = ParseHashV(params[2], "parameter 3");
BlockMap::iterator it = mapBlockIndex.find(blockhash);
if (it == mapBlockIndex.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
}
blockindex = it->second;
in_active_chain = chainActive.Contains(blockindex);
}
CTransaction tx;
uint256 hash_block;
if (!GetTransaction(hash, tx, hash_block, true, blockindex)) {
std::string errmsg;
if (blockindex) {
if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
}
errmsg = "No such transaction found in the provided block";
} else {
errmsg = fTxIndex
? "No such mempool or blockchain transaction"
: "No such mempool transaction. Use -txindex to enable blockchain transaction queries";
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
}
if (!fVerbose) {
return EncodeHexTx(tx);
}
UniValue result(UniValue::VOBJ);
if (blockindex) result.push_back(Pair("in_active_chain", in_active_chain));
TxToJSON(tx, hash_block, result);
return result;
}
#ifdef ENABLE_WALLET
UniValue listunspent(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 4)
throw std::runtime_error(
"listunspent ( minconf maxconf [\"address\",...] watchonlyconfig )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations, spendable}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of BitcoinAdult addresses to filter\n"
" [\n"
" \"address\" (string) BitcoinAdult address\n"
" ,...\n"
" ]\n"
"4. watchonlyconfig (numeric, optional, default=1) 1 = list regular unspent transactions, 2 = list only watchonly transactions, 3 = list all unspent transactions (including watchonly)\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the BitcoinAdult address\n"
" \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"redeemScript\" : \"key\", (string) the redeemscript key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in btc\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"spendable\" : true|false (boolean) Whether we have the private keys to spend this output\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\""));
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR)(UniValue::VNUM));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
std::set<CBitcoinAddress> setAddress;
if (params.size() > 2) {
UniValue inputs = params[2].get_array();
for (unsigned int inx = 0; inx < inputs.size(); inx++) {
const UniValue& input = inputs[inx];
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid BTAD address: ") + input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str());
setAddress.insert(address);
}
}
int nWatchonlyConfig = 1;
if(params.size() > 3) {
nWatchonlyConfig = params[3].get_int();
if (nWatchonlyConfig > 3 || nWatchonlyConfig < 1)
nWatchonlyConfig = 1;
}
UniValue results(UniValue::VARR);
std::vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->AvailableCoins(vecOutputs, false, NULL, false, ALL_COINS, false, nWatchonlyConfig);
for (const COutput& out : vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount", ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations", out.nDepth));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
#endif
UniValue createrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw std::runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...} ( locktime )\n"
"\nCreate a transaction spending the given inputs and sending to the given addresses.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"sequence\":n (numeric, optional) The sequence number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"address\": x.xxx (numeric, required) The key is the BitcoinAdult address, the value is the btc amount\n"
" ,...\n"
" }\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n" +
HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\""));
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM));
if (params[0].isNull() || params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = params[0].get_array();
UniValue sendTo = params[1].get_obj();
CMutableTransaction rawTx;
if (params.size() > 2 && !params[2].isNull()) {
int64_t nLockTime = params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
// set the sequence number if passed in the parameters object
const UniValue& sequenceObj = find_value(o, "sequence");
if (sequenceObj.isNum()) {
int64_t seqNr64 = sequenceObj.get_int64();
if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
else
nSequence = (uint32_t)seqNr64;
}
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
std::set<CBitcoinAddress> setAddress;
std::vector<std::string> addrList = sendTo.getKeys();
for (const std::string& name_ : addrList) {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid BTAD address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
return EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) BitcoinAdult address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\""));
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
TxToJSON(tx, 0, result);
return result;
}
UniValue decodescript(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) BitcoinAdult address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\""));
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (params[0].get_str().size() > 0) {
std::vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
entry.push_back(Pair("error", strMessage));
vErrorsRet.push_back(entry);
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw std::runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\""));
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
std::vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
std::vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
} catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
std::map<COutPoint, CScript> mapPrevOut;
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
for (const CTxIn &txbase : mergedTx.vin)
{
CTransaction tempTx;
uint256 hashBlock;
if (GetTransaction(txbase.prevout.hash, tempTx, hashBlock, true)) {
// Copy results into mapPrevOut:
mapPrevOut[txbase.prevout] = tempTx.vout[txbase.prevout.n].scriptPubKey;
}
}
}
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache& viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for (const CTxIn& txin : mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && !params[2].isNull()) {
fGivenKeys = true;
UniValue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull()) {
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" +
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut + 1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && !params[3].isNull()) {
static std::map<std::string, int> mapSigHashValues =
boost::assign::map_list_of(std::string("ALL"), int(SIGHASH_ALL))(std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))(std::string("NONE"), int(SIGHASH_NONE))(std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE | SIGHASH_ANYONECANPAY))(std::string("SINGLE"), int(SIGHASH_SINGLE))(std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY));
std::string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
if (mapPrevOut.count(txin.prevout) == 0 && (coins == NULL || !coins->IsAvailable(txin.prevout.n)))
{
TxInErrorToJSON(txin, vErrors, "Input not found");
continue;
}
} else {
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
}
const CScript& prevPubKey = (Params().NetworkID() == CBaseChainParams::REGTEST && mapPrevOut.count(txin.prevout) != 0 ? mapPrevOut[txin.prevout] : coins->vout[txin.prevout.n].scriptPubKey);
txin.scriptSig.clear();
// if this is a P2CS script, select which key to use
bool fColdStake = false;
if (prevPubKey.IsPayToColdStaking()) {
// if we have both keys, sign with the spender key
fColdStake = !bool(IsMine(keystore, prevPubKey) & ISMINE_SPENDABLE_DELEGATED);
}
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType, fColdStake);
// ... and merge in other signatures:
for (const CMutableTransaction& txv : txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
if (!vErrors.empty()) {
result.push_back(Pair("errors", vErrors));
}
return result;
}
UniValue sendrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw std::runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"3. swiftx (boolean, optional, default=false) Use SwiftX to send this transaction\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n" +
HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\""));
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
bool fSwiftX = false;
if (params.size() > 2)
fSwiftX = params[2].get_bool();
CCoinsViewCache& view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
if (fSwiftX) {
mapTxLockReq.insert(std::make_pair(tx.GetHash(), tx));
CreateNewLock(tx);
RelayTransactionLockReq(tx, true);
}
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, !fOverrideFees)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
UniValue getspentzerocoinamount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw std::runtime_error(
"getspentzerocoinamount hexstring index\n"
"\nReturns value of spent zerocoin output designated by transaction hash and input index.\n"
"\nArguments:\n"
"1. hash (hexstring) Transaction hash\n"
"2. index (int) Input index\n"
"\nResult:\n"
"\"value\" (int) Spent output value, -1 if error\n"
"\nExamples:\n" +
HelpExampleCli("getspentzerocoinamount", "78021ebf92a80dfccef1413067f1222e37535399797cce029bb40ad981131706 0"));
LOCK(cs_main);
uint256 txHash = ParseHashV(params[0], "parameter 1");
int inputIndex = params[1].get_int();
if (inputIndex < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter for transaction input");
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(txHash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
if (inputIndex >= (int)tx.vin.size())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter for transaction input");
const CTxIn& input = tx.vin[inputIndex];
if (!input.IsZerocoinSpend())
return -1;
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(input);
CAmount nValue = libzerocoin::ZerocoinDenominationToAmount(spend.getDenomination());
return FormatMoney(nValue);
}
#ifdef ENABLE_WALLET
UniValue createrawzerocoinstake(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"createrawzerocoinstake mint_input \n"
"\nCreates raw zBTAD coinstakes (without MN output).\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. mint_input (hex string, required) serial hash of the mint used as input\n"
"\nResult:\n"
"{\n"
" \"hex\": \"xxx\", (hex string) raw coinstake transaction\n"
" \"private-key\": \"xxx\" (hex string) private key of the input mint [needed to\n"
" sign a block with this stake]"
"}\n"
"\nExamples\n" +
HelpExampleCli("createrawzerocoinstake", "0d8c16eee7737e3cc1e4e70dc006634182b175e039700931283b202715a0818f") +
HelpExampleRpc("createrawzerocoinstake", "0d8c16eee7737e3cc1e4e70dc006634182b175e039700931283b202715a0818f"));
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
if(sporkManager.IsSporkActive(SPORK_16_ZEROCOIN_MAINTENANCE_MODE))
throw JSONRPCError(RPC_WALLET_ERROR, "zBTAD is currently disabled due to maintenance.");
std::string serial_hash = params[0].get_str();
if (!IsHex(serial_hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex serial hash");
EnsureWalletIsUnlocked();
uint256 hashSerial(serial_hash);
CZerocoinMint input_mint;
if (!pwalletMain->GetMint(hashSerial, input_mint)) {
std::string strErr = "Failed to fetch mint associated with serial hash " + serial_hash;
throw JSONRPCError(RPC_WALLET_ERROR, strErr);
}
CMutableTransaction coinstake_tx;
// create the zerocoinmint output (one spent denom + three 1-zBTAD denom)
libzerocoin::CoinDenomination staked_denom = input_mint.GetDenomination();
std::vector<CTxOut> vOutMint(5);
// Mark coin stake transaction
CScript scriptEmpty;
scriptEmpty.clear();
vOutMint[0] = CTxOut(0, scriptEmpty);
CDeterministicMint dMint;
if (!pwalletMain->CreateZPIVOutPut(staked_denom, vOutMint[1], dMint))
throw JSONRPCError(RPC_WALLET_ERROR, "failed to create new zpiv output");
for (int i=2; i<5; i++) {
if (!pwalletMain->CreateZPIVOutPut(libzerocoin::ZQ_ONE, vOutMint[i], dMint))
throw JSONRPCError(RPC_WALLET_ERROR, "failed to create new zpiv output");
}
coinstake_tx.vout = vOutMint;
//hash with only the output info in it to be used in Signature of Knowledge
uint256 hashTxOut = coinstake_tx.GetHash();
CZerocoinSpendReceipt receipt;
// create the zerocoinspend input
CTxIn newTxIn;
// !TODO: mint checks
if (!pwalletMain->MintToTxIn(input_mint, hashTxOut, newTxIn, receipt, libzerocoin::SpendType::STAKE))
throw JSONRPCError(RPC_WALLET_ERROR, "failed to create zc-spend stake input");
coinstake_tx.vin.push_back(newTxIn);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("hex", EncodeHexTx(coinstake_tx)));
CPrivKey pk = input_mint.GetPrivKey();
CKey key;
key.SetPrivKey(pk, true);
ret.push_back(Pair("private-key", HexStr(key)));
return ret;
}
UniValue createrawzerocoinpublicspend(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"createrawzerocoinpublicspend mint_input \n"
"\nCreates raw zBTAD public spend.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. mint_input (hex string, required) serial hash of the mint used as input\n"
"2. \"address\" (string, optional, default=change) Send to specified address or to a new change address.\n"
"\nResult:\n"
"{\n"
" \"hex\": \"xxx\", (hex string) raw public spend signed transaction\n"
"}\n"
"\nExamples\n" +
HelpExampleCli("createrawzerocoinpublicspend", "0d8c16eee7737e3cc1e4e70dc006634182b175e039700931283b202715a0818f") +
HelpExampleRpc("createrawzerocoinpublicspend", "0d8c16eee7737e3cc1e4e70dc006634182b175e039700931283b202715a0818f"));
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string serial_hash = params[0].get_str();
if (!IsHex(serial_hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex serial hash");
std::string address_str = "";
CBitcoinAddress address;
CBitcoinAddress* addr_ptr = nullptr;
if (params.size() > 1) {
address_str = params[1].get_str();
address = CBitcoinAddress(address_str);
if(!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BTAD address");
addr_ptr = &address;
}
EnsureWalletIsUnlocked();
uint256 hashSerial(serial_hash);
CZerocoinMint input_mint;
if (!pwalletMain->GetMint(hashSerial, input_mint)) {
std::string strErr = "Failed to fetch mint associated with serial hash " + serial_hash;
throw JSONRPCError(RPC_WALLET_ERROR, strErr);
}
CAmount nAmount = input_mint.GetDenominationAsAmount();
std::vector<CZerocoinMint> vMintsSelected = std::vector<CZerocoinMint>(1,input_mint);
// create the spend
CWalletTx rawTx;
CZerocoinSpendReceipt receipt;
CReserveKey reserveKey(pwalletMain);
std::vector<CDeterministicMint> vNewMints;
std::list<std::pair<CBitcoinAddress*, CAmount>> outputs;
if (addr_ptr) {
outputs.push_back(std::pair<CBitcoinAddress*, CAmount>(addr_ptr, nAmount));
}
if (!pwalletMain->CreateZerocoinSpendTransaction(nAmount, rawTx, reserveKey, receipt, vMintsSelected, vNewMints, false, true, outputs, nullptr, true))
throw JSONRPCError(RPC_WALLET_ERROR, receipt.GetStatusMessage());
// output the raw transaction
return EncodeHexTx(rawTx);
}
#endif
| [
"68110517+BitcoinAdultNg@users.noreply.github.com"
] | 68110517+BitcoinAdultNg@users.noreply.github.com |
0f85b4b5f3af63874a35dd241f2f81bcda2c4770 | aa65dbff3116e492746ab948a27dfa8fd1c68f09 | /study/c++_primer_plus/chapter4/7pointer_freemem/sizeofpointer.cpp | 770fc28c8d3790493b3a7fb9f68fd426279dd8b5 | [] | no_license | rambog/git | 27531c4773122c229d1537a03df4620aea829481 | a9447dae330ee0dccab5533d0b967e7150b9fc0c | refs/heads/master | 2021-07-23T14:28:58.959184 | 2019-01-17T15:01:18 | 2019-01-17T15:01:18 | 153,124,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp | /*======================================================================
* filename: sizeofpointer.cpp
* author: rambogui
* data: 2018-11-26 09:43:39
======================================================================*/
#include <iostream>
int main(int argc, char *argv[])
{
using namespace std;
cout << sizeof(char *) << endl;
cout << sizeof(int *) << endl;
cout << sizeof(short *) << endl;
cout << sizeof(long long *) << endl;
cout << sizeof(wchar_t *) << endl;
cout << sizeof(long double *) << endl;
cout << sizeof(float *) << endl;
return 0;
}
| [
"576381563@qq.com"
] | 576381563@qq.com |
676d7f486e00aada1ef887569af742d75615495b | 9f5b8b72b24f22e5e9e031013d95d217ce3e8d5f | /devel/include/rowcrop_scripts/Num.h | c287f732ad1232c54939ea3907f8569afd4780a3 | [] | no_license | bigkricket/row_crop_navigator | 7ed0ec0302d68cc7d3be37bbe97409a03eea4182 | ef4d796cf23567e4ca992ae1149a9565147c281c | refs/heads/master | 2023-02-27T12:47:39.905890 | 2021-02-08T07:56:52 | 2021-02-08T07:56:52 | 335,496,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,464 | h | // Generated by gencpp from file rowcrop_scripts/Num.msg
// DO NOT EDIT!
#ifndef ROWCROP_SCRIPTS_MESSAGE_NUM_H
#define ROWCROP_SCRIPTS_MESSAGE_NUM_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace rowcrop_scripts
{
template <class ContainerAllocator>
struct Num_
{
typedef Num_<ContainerAllocator> Type;
Num_()
: num(0) {
}
Num_(const ContainerAllocator& _alloc)
: num(0) {
(void)_alloc;
}
typedef int64_t _num_type;
_num_type num;
typedef boost::shared_ptr< ::rowcrop_scripts::Num_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::rowcrop_scripts::Num_<ContainerAllocator> const> ConstPtr;
}; // struct Num_
typedef ::rowcrop_scripts::Num_<std::allocator<void> > Num;
typedef boost::shared_ptr< ::rowcrop_scripts::Num > NumPtr;
typedef boost::shared_ptr< ::rowcrop_scripts::Num const> NumConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::rowcrop_scripts::Num_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::rowcrop_scripts::Num_<ContainerAllocator> >::stream(s, "", v);
return s;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator==(const ::rowcrop_scripts::Num_<ContainerAllocator1> & lhs, const ::rowcrop_scripts::Num_<ContainerAllocator2> & rhs)
{
return lhs.num == rhs.num;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator!=(const ::rowcrop_scripts::Num_<ContainerAllocator1> & lhs, const ::rowcrop_scripts::Num_<ContainerAllocator2> & rhs)
{
return !(lhs == rhs);
}
} // namespace rowcrop_scripts
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsMessage< ::rowcrop_scripts::Num_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::rowcrop_scripts::Num_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::rowcrop_scripts::Num_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::rowcrop_scripts::Num_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::rowcrop_scripts::Num_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::rowcrop_scripts::Num_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::rowcrop_scripts::Num_<ContainerAllocator> >
{
static const char* value()
{
return "57d3c40ec3ac3754af76a83e6e73127a";
}
static const char* value(const ::rowcrop_scripts::Num_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x57d3c40ec3ac3754ULL;
static const uint64_t static_value2 = 0xaf76a83e6e73127aULL;
};
template<class ContainerAllocator>
struct DataType< ::rowcrop_scripts::Num_<ContainerAllocator> >
{
static const char* value()
{
return "rowcrop_scripts/Num";
}
static const char* value(const ::rowcrop_scripts::Num_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::rowcrop_scripts::Num_<ContainerAllocator> >
{
static const char* value()
{
return "int64 num\n"
;
}
static const char* value(const ::rowcrop_scripts::Num_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::rowcrop_scripts::Num_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.num);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct Num_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::rowcrop_scripts::Num_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rowcrop_scripts::Num_<ContainerAllocator>& v)
{
s << indent << "num: ";
Printer<int64_t>::stream(s, indent + " ", v.num);
}
};
} // namespace message_operations
} // namespace ros
#endif // ROWCROP_SCRIPTS_MESSAGE_NUM_H
| [
"perezben37@gmail.com"
] | perezben37@gmail.com |
82318ba28fbb2e2723d6e3e9404318e4511e2e9d | f15a06ce734ab59bf9a027a74c6511949e44ab18 | /leetcode/leetcode/186.h | e0ba0afe8c317d113c52e931e86c64bfc48058bf | [] | no_license | eescueta/leetcode | a8003c95bd536668d2620e65d5a6df206466b898 | 57575be0a3bf0f7e1f676df779621cd46699b732 | refs/heads/master | 2020-09-17T12:10:25.771503 | 2017-04-14T22:54:00 | 2017-04-14T22:54:00 | 66,740,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | h | #pragma once
#include <vector>
#include <iostream>
#include <map>
#include <algorithm>
#include <stack>
#include <string>
#include <queue>
#include "Solution.h"
using namespace std;
/*
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
*/
void reverseWords(string &s) {
reverse(s.begin(), s.end());
int startIdx = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == ' ')
{
reverse(s.begin() + startIdx, s.begin() + i);
startIdx = i + 1;
}
else if (i == s.length() - 1)
reverse(s.begin() + startIdx, s.end());
}
} | [
"earl.escueta@intel.com"
] | earl.escueta@intel.com |
84ceb12ec571ba60e3d56729d0c22b93991b6d58 | 88dcae753f2477ae102f832526106493b5de5dbf | /src/MahonyFilter.cpp | f459e6d8762e877504373fbb4211ac2f0b53a305 | [] | no_license | herzig/dual_mpu9250_teensy | 3cc6c18a1ccf9b43726cbbad822a90f872ff3235 | 0a8a99fdc8da04f562f8605292b03d0ec877a9b1 | refs/heads/master | 2023-01-11T08:22:10.292536 | 2020-11-07T19:17:05 | 2020-11-07T19:17:05 | 310,915,541 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,991 | cpp | #include "MahonyFilter.h"
MahonyFilter::MahonyFilter()
{
}
void MahonyFilter::update(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz, float deltat)
{
// short name local variable for readability
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3];
float norm;
float hx, hy, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
float pa, pb, pc;
// Auxiliary variables to avoid repeated arithmetic
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Normalise accelerometer measurement
norm = sqrt(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // Handle NaN
norm = 1.0f / norm; // Use reciprocal for division
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrt(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // Handle NaN
norm = 1.0f / norm; // Use reciprocal for division
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);
hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);
bx = sqrt((hx * hx) + (hy * hy));
bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);
// Estimated direction of gravity and magnetic field
vx = 2.0f * (q2q4 - q1q3);
vy = 2.0f * (q1q2 + q3q4);
vz = q1q1 - q2q2 - q3q3 + q4q4;
wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);
wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);
wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);
// Error is cross product between estimated direction and measured direction of gravity
ex = (ay * vz - az * vy) + (my * wz - mz * wy);
ey = (az * vx - ax * vz) + (mz * wx - mx * wz);
ez = (ax * vy - ay * vx) + (mx * wy - my * wx);
if (Ki > 0.0f)
{
eInt[0] += ex; // accumulate integral error
eInt[1] += ey;
eInt[2] += ez;
}
else
{
eInt[0] = 0.0f; // prevent integral wind up
eInt[1] = 0.0f;
eInt[2] = 0.0f;
}
// Apply feedback terms
gx = gx + Kp * ex + Ki * eInt[0];
gy = gy + Kp * ey + Ki * eInt[1];
gz = gz + Kp * ez + Ki * eInt[2];
// Integrate rate of change of quaternion
pa = q2;
pb = q3;
pc = q4;
q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * deltat);
q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * deltat);
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * deltat);
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * deltat);
// Normalise quaternion
norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);
norm = 1.0f / norm;
q[0] = q1 * norm;
q[1] = q2 * norm;
q[2] = q3 * norm;
q[3] = q4 * norm;
} | [
"ivoherzig@gmail.com"
] | ivoherzig@gmail.com |
f785b2a5e0e3b7764142a64e91bf034206037358 | 9fad4848e43f4487730185e4f50e05a044f865ab | /src/chrome/browser/extensions/api/chrome_extensions_api_client.cc | f2295a5c8dec5cb874b7a06e01df0c2d7b371546 | [
"BSD-3-Clause"
] | permissive | dummas2008/chromium | d1b30da64f0630823cb97f58ec82825998dbb93e | 82d2e84ce3ed8a00dc26c948219192c3229dfdaa | refs/heads/master | 2020-12-31T07:18:45.026190 | 2016-04-14T03:17:45 | 2016-04-14T03:17:45 | 56,194,439 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,610 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/chrome_extensions_api_client.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/memory/ptr_util.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/chrome_device_permissions_prompt.h"
#include "chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h"
#include "chrome/browser/extensions/api/declarative_content/default_content_predicate_evaluators.h"
#include "chrome/browser/extensions/api/management/chrome_management_api_delegate.h"
#include "chrome/browser/extensions/api/storage/managed_value_store_cache.h"
#include "chrome/browser/extensions/api/storage/sync_value_store_cache.h"
#include "chrome/browser/extensions/api/web_request/chrome_extension_web_request_event_router_delegate.h"
#include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
#include "chrome/browser/favicon/favicon_utils.h"
#include "chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.h"
#include "chrome/browser/guest_view/chrome_guest_view_manager_delegate.h"
#include "chrome/browser/guest_view/extension_options/chrome_extension_options_guest_delegate.h"
#include "chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_guest_delegate.h"
#include "chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.h"
#include "chrome/browser/guest_view/web_view/chrome_web_view_permission_helper_delegate.h"
#include "chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.h"
#include "components/pdf/browser/pdf_web_contents_helper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/api/virtual_keyboard_private/virtual_keyboard_delegate.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h"
#endif
#if defined(ENABLE_PRINTING)
#if defined(ENABLE_PRINT_PREVIEW)
#include "chrome/browser/printing/print_preview_message_handler.h"
#include "chrome/browser/printing/print_view_manager.h"
#else
#include "chrome/browser/printing/print_view_manager_basic.h"
#endif // defined(ENABLE_PRINT_PREVIEW)
#endif // defined(ENABLE_PRINTING)
namespace extensions {
ChromeExtensionsAPIClient::ChromeExtensionsAPIClient() {}
ChromeExtensionsAPIClient::~ChromeExtensionsAPIClient() {}
void ChromeExtensionsAPIClient::AddAdditionalValueStoreCaches(
content::BrowserContext* context,
const scoped_refptr<ValueStoreFactory>& factory,
const scoped_refptr<base::ObserverListThreadSafe<SettingsObserver>>&
observers,
std::map<settings_namespace::Namespace, ValueStoreCache*>* caches) {
// Add support for chrome.storage.sync.
(*caches)[settings_namespace::SYNC] =
new SyncValueStoreCache(factory, observers, context->GetPath());
// Add support for chrome.storage.managed.
(*caches)[settings_namespace::MANAGED] =
new ManagedValueStoreCache(context, factory, observers);
}
void ChromeExtensionsAPIClient::AttachWebContentsHelpers(
content::WebContents* web_contents) const {
favicon::CreateContentFaviconDriverForWebContents(web_contents);
#if defined(ENABLE_PRINTING)
#if defined(ENABLE_PRINT_PREVIEW)
printing::PrintViewManager::CreateForWebContents(web_contents);
printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
#else
printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
#endif // defined(ENABLE_PRINT_PREVIEW)
#endif // defined(ENABLE_PRINTING)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents, std::unique_ptr<pdf::PDFWebContentsHelperClient>(
new ChromePDFWebContentsHelperClient()));
extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
web_contents);
}
AppViewGuestDelegate* ChromeExtensionsAPIClient::CreateAppViewGuestDelegate()
const {
return new ChromeAppViewGuestDelegate();
}
ExtensionOptionsGuestDelegate*
ChromeExtensionsAPIClient::CreateExtensionOptionsGuestDelegate(
ExtensionOptionsGuest* guest) const {
return new ChromeExtensionOptionsGuestDelegate(guest);
}
std::unique_ptr<guest_view::GuestViewManagerDelegate>
ChromeExtensionsAPIClient::CreateGuestViewManagerDelegate(
content::BrowserContext* context) const {
return base::WrapUnique(new ChromeGuestViewManagerDelegate(context));
}
std::unique_ptr<MimeHandlerViewGuestDelegate>
ChromeExtensionsAPIClient::CreateMimeHandlerViewGuestDelegate(
MimeHandlerViewGuest* guest) const {
return base::WrapUnique(new ChromeMimeHandlerViewGuestDelegate());
}
WebViewGuestDelegate* ChromeExtensionsAPIClient::CreateWebViewGuestDelegate(
WebViewGuest* web_view_guest) const {
return new ChromeWebViewGuestDelegate(web_view_guest);
}
WebViewPermissionHelperDelegate* ChromeExtensionsAPIClient::
CreateWebViewPermissionHelperDelegate(
WebViewPermissionHelper* web_view_permission_helper) const {
return new ChromeWebViewPermissionHelperDelegate(web_view_permission_helper);
}
WebRequestEventRouterDelegate*
ChromeExtensionsAPIClient::CreateWebRequestEventRouterDelegate() const {
return new ChromeExtensionWebRequestEventRouterDelegate();
}
scoped_refptr<ContentRulesRegistry>
ChromeExtensionsAPIClient::CreateContentRulesRegistry(
content::BrowserContext* browser_context,
RulesCacheDelegate* cache_delegate) const {
return scoped_refptr<ContentRulesRegistry>(
new ChromeContentRulesRegistry(
browser_context,
cache_delegate,
base::Bind(&CreateDefaultContentPredicateEvaluators,
base::Unretained(browser_context))));
}
std::unique_ptr<DevicePermissionsPrompt>
ChromeExtensionsAPIClient::CreateDevicePermissionsPrompt(
content::WebContents* web_contents) const {
return base::WrapUnique(new ChromeDevicePermissionsPrompt(web_contents));
}
std::unique_ptr<VirtualKeyboardDelegate>
ChromeExtensionsAPIClient::CreateVirtualKeyboardDelegate() const {
#if defined(OS_CHROMEOS)
return base::WrapUnique(new ChromeVirtualKeyboardDelegate());
#else
return nullptr;
#endif
}
ManagementAPIDelegate* ChromeExtensionsAPIClient::CreateManagementAPIDelegate()
const {
return new ChromeManagementAPIDelegate;
}
} // namespace extensions
| [
"dummas@163.com"
] | dummas@163.com |
ad5adc8845cc18ce4d1ffae39360bcc17f35dad1 | e5555acd4f5fd084f346bb5af0945280cc68949d | /4 sem/Project/trainSVM.h | 30c041c6509cd659b65ec2f4dd5bc786eeaa0ec9 | [] | no_license | Binpord/Informatics | 7250ac95490403302ba55d86757320465737ae8c | ecc47fbe07efcab8509687e8e666aa603bfc7b52 | refs/heads/master | 2021-06-19T05:40:53.555650 | 2017-06-13T10:21:08 | 2017-06-13T10:21:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 186 | h | #include "precompiled_headers.h"
void trainSVM(std::string);
void GetTrainingFiles(std::string);
std::vector<std::string> GetListFiles(std::string);
#ifdef __DEBUG
void Print();
#endif
| [
"vadimsh853@gmail.com"
] | vadimsh853@gmail.com |
5340186bedd70f6e40210afa2a2a3f232064c463 | 3aeec367b34cfc2965328f7552584dde36b69457 | /src/predict_pexel.hh | d2484f24487caefec9586b965df5f7b0e66dd6a4 | [
"MIT"
] | permissive | wwood/exportpred | b6adc828a00815ee412f7e7f679940ef3418ba66 | 55238e5f06d7837b27899cd51bc3f3763d2233c8 | refs/heads/master | 2021-01-23T03:52:51.980820 | 2012-07-24T13:02:30 | 2012-07-24T13:02:30 | 5,165,611 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 355 | hh | #ifndef PREDICT_PEXEL_HH_INCLUDED
#define PREDICT_PEXEL_HH_INCLUDED
#include <string>
#include <utility>
#include <GHMM/ghmm.hh>
#define RLE_PATTERN
#define KLD_PATTERN
// #define VERSION 1
#define VERSION 2
// #define SIGNALP_MODEL
// #define HALDAR_MOTIF
#define ARRAYLEN(x) (sizeof(x) / sizeof(x[0]))
#define ENDOF(x) ((x) + ARRAYLEN(x))
#endif
| [
"donttrustben@gmail.com"
] | donttrustben@gmail.com |
ef2e86913a3d5ce037a4b935d2dabc9b7cabd964 | 9ff99814bac539695fe601306be65ace79df546d | /吉田学園情報ビジネス専門学校 荒谷由朗/06_QUIETEXECUTION/00_制作環境/input.cpp | 96f8c61be0c110f95e9d8f92df37d99609668f48 | [] | no_license | YoshiroAraya/Yoshidagakuen_ArayaYoshiro | ccacac44557a103e0406e956dbdb9e60e99756e8 | 790f61425f3104ae7a33c0fef7c751de095cec83 | refs/heads/master | 2022-01-26T21:13:32.953523 | 2019-06-18T02:21:28 | 2019-06-18T02:21:28 | 185,294,374 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 24,139 | cpp | //=============================================================================
//
// 入力処理 [input.cpp]
// Author : 荒谷由朗
//
//=============================================================================
#include "input.h"
#include "debuglog.h"
#include "manager.h"
//*****************************************************************************
// マクロ定義
//*****************************************************************************
#define DI_JOY_I_INPUT (1000) // スティックの方向入力受付を行う範囲
//*****************************************************************************
// プロトタイプ宣言
//*****************************************************************************
//*****************************************************************************
// 静的メンバ変数
//*****************************************************************************
LPDIRECTINPUT8 CInput::m_pInput = NULL;
D3DXVECTOR3 CInputMouse::m_MousePos = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
//===============================================================================
// デフォルトコンストラクタ
//===============================================================================
CInput::CInput()
{
m_pDevice = NULL;
}
//===============================================================================
// デストラクタ
//===============================================================================
CInput::~CInput()
{
}
//=============================================================================
// 初期化処理
//=============================================================================
HRESULT CInput::Init(HINSTANCE hInstance, HWND hWnd)
{
// NULLチェック
if (m_pInput == NULL)
{// DirectInputオブジェクトの生成
if (FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pInput, NULL)))
{
return E_FAIL;
}
}
return S_OK;
}
//=============================================================================
// 終了処理
//=============================================================================
void CInput::Uninit(void)
{
// 入力デバイス(キーボード)の開放
if (m_pDevice != NULL)
{
m_pDevice->Unacquire(); // キーボードへのアクセス権を放棄
m_pDevice->Release();
m_pDevice = NULL;
}
// DirectInputオブジェクトの開放
if (m_pInput != NULL)
{
m_pInput->Release();
m_pInput = NULL;
}
}
//=============================================================================
// 更新処理
//=============================================================================
void CInput::Update(void)
{
}
//********************************************************************************************************
//ここから派生クラスのキーボード
//********************************************************************************************************
//===============================================================================
// キーボードのデフォルトコンストラクタ
//===============================================================================
CInputKeyBoard::CInputKeyBoard()
{
// キー情報のクリア
for (int nCnt = 0; nCnt < NUM_KEY_MAX; nCnt++)
{
m_aKeyState[nCnt] = 0; // キーボードの入力情報(プレス情報)
m_aKeyStateTrigger[nCnt] = 0; // キーボードの入力情報 (トリガー情報)
}
}
//===============================================================================
// キーボードのデストラクタ
//===============================================================================
CInputKeyBoard::~CInputKeyBoard()
{
}
//=============================================================================
// キーボードの初期化処理
//=============================================================================
HRESULT CInputKeyBoard::Init(HINSTANCE hInstance, HWND hWnd)
{
CInput::Init(hInstance, hWnd);
// 入力デバイス(キーボード)の生成
if (FAILED(m_pInput->CreateDevice(GUID_SysKeyboard, &m_pDevice, NULL)))
{
return E_FAIL;
}
// データフォーマットを設定
if (FAILED(m_pDevice->SetDataFormat(&c_dfDIKeyboard)))
{
return E_FAIL;
}
// 協調モードを設定
if (FAILED(m_pDevice->SetCooperativeLevel(hWnd, (DISCL_FOREGROUND | DISCL_NONEXCLUSIVE))))
{
return E_FAIL;
}
// キーボードへのアクセス権を獲得(入力制御開始)
m_pDevice->Acquire();
return S_OK;
}
//=============================================================================
// キーボードの終了処理
//=============================================================================
void CInputKeyBoard::Uninit(void)
{
CInput::Uninit();
}
//=============================================================================
// キーボードの更新処理
//=============================================================================
void CInputKeyBoard::Update(void)
{
BYTE aKeyState[NUM_KEY_MAX];
int nCntKey;
// 入力デバイスからデータを取得
if (SUCCEEDED(m_pDevice->GetDeviceState(sizeof(aKeyState), &aKeyState[0])))
{
for (nCntKey = 0; nCntKey < NUM_KEY_MAX; nCntKey++)
{
m_aKeyStateTrigger[nCntKey] = (m_aKeyState[nCntKey] ^ aKeyState[nCntKey]) & aKeyState[nCntKey]; // ※トリガーのときは一番上
m_aKeyState[nCntKey] = aKeyState[nCntKey]; // キーボードの入力情報保存
}
}
else
{
m_pDevice->Acquire(); // キーボードへのアクセス権を獲得
}
}
//===============================================================================
// キーボードのクリエイト
//===============================================================================
CInputKeyBoard *CInputKeyBoard::Create(HINSTANCE hInstance, HWND hWnd)
{
CInputKeyBoard *pCInputKeyBoard = NULL;
// NULLチェック
if (pCInputKeyBoard == NULL)
{
// 動的確保
pCInputKeyBoard = new CInputKeyBoard;
// NULLチェック
if (pCInputKeyBoard != NULL)
{
// 初期化処理
pCInputKeyBoard->Init(hInstance, hWnd);
}
else
{// 警告文
MessageBox(0, "警告:メモリがないです", "警告", MB_OK);
}
}
else
{//警告文
MessageBox(0, "警告:何かが入ってます", "警告", MB_OK);
}
return pCInputKeyBoard;
}
//=========================================================================================================================
// キーボードの入力情報(プレス情報)を取得
//=========================================================================================================================
bool CInputKeyBoard::GetKeyboardPress(int nKey)
{
return (m_aKeyState[nKey] & 0x80) ? true : false;
}
//=========================================================================================================================
// キーボードの入力情報(トリガー情報)を取得
//=========================================================================================================================
bool CInputKeyBoard::GetKeyboardTrigger(int nKey)
{
return (m_aKeyStateTrigger[nKey] & 0x80) ? true : false;
}
//=========================================================================================================================
// キーボードの入力情報(全ボタン情報)を取得
//=========================================================================================================================
bool CInputKeyBoard::GetKeyboardAny(int nNumber)
{
if (nNumber == 1)
{
for (int nCount = 0; nCount < NUM_KEY_MAX; nCount++)
{
if (m_aKeyStateTrigger[nCount] == 0x80)
{
return true;
}
}
}
return false;
}
//********************************************************************************************************
//ここから派生クラスのマウス
//********************************************************************************************************
//===============================================================================
// マウスのデフォルトコンストラクタ
//===============================================================================
CInputMouse::CInputMouse()
{
// キー情報のクリア
for (int nCnt = 0; nCnt < NUM_MOUSE_MAX; nCnt++)
{
m_moveRect; // 画面上で動ける範囲
m_x = 0; // X座標
m_y = 0; // Y座標
m_lButton = 0; // 左ボタン
m_rButton = 0; // 右ボタン
m_cButton = 0; // 真ん中ボタン
m_moveAdd = 0; // 移動量
m_imgRect; // マウス用画像矩形
m_imgWidth = 0; // マウス画像幅
m_imgHeight = 0; // マウス画像高さ
m_MousePos = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
m_Pos, m_WPos;
m_MouseState;
m_MouseStatePress = {}; // マウスの入力情報(プレス情報)
m_MouseStateTrigger = {}; // マウスの入力情報(トリガー情報)
m_MouseStateRelease = {}; // マウスの入力情報(リリース情報
}
}
//===============================================================================
// マウスのデストラクタ
//===============================================================================
CInputMouse::~CInputMouse()
{
}
//=============================================================================
// マウスの初期化処理
//=============================================================================
HRESULT CInputMouse::Init(HINSTANCE hInstance, HWND hWnd)
{
CInput::Init(hInstance, hWnd);
// DirectInputオブジェクトの生成
if (FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pInput, NULL)))
{
return E_FAIL;
}
// 入力デバイス(キーボード)の生成
if (FAILED(m_pInput->CreateDevice(GUID_SysMouse, &m_pDevice, NULL)))
{
return E_FAIL;
}
// データフォーマットを設定
if (FAILED(m_pDevice->SetDataFormat(&c_dfDIMouse2)))
{
return E_FAIL;
}
// 協調モードを設定
if (FAILED(m_pDevice->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)))
{
return E_FAIL;
}
// 軸モードを設定(相対値モードに設定)
DIPROPDWORD diprop;
diprop.diph.dwSize = sizeof(diprop);
diprop.diph.dwHeaderSize = sizeof(diprop.diph);
diprop.diph.dwObj = 0;
diprop.diph.dwHow = DIPH_DEVICE;
diprop.dwData = DIPROPAXISMODE_REL;
//diprop.dwData = DIPROPAXISMODE_ABS; // 絶対値モードの場合
if (FAILED(m_pDevice->SetProperty(DIPROP_AXISMODE, &diprop.diph)))
{
return E_FAIL;
}
// マウスへのアクセス権を獲得(入力制御開始)
m_pDevice->Acquire();
return S_OK;
}
//=============================================================================
// マウスの終了処理
//=============================================================================
void CInputMouse::Uninit(void)
{
CInput::Uninit();
}
//=============================================================================
// マウスの更新処理
//=============================================================================
void CInputMouse::Update(void)
{
// 変数宣言
int nCntMouse;
POINT pt;
GetCursorPos(&pt);
// POINT型をD3DXVECTOR3型の物に代入する
m_MousePos = D3DXVECTOR3((FLOAT)pt.x, (FLOAT)pt.y, 0.0f);
// 入力デバイスからデータを取得
if (SUCCEEDED(m_pDevice->GetDeviceState(sizeof(m_MouseState), &m_MouseState)))
{
for (nCntMouse = 0; nCntMouse < NUM_MOUSE_MAX; nCntMouse++)
{
m_MouseStateRelease.rgbButtons[nCntMouse] = (m_MouseStatePress.rgbButtons[nCntMouse] ^ m_MouseState.rgbButtons[nCntMouse]) & m_MouseStatePress.rgbButtons[nCntMouse];
m_MouseStateTrigger.rgbButtons[nCntMouse] = (m_MouseStatePress.rgbButtons[nCntMouse] ^ m_MouseState.rgbButtons[nCntMouse]) & m_MouseState.rgbButtons[nCntMouse];
m_MouseStatePress.rgbButtons[nCntMouse] = m_MouseState.rgbButtons[nCntMouse];
}
}
else
{
m_pDevice->Acquire();
}
CManager::m_pDebuglog->Print(1, "マウス ; %0.1f,%0.1f,%0.1f\n", m_MousePos.x, m_MousePos.y, m_MousePos.z);
}
//===============================================================================
// マウスのクリエイト
//===============================================================================
CInputMouse *CInputMouse::Create(HINSTANCE hInstance, HWND hWnd)
{
CInputMouse *pCInputMouse = NULL;
// NULLチェック
if (pCInputMouse == NULL)
{
// 動的確保
pCInputMouse = new CInputMouse;
// NULLチェック
if (pCInputMouse != NULL)
{
// 初期化処理
pCInputMouse->Init(hInstance, hWnd);
}
else
{// 警告文
MessageBox(0, "警告:メモリがないです", "警告", MB_OK);
}
}
else
{// 警告文
MessageBox(0, "警告:何かが入ってます", "警告", MB_OK);
}
return pCInputMouse;
}
//=========================================================================================================================
// マウスの入力情報(プレス情報)を取得
//=========================================================================================================================
bool CInputMouse::GetMousePress(int nKey)
{
return (m_MouseStatePress.rgbButtons[nKey] & 0x80) ? true : false;
}
//=========================================================================================================================
// マウスの入力情報(トリガー情報)を取得
//=========================================================================================================================
bool CInputMouse::GetMouseTrigger(int nKey)
{
return (m_MouseStateTrigger.rgbButtons[nKey] & 0x80) ? true : false;
}
//=========================================================================================================================
// マウスの入力情報(リリース情報)を取得
//=========================================================================================================================
bool CInputMouse::GetMouseRelease(int nKey)
{
return (m_MouseStateRelease.rgbButtons[nKey] & 0x80) ? true : false;
}
//********************************************************************************************************
//ここから派生クラスのジョイパッド
//********************************************************************************************************
//=============================================================================
//コントローラークラス コンストラクタ
//=============================================================================
CInputJoypad::CInputJoypad()
{
// キー情報をクリア
for (int nCnt = 0; nCnt < NUM_BUTTON_MAX; nCnt++)
{
m_aKeyState[nCnt] = 0;
m_aKeyStateTrigger[nCnt] = 0;
}
}
//=============================================================================
//コントローラークラス デストラクタ
//=============================================================================
CInputJoypad::~CInputJoypad()
{
}
//=============================================================================
// コントローラークラス初期化
//=============================================================================
HRESULT CInputJoypad::Init(HINSTANCE hInstance, HWND hWnd)
{
// HWND = ウィンドウがアクティブの時にする
// 初期化してから
CInput::Init(hInstance, hWnd);
// 入力デバイス(コントローラー)の生成
if (FAILED(m_pInput->CreateDevice(GUID_Joystick,
&m_pDevice,
NULL)))
{
return E_FAIL;
}
// データフォーマットを設定
if (FAILED(m_pDevice->SetDataFormat(&c_dfDIJoystick)))
{
return E_FAIL;
}
// 協調モードを設定 *入力をとる取らないだから変わらない
if (FAILED(m_pDevice->SetCooperativeLevel(hWnd, (DISCL_FOREGROUND | DISCL_NONEXCLUSIVE))))
{
return E_FAIL;
}
// コントローラーのアクセス権を獲得(入力制御開始)
if (m_pDevice != NULL)
{// 生成できた
DIPROPRANGE diprg;
// 軸の値の範囲を設定
diprg.diph.dwSize = sizeof(diprg);
diprg.diph.dwHeaderSize = sizeof(diprg.diph);
diprg.diph.dwHow = DIPH_BYOFFSET;
diprg.lMin = -DI_JOY_I_INPUT;
diprg.lMax = DI_JOY_I_INPUT;
// 軸の設定
// 左アナログスティック
// X軸
diprg.diph.dwObj = DIJOFS_X;
m_pDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
// Y軸
diprg.diph.dwObj = DIJOFS_Y;
m_pDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
// Z軸
diprg.diph.dwObj = DIJOFS_Z;
m_pDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
// 右アナログスティック
// RX軸
diprg.diph.dwObj = DIJOFS_RX;
m_pDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
// RY軸
diprg.diph.dwObj = DIJOFS_RY;
m_pDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
// RZ軸
diprg.diph.dwObj = DIJOFS_RZ;
m_pDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
// 十字キー(上を0度とし時計回りに角度 * 100)
diprg.diph.dwObj = DIJOFS_POV(0);
m_pDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
// ジョイスティックへのアクセス権を獲得(入力制御開始)
m_pDevice->Acquire();
}
return S_OK;
}
//=============================================================================
// コントローラークラス終了処理
//=============================================================================
void CInputJoypad::Uninit(void)
{
// 入力デバイス(コントローラー)の開放
CInput::Uninit();
// 消されていなかったときに消す
// 入力デバイス(キーボード)の開放
if (m_pDevice != NULL)
{
m_pDevice->Unacquire();
m_pDevice->Release();
m_pDevice = NULL;
}
}
//=============================================================================
// コントローラークラス更新処理
//=============================================================================
void CInputJoypad::Update(void)
{
DIJOYSTATE dijs;
if (m_pDevice != NULL)
{
m_pDevice->Poll();
if (SUCCEEDED(m_pDevice->GetDeviceState(sizeof(dijs), &dijs)))
{
// 入力デバイスからデータ(軸)を取得
m_LeftAxizX = (float)dijs.lX;
m_LeftAxizY = (float)dijs.lY;
m_RightAxizX = (float)dijs.lZ;
m_RightAxizY = (float)dijs.lRz;
// 左スティックが上に倒された
if (m_LeftAxizY > 100)
{
dijs.rgbButtons[STICK_L_UP] = 0x80;
}
// 左スティックが下に倒された
if (m_LeftAxizY < -100)
{
dijs.rgbButtons[STICK_L_DOWN] = 0x80;
}
// 左スティックが右に倒された
if (m_LeftAxizX > 100)
{
dijs.rgbButtons[STICK_L_RIGHT] = 0x80;
}
// 左スティックが左に倒された
if (m_LeftAxizX < -100)
{
dijs.rgbButtons[STICK_L_LEFT] = 0x80;
}
// 右スティックが上に倒された
if (m_LeftAxizY > 100)
{
dijs.rgbButtons[STICK_R_UP] = 0x80;
}
// 右スティックが下に倒された
if (m_LeftAxizY < -100)
{
dijs.rgbButtons[STICK_R_DOWN] = 0x80;
}
// 右スティックが右に倒された
if (m_LeftAxizX > 100)
{
dijs.rgbButtons[STICK_R_RIGHT] = 0x80;
}
// 右スティックが左に倒された
if (m_LeftAxizX < -100)
{
dijs.rgbButtons[STICK_R_LEFT] = 0x80;
}
// 十字キーが上に倒された
if (dijs.rgdwPOV[0] == 0)
{
dijs.rgbButtons[POV_UP] = 0x80;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
// 十字キーが下に倒された
if (dijs.rgdwPOV[0] == 18000)
{
dijs.rgbButtons[POV_DOWN] = 0x80;
dijs.rgdwPOV[0] /= 100;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
// 十字キーが右に倒された
if (dijs.rgdwPOV[0] == 9000)
{
dijs.rgbButtons[POV_RIGHT] = 0x80;
dijs.rgdwPOV[0] /= 100;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
// 十字キーが左に倒された
if (dijs.rgdwPOV[0] == 27000)
{
dijs.rgbButtons[POV_LEFT] = 0x80;
dijs.rgdwPOV[0] /= 100;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
// 十字キーが右上に倒された
if (dijs.rgdwPOV[0] == 4500)
{
dijs.rgbButtons[POV_UP_RIGHT] = 0x80;
dijs.rgdwPOV[0] /= 100;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
// 十字キーが右下に倒された
if (dijs.rgdwPOV[0] == 13500)
{
dijs.rgbButtons[POV_DOWN_RIGHT] = 0x80;
dijs.rgdwPOV[0] /= 100;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
// 十字キーが左下に倒された
if (dijs.rgdwPOV[0] == 22500)
{
dijs.rgbButtons[POV_DOWN_LEFT] = 0x80;
dijs.rgdwPOV[0] /= 100;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
// 十字キーが左下に倒された
if (dijs.rgdwPOV[0] == 31500)
{
dijs.rgbButtons[POV_UP_LEFT] = 0x80;
dijs.rgdwPOV[0] /= 100;
m_Radian = D3DXToRadian(dijs.rgdwPOV[0]);
}
for (int nCntKey = 0; nCntKey < NUM_BUTTON_MAX; nCntKey++)
{
m_aKeyStateRelease[nCntKey] = (m_aKeyState[nCntKey] ^ dijs.rgbButtons[nCntKey]) & m_aKeyState[nCntKey];
m_aKeyStateTrigger[nCntKey] = (m_aKeyState[nCntKey] ^ dijs.rgbButtons[nCntKey]) & dijs.rgbButtons[nCntKey];
m_aKeyState[nCntKey] = dijs.rgbButtons[nCntKey];
}
}
else
{
// キーボードへのアクセス権を獲得(入力制御開始)
m_pDevice->Acquire();
}
}
}
//=============================================================================
// コントローラークラス入力情報(プレス情報)を取得
//=============================================================================
bool CInputJoypad::GetPress(int nKey)
{
return(m_aKeyState[nKey] & 0x80) ? true : false;
}
//=============================================================================
// コントローラークラス入力情報(トリガー情報)を取得
//=============================================================================
bool CInputJoypad::GetTrigger(int nKey)
{
return(m_aKeyStateTrigger[nKey] & 0x80) ? true : false;
}
//=============================================================================
// コントローラークラス入力情報(リリース情報)を取得
//=============================================================================
bool CInputJoypad::GetRelease(int nKey)
{
return(m_aKeyStateRelease[nKey] & 0x80) ? true : false;
}
//=============================================================================
// コントローラーの左スティックの向き
//=============================================================================
float CInputJoypad::GetLeftAxiz(void)
{
float Axiz = atan2f(m_LeftAxizX, m_LeftAxizY);
return Axiz;
}
//=============================================================================
// コントローラーの右スティックの向きを取得
//=============================================================================
float CInputJoypad::GetRightAxiz(void)
{
float Axiz = atan2f(m_RightAxizX, m_RightAxizY);
return Axiz;
}
//=============================================================================
// コントローラーの 十字キー取得
//=============================================================================
float CInputJoypad::GetRadian(void)
{
return m_Radian;
}
//=============================================================================
// コントローラーの生成処理
//=============================================================================
CInputJoypad * CInputJoypad::Create(HINSTANCE hInstance, HWND hWnd)
{
CInputJoypad *pCInputJoyPad = NULL;
// NULLチェック
if (pCInputJoyPad == NULL)
{
// 動的確保
pCInputJoyPad = new CInputJoypad;
// NULLチェック
if (pCInputJoyPad != NULL)
{
// 初期化処理
pCInputJoyPad->Init(hInstance, hWnd);
}
else
{// 警告文
MessageBox(0, "警告:メモリがないです", "警告", MB_OK);
}
}
else
{// 警告文
MessageBox(0, "警告:何かが入ってます", "警告", MB_OK);
}
return pCInputJoyPad;
}
bool CInputJoypad::GetJoyPadAny(int nNumber)
{
if (nNumber == 1)
{
for (int nCount = 0; nCount < NUM_KEY_MAX; nCount++)
{
if (m_aKeyStateTrigger[nCount] == 0x80)
{
return true;
}
}
}
return false;
} | [
"yoshiro446025@gmail.com"
] | yoshiro446025@gmail.com |
91c637a179b51fd619213c9e531a2d8bbe018fa2 | 0db983816ce3d4b43617a36733c38aef7cd54e43 | /CPP-Concourrency-in-Action/chapter2 managing threads/join_detach.cpp | 7f354932b104fd423b7233855585f13bee935f63 | [] | no_license | fkgkdfgy/C3P | fd23e755a32eb5231524137d077d7ede8fa3548e | c97121169e2c25b65c3902968af5c92d1dbaf7b8 | refs/heads/master | 2023-03-25T12:06:47.538598 | 2021-03-15T05:49:12 | 2021-03-15T05:49:12 | 295,170,738 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,525 | cpp | /*
* @Author: Liu Weilong
* @Date: 2020-09-25 16:14:39
* @LastEditors: Liu Weilong
* @LastEditTime: 2020-10-29 13:54:29
* @FilePath: /C3P/CPP-Concourrency-in-Action/chapter2 managing threads/join_detach.cpp
* @Description: thread join 和detach 操作
* 经过这段时间的多线程的使用
* 还是对多线程有了一些了解
* t.join() 就是会在这里对这行代码一直等待 t 运行结束
* t.detach() 就是说明不用继续等待
*
*
*
*/
#include <thread>
#include <iostream>
#include "common.hpp"
using namespace std;
void join()
{
thread t(print);
cout<<"this thread's id is "<<t.get_id()<<endl; // thread id 需要在detach 和 join 之前调用
t.join();
print();
}
void detach()
{
thread t(print);
cout<<"this thread's id is "<<t.get_id()<<endl;
t.detach();
print();
}
// 此处会直接调用print
void no_decision()
{
thread t(print);
}
void join_later()
{
thread t(print);
cout<<"=============="<<endl;
print();
t.join(); // 线程并没有把之后的print() 一起跑完,最后只是运行了print 两遍
}
int main(int argc,char **argv)
{
// cout<<"join"<<endl;
// join();
//cout<<"detach"<<endl;
//detach();
//cout<<"no decision"<<endl;
//no_decision(); // 会直接调用 terminate 尽量避免这种情况出现
cout<<"join_later"<<endl;
thread t(print);
for(int i=0;i<2000;i++)
cout<<i<<endl;
return 0;
} | [
"weilong.liu-csu@outlook.com"
] | weilong.liu-csu@outlook.com |
71acd9b98966f60b3bbf499515fc68e3c474e08e | a0604bbb76abbb42cf83e99f673134c80397b92b | /fldserver/base/sql/transaction.cc | 31e86fb9ad33d6a5d5a46ac4b34ed06a93b8ca8b | [
"BSD-3-Clause"
] | permissive | Hussam-Turjman/FLDServer | 816910da39b6780cfd540fa1e79c84a03c57a488 | ccc6e98d105cfffbf44bfd0a49ee5dcaf47e9ddb | refs/heads/master | 2022-07-29T20:59:28.954301 | 2022-07-03T12:02:42 | 2022-07-03T12:02:42 | 461,034,667 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | cc | // Copyright (c) 2011 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 "fldserver/base/sql/transaction.h"
#include "fldserver/base/check.h"
#include "fldserver/base/sql/database.h"
namespace sql
{
Transaction::Transaction(Database* database) : database_(database)
{
}
Transaction::~Transaction()
{
if (is_open_)
database_->RollbackTransaction();
}
bool
Transaction::Begin()
{
DCHECK(!is_open_) << "Beginning a transaction twice!";
is_open_ = database_->BeginTransaction();
return is_open_;
}
void
Transaction::Rollback()
{
DCHECK(is_open_) << "Attempting to roll back a nonexistent transaction. "
<< "Did you remember to call Begin() and check its return?";
is_open_ = false;
database_->RollbackTransaction();
}
bool
Transaction::Commit()
{
DCHECK(is_open_) << "Attempting to commit a nonexistent transaction. "
<< "Did you remember to call Begin() and check its return?";
is_open_ = false;
return database_->CommitTransaction();
}
} // namespace sql
| [
"hussam.turjman@gmail.com"
] | hussam.turjman@gmail.com |
6172af8b9ee4fc7eef0eacbf312c34f551b83228 | 91b19ebb15c3f07785929b7f7a4972ca8f89c847 | /Classes/SaveData_android.cpp | da234a379656d11265a8bd1199504a97c019e90d | [] | no_license | droidsde/DrawGirlsDiary | 85519ac806bca033c09d8b60fd36624f14d93c2e | 738e3cee24698937c8b21bd85517c9e10989141e | refs/heads/master | 2020-04-08T18:55:14.160915 | 2015-01-07T05:33:16 | 2015-01-07T05:33:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,541 | cpp | //
// SaveData_android.cpp
// BasketWorldCup2
//
// Created by ksoo k on 13. 1. 4..
//
//
#include "SaveData_android.h"
/*
string filePath = "KSDATA";
NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* nsfilePath = [NSString stringWithUTF8String:filePath.c_str()];
NSString* fullFileName = [NSString stringWithFormat:@"%@/%@", documentsDirectory, nsfilePath ];
const char* szFilePath = [fullFileName UTF8String];
FILE* fp = fopen( szFilePath, "w" );
fprintf(fp, "%s", tt.c_str());
fclose(fp);
}
string readF()
{
string filePath = "KSDATA";
NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* nsfilePath = [NSString stringWithUTF8String:filePath.c_str()];
NSString* fullFileName = [NSString stringWithFormat:@"%@/%@", documentsDirectory, nsfilePath ];
const char* szFilePath = [fullFileName UTF8String];
cout << szFilePath << endl;
FILE* fp = fopen( szFilePath, "r" );
string result;
if(fp)
{
fseek(fp, 0L, SEEK_END);
int s = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char* buffer = new char[s+1];
memset(buffer, 0, sizeof(s+1));
fread(buffer, sizeof(char), s, fp);
fclose(fp);
result = buffer;
delete [] buffer;
}
else
{
return "";
}
return result;
}
*/
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
//void testF(string tt)
//{
//
// string path = CCFileUtils::sharedFileUtils()->getWritablePath() + "KSDATA";
// FILE* fp = fopen( path.c_str(), "w" );
// if(!fp)
// {
// CCLOG("file failure");
// }
// fprintf(fp, "%s", tt.c_str());
// fclose(fp);
//}
//string readF()
//{
// string path = CCFileUtils::sharedFileUtils()->getWritablePath() + "KSDATA";
// FILE* fp = fopen( path.c_str(), "r" );
// string result;
// if(fp)
// {
// fseek(fp, 0L, SEEK_END);
// int s = ftell(fp);
// fseek(fp, 0L, SEEK_SET);
// char* buffer = new char[s+1];
// memset(buffer, 0, sizeof(s+1));
// fread(buffer, sizeof(char), s, fp);
// fclose(fp);
//
//
// result = buffer;
// delete [] buffer;
// }
// else
// {
// CCLOG("read fail");
// return "";
// }
//
// return result;
//}
int testF(string filePath, string tt)
{
int return_value = 0;
string t_path = CCFileUtils::sharedFileUtils()->getWritablePath() + filePath;
FILE* t_fp = fopen( t_path.c_str(), "w" );
if(!t_fp)
{
CCLOG("file failure");
}
return_value = fprintf(t_fp, "%s", tt.c_str());
fclose(t_fp);
return return_value;
// string path = CCFileUtils::sharedFileUtils()->getWritablePath() + filePath;
// int rename_result;
// rename_result = rename( t_path.c_str(), path.c_str() );
// if(rename_result != 0)
// CCLOG("file failure(rename)");
}
string readF(string filePath)
{
string path = CCFileUtils::sharedFileUtils()->getWritablePath() + filePath;
FILE* fp = fopen( path.c_str(), "r" );
string result;
if(fp)
{
fseek(fp, 0L, SEEK_END);
int s = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char* buffer = new char[s+1];
memset(buffer, 0, sizeof(s+1));
fread(buffer, sizeof(char), s, fp);
fclose(fp);
result = buffer;
delete [] buffer;
}
else
{
CCLOG("read fail");
return "";
}
return result;
}
void addF(string filePath, string tt)
{
string path = CCFileUtils::sharedFileUtils()->getWritablePath() + filePath;
FILE* fp = fopen( path.c_str(), "a" );
if(!fp)
{
CCLOG("file failure");
}
fprintf(fp, "%s", tt.c_str());
fclose(fp);
}
#endif
| [
"seo88youngho@gmail.com"
] | seo88youngho@gmail.com |
a0e8c3fd7b59871739ca5fe636a96ee29a992197 | 55eb24ea6b0ea4257046f04aa6d3c18e9a0be29a | /Samsung/미세먼지 안녕!/17144_solution.cpp | ccf3f74720804b15c32f7a102d5a34ca111021af | [] | no_license | dwywdo/PS | dbb8b913f46d178783bc4b6ebf2a185a2a66b220 | 05700db6b6a49de93e72848b4d516e2a65da592a | refs/heads/master | 2021-11-28T19:15:11.903267 | 2021-11-22T15:46:01 | 2021-11-22T15:46:01 | 248,372,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,526 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int map[50][50];
int copy_map[50][50];
int R, C, T;
int dy[4] = {-1, 1, 0, 0};
int dx[4] = {0, 0, -1, 1};
vector<pair<int, int>> airs;
void rotation(pair<int, int> air, bool isupper){
vector<int> group;
if(isupper){
for(int i=air.first, j=air.second; j<C-1; j++){
if(map[i][j] == -1) group.push_back(0);
else group.push_back(map[i][j]);
}
for(int i=air.first, j=C-1; i>0; i--) group.push_back(map[i][j]);
for(int i=0, j=C-1; j>0; j--) group.push_back(map[i][j]);
for(int i=0, j=0; i<air.first; i++) group.push_back(map[i][j]);
rotate(group.rbegin(), group.rbegin()+1, group.rend());
int idx = 0;
for(int i=air.first, j=air.second; j<C-1; j++){
if(map[i][j] != -1) map[i][j] = group[idx++];
else idx++;
}
for(int i=air.first, j=C-1; i>0; i--) map[i][j] = group[idx++];
for(int i=0, j=C-1; j>0; j--) map[i][j] = group[idx++];
for(int i=0, j=0; i<air.first; i++) map[i][j] = group[idx++];
}
else{
for(int i=air.first, j=air.second; j<C-1; j++){
if(map[i][j] == -1) group.push_back(0);
else group.push_back(map[i][j]);
}
for(int i=air.first, j=C-1; i<R-1; i++) group.push_back(map[i][j]);
for(int i=R-1, j=C-1; j>0; j--) group.push_back(map[i][j]);
for(int i=R-1, j=0; i>air.first; i--) group.push_back(map[i][j]);
rotate(group.rbegin(), group.rbegin()+1, group.rend());
int idx = 0;
for(int i=air.first, j=air.second; j<C-1; j++){
if(map[i][j] != -1) map[i][j] = group[idx++];
else idx++;
}
for(int i=air.first, j=C-1; i<R-1; i++) map[i][j] = group[idx++];
for(int i=R-1, j=C-1; j>0; j--) map[i][j] = group[idx++];
for(int i=R-1, j=0; i>air.first; i--) map[i][j] = group[idx++];
}
}
int main(){
cin >> R >> C >> T;
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
cin >> map[i][j];
copy_map[i][j] = map[i][j];
if(map[i][j] == -1){
airs.push_back(make_pair(i, j));
}
}
}
int tmp = 0;
while(T--){
// 확산
bool check[50][50];
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
if(copy_map[i][j] >= 5) check[i][j] = true;
else check[i][j] = false;
}
}
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
if(check[i][j]){
int cnt = 0;
for(int k=0; k<4; k++){
int ny = i + dy[k]; int nx = j + dx[k];
if(ny>=0 && ny<R && nx>=0 && nx<C){
if(map[ny][nx] != -1){
map[ny][nx] += copy_map[i][j] / 5; cnt++;
}
}
}
map[i][j] -= (copy_map[i][j]/5)*cnt;
}
}
}
rotation(airs[0], true);
rotation(airs[1], false);
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
copy_map[i][j] = map[i][j];
}
}
}
int amount = 0;
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
if(map[i][j] != -1) amount += map[i][j];
}
}
cout << amount << endl;
return 0;
} | [
"dwywdo@gmail.com"
] | dwywdo@gmail.com |
94229cfe0d4783d180435048951644a5e5e785a1 | 24128d7dc7a16470bd2f2082c20e6cc00e083baf | /CPlusPlus/lru/lru.cpp | 03e7a3c89a8c87a3c6759eeee8e072e4a58d4220 | [
"Apache-2.0"
] | permissive | MakeBugsEveryday/algorithms | 1689ba8b903896bcbc97a5eaa5cf7e26bd8c5875 | 0f3e310f09884c8c6ac3578aab4884ddd0baa711 | refs/heads/master | 2021-08-19T05:03:20.419836 | 2020-04-14T08:30:49 | 2020-04-14T08:30:49 | 161,980,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,637 | cpp | #include<iostream>
#include"../node/node.hpp"
using namespace std;
class LRU
{
private:
// 头结点
Node *head;
// 尾巴节点
Node *tail;
public:
LRU(/* args */);
~LRU();
/* 将节点插入首部 */
void insertNodeAtHead(Node *node);
/* 将节点放入头结点 */
void bringToHead(Node *node);
/* 移除尾巴节点 */
void removeTail();
/* 移除节点 */
void remove(Node *node);
/* 移除所有节点 */
void removeAll();
/* 遍历打印所有节点 */
void description();
};
LRU::LRU(/* args */)
{
}
LRU::~LRU()
{
}
void LRU::insertNodeAtHead(Node *node)
{
// 已经是首部了,返回
if (node == head)
{
return;
}
// 置空前节点
node->previous = NULL;
// 头结点为空,
if (head == NULL)
{
head = tail = node;
return;
}
// header 不为空
head->previous = node;
node->next = head;
head = node;
}
void LRU::removeTail()
{
// tail为空
if (tail == NULL)
{
return;
}
// 只有一个节点
if (tail == head)
{
head = tail = NULL;
return;
}
tail = tail->previous;
tail->next = NULL;
}
void LRU::bringToHead(Node *node)
{
if (head == node)
{
return;
}
// node为尾巴节点
if (node == tail)
{
// 移除尾巴节点
removeTail();
// 插入头结点
insertNodeAtHead(node);
return;
}
// 断开节点
node->previous->next = node->next;
node->next->previous = node->previous;
// 连接链表
node->next = node->previous = NULL;
insertNodeAtHead(node);
}
void LRU::remove(Node *node)
{
if (node == head && node == tail)
{
head = tail = NULL;
return;
}
if (node == head)
{
head = head->next;
node->next = node->previous = NULL;
return;
}
if (node == tail)
{
removeTail();
return;
}
// 断开连接
node->previous->next = node->next;
node->next->previous = node->previous;
// 清空
node->next = node->previous = NULL;
}
void LRU::description()
{
Node *root = head;
while (root)
{
cout << root->value << " ";
root = root->next;
}
cout << endl;
}
int main(int argc, char const *argv[])
{
LRU lru;
lru.insertNodeAtHead(new Node(3));
lru.insertNodeAtHead(new Node(2));
lru.insertNodeAtHead(new Node(1));
lru.description();
lru.removeTail();
lru.description();
return 0;
}
| [
"1349963838@163.com"
] | 1349963838@163.com |
f055e5cf390a2e7adf4246a033b173e22ca41572 | f0f3c9c8933941a0792a1fd8f95c5427ab0ec5e9 | /iree/compiler/Conversion/Common/FlattenMemRefSubspanPass.cpp | c226f5aa9b77c34e6d3ceb5202c3c4f0bf40f38e | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | Presburger/iree | 0255f7f0d4a9e7387d1c92938c42171ac05b73d1 | 51f8385c68b7e61f06c4a59971b48e72dc097427 | refs/heads/main | 2023-04-22T14:47:29.140029 | 2021-05-07T00:04:12 | 2021-05-07T00:04:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,699 | cpp | // Copyright 2021 Google LLC
//
// 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
//
// https://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.
//===- FlattenMemRefSubspanPass.cpp - Flatten n-D MemRef subspan ----------===//
//
// This file implements a pass to flatten n-D MemRef subspan ops to 1-D MemRef
// ones and folds the byte offsets on subspan ops to the consumer load/store
// ops, in preparation for lowering to the final target.
//
// This pass is needed because of how MemRef is used by subspan ops:
//
// 1) Normally MemRef should capture the mapping to the underlying buffer with
// its internal strides and offsets. However, although subspan ops in IREE are
// subview-like constructs, they carry the offset directly on the ops themselves
// and return MemRefs with the identity layout map. This is due to that IREE can
// perform various optimizations over buffer allocation and decide, for example,
// to use the same underlying buffer for two MemRefs, which are converted form
// disjoint tensors initially.
// 2) The byte offset on subspan ops is an offset into the final planned 1-D
// byte buffer, while the MemRef can be n-D without considering a backing
// buffer and its data layout.
//
// So to bridge the gap, we need to linearize the MemRef dimensions to bring it
// onto the same view as IREE: buffers are just a bag of bytes. Then we need to
// fold the byte offset on subspan ops to the consumer load/store ops, so that
// we can rely on transformations in MLIR core, because they assume MemRefs map
// to the underlying buffers with its internal strides and offsets.
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
namespace mlir {
namespace iree_compiler {
namespace {
//===----------------------------------------------------------------------===//
// Type Conversion
//===----------------------------------------------------------------------===//
/// Returns true if the given `type` is a MemRef of rank 0 or 1.
static bool isRankZeroOrOneMemRef(Type type) {
if (auto memrefType = type.dyn_cast<MemRefType>()) {
return memrefType.hasRank() && memrefType.getRank() <= 1;
}
return false;
}
/// Flattens n-D MemRef to 1-D MemRef and allows other types.
struct FlattenMemRefTypeConverter final : public TypeConverter {
FlattenMemRefTypeConverter() {
// Allow all other types.
addConversion([](Type type) -> Optional<Type> { return type; });
// Convert n-D MemRef to 1-D MemRef.
addConversion([](MemRefType type) -> Optional<Type> {
// 1-D MemRef types are okay.
if (isRankZeroOrOneMemRef(type)) return type;
// We can only handle static strides and offsets for now; fail the rest.
int64_t offset;
SmallVector<int64_t, 4> strides;
if (failed(getStridesAndOffset(type, strides, offset))) return Type();
// Convert to a MemRef with unknown dimension. This is actually more akin
// to how IREE uses memref types: they are for representing a view from a
// byte buffer with potentially unknown total size, as transformation
// passes can concatenate buffers, etc.
return MemRefType::get(ShapedType::kDynamicSize, type.getElementType(),
ArrayRef<AffineMap>(), type.getMemorySpace());
});
}
};
//===----------------------------------------------------------------------===//
// Flattening Patterns
//===----------------------------------------------------------------------===//
/// Flattens memref subspan ops with more than 1 dimensions to 1 dimension.
struct FlattenBindingSubspan final
: public OpConversionPattern<IREE::HAL::InterfaceBindingSubspanOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
IREE::HAL::InterfaceBindingSubspanOp subspanOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
auto oldType = subspanOp.getType().dyn_cast<MemRefType>();
// IREE subspan ops only use memref types with the default identity
// layout maps.
if (!oldType || !oldType.getAffineMaps().empty()) return failure();
Type newType = getTypeConverter()->convertType(oldType);
rewriter.replaceOpWithNewOp<IREE::HAL::InterfaceBindingSubspanOp>(
subspanOp, newType, subspanOp.binding(), subspanOp.byte_offset(),
subspanOp.byte_length());
return success();
}
};
/// Generates IR to perform index linearization with the given `indices`
/// indexing into the given memref `sourceType`.
static Value linearizeIndices(MemRefType sourceType, ValueRange indices,
Location loc, OpBuilder &builder) {
assert(sourceType.hasRank() && sourceType.getRank() != 0);
int64_t offset;
SmallVector<int64_t, 4> strides;
if (failed(getStridesAndOffset(sourceType, strides, offset)) ||
llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) ||
offset == MemRefType::getDynamicStrideOrOffset()) {
return nullptr;
}
AffineExpr sym0, sym1, sym2;
bindSymbols(builder.getContext(), sym0, sym1, sym2);
MLIRContext *context = builder.getContext();
auto mulAddMap = AffineMap::get(0, 3, {sym0 * sym1 + sym2}, context);
Value linearIndex = builder.create<ConstantIndexOp>(loc, offset);
for (auto pair : llvm::zip(indices, strides)) {
Value stride = builder.create<ConstantIndexOp>(loc, std::get<1>(pair));
linearIndex = builder.create<AffineApplyOp>(
loc, mulAddMap, ValueRange{std::get<0>(pair), stride, linearIndex});
}
return linearIndex;
}
/// Linearizes indices in memref.load ops.
struct LinearizeLoadIndices final : public OpConversionPattern<memref::LoadOp> {
using OpConversionPattern<memref::LoadOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
memref::LoadOp loadOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
memref::LoadOp::Adaptor adaptor(operands);
if (!isRankZeroOrOneMemRef(adaptor.memref().getType())) {
return rewriter.notifyMatchFailure(
loadOp, "expected converted memref of rank <= 1");
}
Value linearIndex = linearizeIndices(
loadOp.getMemRefType(), loadOp.getIndices(), loadOp.getLoc(), rewriter);
rewriter.replaceOpWithNewOp<memref::LoadOp>(loadOp, adaptor.memref(),
linearIndex);
return success();
}
};
/// Linearizes indices in memref.store ops.
struct LinearizeStoreIndices final
: public OpConversionPattern<memref::StoreOp> {
using OpConversionPattern<memref::StoreOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
memref::StoreOp storeOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
memref::StoreOp::Adaptor adaptor(operands);
if (!isRankZeroOrOneMemRef(adaptor.memref().getType())) {
return rewriter.notifyMatchFailure(
storeOp, "expected converted memref of rank <= 1");
}
Value linearIndex =
linearizeIndices(storeOp.getMemRefType(), storeOp.getIndices(),
storeOp.getLoc(), rewriter);
rewriter.replaceOpWithNewOp<memref::StoreOp>(storeOp, adaptor.value(),
adaptor.memref(), linearIndex);
return success();
}
};
/// Adjusts unrealized_conversion_cast ops' inputs to flattened memref values.
struct AdjustConversionCast final
: public OpConversionPattern<UnrealizedConversionCastOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
UnrealizedConversionCastOp castOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
if (castOp->getNumOperands() != 1) return failure();
Value input = operands.front();
if (!isRankZeroOrOneMemRef(input.getType())) {
return rewriter.notifyMatchFailure(
castOp, "expected converted memref of rank <= 1");
}
rewriter.replaceOpWithNewOp<UnrealizedConversionCastOp>(
castOp, castOp.getResultTypes(), input);
return success();
}
};
//===----------------------------------------------------------------------===//
// Folding Patterns
//===----------------------------------------------------------------------===//
/// Returns the number of bytes of the given `type`. Returns llvm::None if
/// cannot deduce.
///
/// Note that this should be kept consistent with how the byte offset was
/// calculated in the subspan ops!
Optional<int64_t> getNumBytes(Type type) {
if (type.isIntOrFloat()) return (type.getIntOrFloatBitWidth() + 7) / 8;
if (auto vectorType = type.dyn_cast<VectorType>()) {
auto elementBytes = getNumBytes(vectorType.getElementType());
if (!elementBytes) return llvm::None;
return elementBytes.getValue() * vectorType.getNumElements();
}
return llvm::None;
}
/// Folds the byte offset on subspan ops into the consumer load/store ops.
template <typename OpType>
struct FoldSubspanOffsetIntoLoadStore final : public OpRewritePattern<OpType> {
using OpRewritePattern<OpType>::OpRewritePattern;
LogicalResult matchAndRewrite(OpType op,
PatternRewriter &rewriter) const override {
auto memrefType = op.memref().getType().template cast<MemRefType>();
if (!isRankZeroOrOneMemRef(memrefType)) {
return rewriter.notifyMatchFailure(op, "expected 0-D or 1-D memref");
}
auto subspanOp =
op.memref()
.template getDefiningOp<IREE::HAL::InterfaceBindingSubspanOp>();
if (!subspanOp) return failure();
// If the subspan op has a zero byte offset then we are done.
if (matchPattern(subspanOp.byte_offset(), m_Zero())) return failure();
// byte length is unsupported for now.
if (subspanOp.byte_length()) {
return rewriter.notifyMatchFailure(op, "byte length unsupported");
}
// Calculate the offset we need to add to the load/store op, in terms of how
// many elements.
Optional<int64_t> numBytes = getNumBytes(memrefType.getElementType());
if (!numBytes) {
return rewriter.notifyMatchFailure(op,
"cannot deduce element byte count");
}
// Create a new subspan op with zero byte offset.
Value zero = rewriter.create<ConstantIndexOp>(op.memref().getLoc(), 0);
Value newSubspan = rewriter.create<IREE::HAL::InterfaceBindingSubspanOp>(
op.memref().getLoc(), subspanOp.getType(), subspanOp.binding(), zero,
subspanOp.byte_length());
MLIRContext *context = rewriter.getContext();
AffineExpr sym0, sym1;
bindSymbols(context, sym0, sym1);
auto addMap = AffineMap::get(0, 2, {sym0 + sym1}, context);
auto divMap = AffineMap::get(0, 2, {sym0.floorDiv(sym1)}, context);
Value byteValue = rewriter.create<ConstantIndexOp>(op.memref().getLoc(),
numBytes.getValue());
// We assume that upper layers guarantee the byte offset is perfectly
// divisible by the element byte count so the content is well aligned.
Value offset = rewriter.create<AffineApplyOp>(
op.getLoc(), divMap, ValueRange{subspanOp.byte_offset(), byteValue});
// Get the new index by adding the old index with the offset.
Value newIndex = rewriter.create<AffineApplyOp>(
op.getLoc(), addMap, ValueRange{op.indices().front(), offset});
if (std::is_same<OpType, memref::LoadOp>::value) {
rewriter.replaceOpWithNewOp<memref::LoadOp>(
op, memrefType.getElementType(), ValueRange{newSubspan, newIndex});
} else {
rewriter.replaceOpWithNewOp<memref::StoreOp>(
op, TypeRange{}, ValueRange{op.getOperand(0), newSubspan, newIndex});
}
return success();
}
};
//===----------------------------------------------------------------------===//
// Pass
//===----------------------------------------------------------------------===//
struct FlattenMemRefSubspanPass
: public PassWrapper<FlattenMemRefSubspanPass, FunctionPass> {
FlattenMemRefSubspanPass() {}
FlattenMemRefSubspanPass(const FlattenMemRefSubspanPass &pass) {}
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<AffineDialect, memref::MemRefDialect>();
}
void runOnFunction() override {
// First flatten the dimensions of subspan op and their consumer load/store
// ops. This requires setting up conversion targets with type converter.
MLIRContext &context = getContext();
FlattenMemRefTypeConverter typeConverter;
RewritePatternSet flattenPatterns(&context);
flattenPatterns.add<FlattenBindingSubspan, LinearizeLoadIndices,
LinearizeStoreIndices, AdjustConversionCast>(
typeConverter, &context);
ConversionTarget target(context);
target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
target.addDynamicallyLegalOp<IREE::HAL::InterfaceBindingSubspanOp>(
[](IREE::HAL::InterfaceBindingSubspanOp subspanOp) {
return isRankZeroOrOneMemRef(subspanOp.getType());
});
target.addDynamicallyLegalOp<memref::LoadOp>([](memref::LoadOp loadOp) {
return isRankZeroOrOneMemRef(loadOp.getMemRefType());
});
target.addDynamicallyLegalOp<memref::StoreOp>([](memref::StoreOp storeOp) {
return isRankZeroOrOneMemRef(storeOp.getMemRefType());
});
target.addDynamicallyLegalOp<UnrealizedConversionCastOp>(
[](UnrealizedConversionCastOp castOp) {
return castOp->getNumOperands() == 1 &&
isRankZeroOrOneMemRef(castOp->getOperandTypes().front());
});
// Use partial conversion here so that we can ignore allocations created by
// promotion and their load/store ops.
if (failed(applyPartialConversion(getFunction(), target,
std::move(flattenPatterns)))) {
return signalPassFailure();
}
// Then fold byte offset on subspan ops into consumer load/store ops.
RewritePatternSet foldPatterns(&context);
foldPatterns.add<FoldSubspanOffsetIntoLoadStore<memref::LoadOp>,
FoldSubspanOffsetIntoLoadStore<memref::StoreOp>>(&context);
(void)applyPatternsAndFoldGreedily(getFunction(), std::move(foldPatterns));
}
};
} // namespace
std::unique_ptr<FunctionPass> createFlattenMemRefSubspanPass() {
return std::make_unique<FlattenMemRefSubspanPass>();
}
static PassRegistration<FlattenMemRefSubspanPass> pass(
"iree-codegen-flatten-memref-subspan",
"Flatten n-D MemRef subspan ops to 1-D ones and fold byte offsets on "
"subspan ops to the consumer load/store ops");
} // namespace iree_compiler
} // namespace mlir
| [
"noreply@github.com"
] | noreply@github.com |
e6bbe4afb4842826c6d2c8f037ade06e7499d727 | 96f8766592fac373d71eda5aef6050330e3a0182 | /src/request.hpp | 36199a74190e4be5db46200a6dee06dd73813cda | [] | no_license | artemp/paleoserver | 0b42eb906f046dfb64a4cd55f6e84ea6b6072de9 | 276fb5135021053b94c97609198449aa8d0eda96 | refs/heads/master | 2020-05-29T14:10:30.196971 | 2012-06-28T13:47:32 | 2012-06-28T13:47:32 | 4,821,063 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 706 | hpp | //
// request.hpp
// ~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef PALEOSERVER_REQUEST_HPP
#define PALEOSERVER_REQUEST_HPP
#include <string>
#include <vector>
#include "header.hpp"
namespace http {
namespace paleoserver {
/// A request received from a client.
struct request
{
std::string method;
std::string uri;
int http_version_major;
int http_version_minor;
std::vector<header> headers;
};
} // namespace paleoserver
} // namespace http
#endif // PALEOSERVER_REQUEST_HPP
| [
"dane@dbsgeo.com"
] | dane@dbsgeo.com |
57c6fac610cf1721f3f1d3684b8b55dc4f64ca14 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/preprocessor/debug/assert.hpp | f6bf539a72d3f76af6d8183ab76f92ee809b2fa0 | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:0d20ac6553e3748779bbf22048f46b22b4c49e8fd446ba3f76960055a5801f80
size 1374
| [
"YLiLarry@gmail.com"
] | YLiLarry@gmail.com |
f866ece8c76031f32401428492ef877ba5bef230 | e8b57223db9c44d891aaec5f92185b82bf6dea55 | /ConsoleApplication7/ConsoleApplication7/stdafx.cpp | bb5a777978a652e2deca6a1c279a8b8dc1fec466 | [] | no_license | gjs001/Algorithm | bc88ebde2f0eed74128aca8eac065c7d45b3043a | 3897cfbdf54589f6499c4af6badde545c02d6856 | refs/heads/master | 2022-04-01T19:07:56.510587 | 2020-02-08T17:51:11 | 2020-02-08T17:51:11 | 78,085,769 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 337 | cpp | // stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// ConsoleApplication7.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
// TODO: 필요한 추가 헤더는
// 이 파일이 아닌 STDAFX.H에서 참조합니다.
| [
"GitHub gjs010@naver.com"
] | GitHub gjs010@naver.com |
a52f27763e43a24c20b6e902b2c8f2292d5759fd | b2de69b5dcbdd35667535f56e227c3b37c52c930 | /CSIS 112/Lab3-GradeBook/Gradebook.h | 4b29a9b44dd583c9a3b43db5f1afa9d0c7d5fae6 | [] | no_license | SamHerts/School-Labs | df73d2f39ec791acb5279dc62d2412b98fe7af20 | a53bbfbd0d372607354e1b5a83d145f13e86a352 | refs/heads/master | 2020-05-19T15:30:43.906300 | 2020-02-10T15:59:16 | 2020-02-10T15:59:16 | 185,086,929 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | h | #ifndef GRADEBOOK_H
#define GRADEBOOK_H
#include <string>
#include <iostream>
#include "Student.h"
class Gradebook
{
public:
Gradebook(std::string);
void addStudent(std::string);
void listStudents();
int size();
void listTitle();
private:
std::string title;
std::vector<Student> book;
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
a2971683f015cc585d51f7afdd6354287ac1b3c0 | b1c06fcc909d57d102b00989fdbd9da91247a4a5 | /Source/Urho3D/Graphics/ShaderVariation.h | 01359f6be5c4da21bfb2c8489435900367f54961 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | TheophilusE/THEOE11 | fa7b2b0be0bc8c9a667b57412b3362c9685a31cb | b5fa471d6d24fd5a2509f658706771093c8cdf08 | refs/heads/master | 2023-08-25T14:31:42.202426 | 2021-11-06T03:40:16 | 2021-11-06T03:40:16 | 410,686,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,830 | h | //
// Copyright (c) 2008-2020 the Urho3D project.
//
// 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.
//
#pragma once
#include <EASTL/unordered_map.h>
#include "../Container/Ptr.h"
#include "../Graphics/GPUObject.h"
#include "../Graphics/GraphicsDefs.h"
namespace Urho3D
{
class ConstantBuffer;
class Shader;
/// %Shader parameter definition.
struct URHO3D_API ShaderParameter
{
/// Construct with defaults.
ShaderParameter() = default;
/// Construct with name, glType and location, leaving the remaining attributes zero-initialized (used only in OpenGL).
ShaderParameter(const ea::string& name, unsigned glType, int location);
/// Construct with type, name, offset, size, and buffer, leaving the remaining attributes zero-initialized (used only in Direct3D11).
ShaderParameter(ShaderType type, const ea::string& name, unsigned offset, unsigned size, unsigned buffer);
/// Construct with type, name, register, and register count, leaving the remaining attributes zero-initialized (used only in Direct3D9).
ShaderParameter(ShaderType type, const ea::string& name, unsigned reg, unsigned regCount);
/// %Shader type.
ShaderType type_{};
/// Name of the parameter.
ea::string name_{};
union
{
/// Offset in constant buffer.
unsigned offset_;
/// OpenGL uniform location.
int location_;
/// Direct3D9 register index.
unsigned register_;
};
union
{
/// Parameter size. Used only on Direct3D11 to calculate constant buffer size.
unsigned size_;
/// Parameter OpenGL type.
unsigned glType_;
/// Number of registers on Direct3D9.
unsigned regCount_;
};
/// Constant buffer index. Only used on Direct3D11.
unsigned buffer_{};
/// Constant buffer pointer. Defined only in shader programs.
ConstantBuffer* bufferPtr_{};
};
/// Vertex or pixel shader on the GPU.
class URHO3D_API ShaderVariation : public RefCounted, public GPUObject
{
public:
typedef ea::array<unsigned, MAX_SHADER_PARAMETER_GROUPS> ConstantBufferSizes;
/// Construct.
ShaderVariation(Shader* owner, ShaderType type);
/// Destruct.
~ShaderVariation() override;
/// Mark the GPU resource destroyed on graphics context destruction.
void OnDeviceLost() override;
/// Release the shader.
void Release() override;
/// Compile the shader. Return true if successful.
bool Create();
/// Set name.
void SetName(const ea::string& name);
/// Set defines.
void SetDefines(const ea::string& defines);
/// Return the owner resource.
Shader* GetOwner() const;
/// Return shader type.
ShaderType GetShaderType() const { return type_; }
/// Return shader name.
const ea::string& GetName() const { return name_; }
/// Return full shader name.
ea::string GetFullName() const { return name_ + "(" + defines_ + ")"; }
/// Return whether uses a parameter. Not applicable on OpenGL, where this information is contained in ShaderProgram instead.
bool HasParameter(StringHash param) const { return parameters_.contains(param); }
/// Return whether uses a texture unit (only for pixel shaders). Not applicable on OpenGL, where this information is contained in ShaderProgram instead.
bool HasTextureUnit(TextureUnit unit) const { return useTextureUnits_[unit]; }
/// Return all parameter definitions. Not applicable on OpenGL, where this information is contained in ShaderProgram instead.
const ea::unordered_map<StringHash, ShaderParameter>& GetParameters() const { return parameters_; }
/// Return vertex element hash.
unsigned long long GetElementHash() const { return elementHash_; }
/// Return shader bytecode. Stored persistently on Direct3D11 only.
const ea::vector<unsigned char>& GetByteCode() const { return byteCode_; }
/// Return defines.
const ea::string& GetDefines() const { return defines_; }
/// Return compile error/warning string.
const ea::string& GetCompilerOutput() const { return compilerOutput_; }
/// Return constant buffer data sizes.
const ConstantBufferSizes& GetConstantBufferSizes() const { return constantBufferSizes_; }
/// D3D11 vertex semantic names. Used internally.
static const char* elementSemanticNames[];
private:
/// Load bytecode from a file. Return true if successful.
bool LoadByteCode(const ea::string& binaryShaderName);
/// Compile from source. Return true if successful.
bool Compile();
/// Inspect the constant parameters and input layout (if applicable) from the shader bytecode.
void ParseParameters(unsigned char* bufData, unsigned bufSize);
/// Save bytecode to a file.
void SaveByteCode(const ea::string& binaryShaderName);
/// Calculate constant buffer sizes from parameters.
void CalculateConstantBufferSizes();
/// Shader this variation belongs to.
WeakPtr<Shader> owner_;
/// Shader type.
ShaderType type_;
/// Vertex element hash for vertex shaders. Zero for pixel shaders. Note that hashing is different than vertex buffers.
unsigned long long elementHash_{};
/// Shader parameters.
ea::unordered_map<StringHash, ShaderParameter> parameters_;
/// Texture unit use flags.
bool useTextureUnits_[MAX_TEXTURE_UNITS]{};
/// Constant buffer sizes. 0 if a constant buffer slot is not in use.
ConstantBufferSizes constantBufferSizes_{};
/// Shader bytecode. Needed for inspecting the input signature and parameters. Not used on OpenGL.
ea::vector<unsigned char> byteCode_;
/// Shader name.
ea::string name_;
/// Defines to use in compiling.
ea::string defines_;
/// Shader compile error string.
ea::string compilerOutput_;
};
}
| [
"65521326+GodTHEO@users.noreply.github.com"
] | 65521326+GodTHEO@users.noreply.github.com |
81dd8d58f2401ecf7370501382c84321fa597742 | becf7caa63d95071221c4120c0f238626b46100a | /src/Lambda_Optimization/Include/Gof_Updater.h | a8d4fab18665da9fff2dbfc57e59c3bddfc4e0c1 | [] | no_license | cran/fdaPDE | 1acaf7798553c5582294cbb99c3a7207b78ccb55 | 4c275d6bfbcbbdef81e094fc977e60f68d1e24f3 | refs/heads/master | 2023-03-09T17:20:47.497214 | 2023-03-01T07:22:39 | 2023-03-01T07:22:39 | 49,715,847 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,263 | h | #ifndef __GOF_UPDATER_H__
#define __GOF_UPDATER_H__
// HEADERS
#include <functional>
#include "../../FdaPDE.h"
#include "../../Global_Utilities/Include/Lambda.h"
// CLASSES
//! External updater for Lambda Optimizer
/*!
This class works as an external updater for a LambdaOptimizer method,
storing its pointer and keeping track of the updates performed in the past.
The purpose of this structure is mainly keeping at minimum the complexity of
each update by performing just what is needed from time to time.
\tparam LambdaOptim LambdaOptimizer type on which the update has to be performed
\tparam T type of the optimization parameter lambda
*/
template <typename LambdaOptim, typename T>
class GOF_updater
{
private:
// -- PARAMETERS FOR THE UPDATES --
//! std::vector of lambdas to keep track of the last lambdas used [position means degree of derivative]
std::vector<T> last_lambda_derivatives;
//! std::vector storing the updaters to be called [position means degree of derivative]
std::vector<std::function<void(T)>> updaters;
//! pointer collecting the lambda optimizer on which the updates have to be performed
LambdaOptim * start_ptr = nullptr;
// -- PRIVATE MEMBERS --
//! Function that selectively updates just the essential terms for the needed task
/*!
This functions calls all the updaters on the given pointer from start to finish
[e.g. start==1, finish==2 means: call first and second updater to prepare
Lambda Optimizer for first and second derivative computation]
\param start first updater to be called, increase sequentially from this
\param finish last updater to be called (included)
\param lambda the actual value of lambda to be used for the computation
*/
inline void call_from_to(UInt start, UInt finish, T lambda)
{
for(UInt i=start; i<=finish; ++i) //loop from start to finish included
{
updaters[i](lambda); // call the update
last_lambda_derivatives[i] = lambda; // keep track of the performed update
}
}
//! Function that initializes the updaters given the pinter to the optimizatio method
/*!
\param lopt_ptr pointer to the Lambda Optimizer from which to capture the updaters
*/
inline void updaters_setter(LambdaOptim * lopt_ptr)
{
this->updaters.reserve(3); // all methods need up to the second derivative
this->updaters.push_back(std::bind(&LambdaOptim::zero_updater, lopt_ptr, std::placeholders::_1));
this->updaters.push_back(std::bind(&LambdaOptim::first_updater, lopt_ptr, std::placeholders::_1));
this->updaters.push_back(std::bind(&LambdaOptim::second_updater, lopt_ptr, std::placeholders::_1));
}
template<typename S=T>
typename std::enable_if<std::is_same<S,lambda::type<1>>::value, lambda::type<1>>::type
lambda_init(Real value) {return value;}
template<typename S=T>
typename std::enable_if<std::is_same<S,lambda::type<2>>::value, lambda::type<2>>::type
lambda_init(Real value) {return lambda::make_pair(value, value);}
public:
// -- CONSTRUCTORS --
//! Default constructor
GOF_updater(void) = default;
//! Initializier for the first lambdas to be stored
/*!
\param first_lambdas the first lambdas to be stored in the vector of last_lambda_derivatives
*/
inline void initialize(const std::vector<T> & first_lambdas)
{
last_lambda_derivatives = first_lambdas;
}
// -- PUBLIC UPDATER --
//! Public function that selectively updates just the essential terms for the needed task
/*!
This functions calls all the updaters on the given pointer up to finish
[e.g. finish==2 calls, if not already updated, zero first and second updater]
\param finish last updater to be called (included)
\param lambda the actual value of lambda to be used for the computation
\param lopt_ptr the object from which to perform the update
*/
inline void call_to(UInt finish, T lambda, LambdaOptim * lopt_ptr)
{
if(start_ptr != lopt_ptr) // new pointer to be stored (or first time we store)
{
//Debugging purpose
//Rprintf("--- Set updaters ---\n");
initialize(std::vector<T>{lambda_init(-1.),lambda_init(-1.),lambda_init(-1.)}); // dummy initialize the last lambdas
updaters_setter(lopt_ptr); // set all the updaters from the given pointer
start_ptr = lopt_ptr; // keep track of the pointer to avoid this procedure next time
}
bool found = false; // cycle breaker
for(UInt i = 0; i<=finish && found==false; ++i) // loop until the desired update level (finish)
if(lambda != last_lambda_derivatives[i]) // if we have found the first not updated derivative
{
call_from_to(i, finish, lambda); // update from that derivative to the needed level (finish)
found = true; // break the cycle since the update is complete
}
}
};
#endif
| [
"csardi.gabor+cran@gmail.com"
] | csardi.gabor+cran@gmail.com |
1a81f9b54a75feb6d3289f8db0505d21cc7ddbb9 | 78918391a7809832dc486f68b90455c72e95cdda | /boost_lib/boost/range/algorithm_ext/push_back.hpp | c19a89d36301b209d8c50f0a1f66597d69cd58f2 | [
"MIT"
] | permissive | kyx0r/FA_Patcher | 50681e3e8bb04745bba44a71b5fd04e1004c3845 | 3f539686955249004b4483001a9e49e63c4856ff | refs/heads/master | 2022-03-28T10:03:28.419352 | 2020-01-02T09:16:30 | 2020-01-02T09:16:30 | 141,066,396 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | hpp | // Boost.Range library
//
// Copyright Neil Groves 2009. Use, modification and
// distribution is subject to 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)
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_EXT_PUSH_BACK_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_EXT_PUSH_BACK_HPP_INCLUDED
#include <boost/range/config.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/difference_type.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/detail/implementation_help.hpp>
#include <boost/assert.hpp>
namespace boost
{
namespace range
{
template< class Container, class Range >
inline Container& push_back( Container& on, const Range& from )
{
BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<Container> ));
BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const Range> ));
BOOST_ASSERT_MSG(!range_detail::is_same_object(on, from),
"cannot copy from a container to itself");
on.insert( on.end(), boost::begin(from), boost::end(from) );
return on;
}
} // namespace range
using range::push_back;
} // namespace boost
#endif // include guard
| [
"k.melekhin@gmail.com"
] | k.melekhin@gmail.com |
b7be2ed731804e3b982136c804cfa8c70799af2b | f662473e9aa4765023181de20eb8eaf149ed96e8 | /PreyPredator/PreyPredator/src/Hybrid.cpp | e23df72f820356692ad3ca22042d03969c563281 | [] | no_license | LordGee/prey_pred | 5b0235e66c2830a3d1db569c52c9eb3387f129a8 | 55b837b19a70f044508070b8e2148e08a3668ee1 | refs/heads/master | 2021-04-06T01:55:56.423724 | 2018-04-16T11:40:35 | 2018-04-16T11:40:35 | 124,538,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,587 | cpp | #include "Hybrid.h"
#include <cstdlib>
#include <ctime>
#include <string>
#include "omp.h"
void Hybrid::PopulateGrid() {
srand(seed);
const int contributionY = abs(height / info.numProcs);
int processorCounter = 1;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// Only the master manages the initial declaration of each cell state
if (info.procRank == MASTER) {
float random = (float)(rand()) / (float)(RAND_MAX);
if (random < prey) {
mainGrid[x][y].type = 1;
mainGrid[x][y].age = 1;
} else if (random < prey + pred) {
mainGrid[x][y].type = -1;
mainGrid[x][y].age = 1;
} else {
mainGrid[x][y].type = 0;
mainGrid[x][y].age = 0;
}
}
// determine if the y value has exceeded the current processor split
if (y >= contributionY * (processorCounter + 1)) {
if (processorCounter != info.numProcs - 1) {
processorCounter++;
}
}
// If within the current processor copy the master cell to the appropriate processor
if (y >= contributionY * processorCounter && y < contributionY * (processorCounter + 1)) {
if (info.procRank == MASTER) {
MPI_Send(&mainGrid[x][y], 2, MPI_INT, processorCounter, y, MPI_COMM_WORLD);
}
if (info.procRank == processorCounter) {
MPI_Recv(&mainGrid[x][y], 2, MPI_INT, 0, y, MPI_COMM_WORLD, &status);
}
}
}
// at the end of each y iteration reset processor to 1
processorCounter = 1;
}
}
void Hybrid::DrawSimToScreen(const int COUNT) {
noDraw = false;
int counter = 0;
clock_t t1, t2;
float timer;
SDL_Event event;
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
// Only master process should draw to screen
if (info.procRank == MASTER) {
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("PREY vs PREDATOR Simulation", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, 0);
renderer = SDL_CreateRenderer(window, -1, 0);
}
while (counter < COUNT) {
t1 = clock();
livePrey = 0, livePred = 0, empty = 0;
deadPrey = 0, deadPred = 0;
UpdateSimulation();
// Only master process should draw to screen
if (info.procRank == MASTER) {
SDL_PollEvent(&event);
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 125);
SDL_RenderClear(renderer);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (mainGrid[x][y].type > 0) {
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderDrawPoint(renderer, x, y);
livePrey++;
} else if (mainGrid[x][y].type < 0) {
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderDrawPoint(renderer, x, y);
livePred++;
} else {
empty++;
}
}
}
SDL_RenderPresent(renderer);
}
counter++;
t2 = clock();
timer = (float)(t2 - t1) / CLOCKS_PER_SEC;
// Only master process should draw to screen
if (info.procRank == MASTER) {
UpdateStatistics(timer, counter, livePrey, livePred, empty, deadPrey, deadPred);
}
}
SDL_DestroyWindow(window);
SDL_Quit();
}
void Hybrid::RunSimNoDraw(const int COUNT) {
noDraw = false;
int counter = 0;
clock_t t1, t2;
float timer;
while (counter < COUNT) {
t1 = clock();
deadPrey = 0, deadPred = 0;
livePrey = 0, livePred = 0, empty = 0;
UpdateSimulation();
// Only master process should draw to screen
if (info.procRank == MASTER) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (mainGrid[x][y].type > 0) {
livePrey++;
} else if (mainGrid[x][y].type < 0) {
livePred++;
} else {
empty++;
}
}
}
}
counter++;
t2 = clock();
timer = (float)(t2 - t1) / CLOCKS_PER_SEC;
// Only master process should draw to screen
if (info.procRank == MASTER) {
UpdateStatistics(timer, counter, livePrey, livePred, empty, deadPrey, deadPred);
}
}
}
void Hybrid::RunNoDisplay(const int COUNT) {
noDraw = true;
int counter = 0;
clock_t t1, t2;
float timer;
while (counter < COUNT) {
t1 = clock();
UpdateSimulation();
counter++;
t2 = clock();
timer = (float)(t2 - t1) / CLOCKS_PER_SEC;
// Only master process should log timer information
if (info.procRank == MASTER) {
timerLog.push_back(timer);
}
}
// Only master process should draw to screen
if (info.procRank == MASTER) {
float average = 0.0f;
for (unsigned int i = 0; i < timerLog.size(); i++) {
average += timerLog[i];
}
average = average / timerLog.size();
std::cout << "Test Completed\nAverage time for each iteration - " << average << std::endl;
fflush(stdout);
}
}
void Hybrid::UpdateStatistics(float time, int iteration, int lPrey, int lPred, int empty, int dPrey, int dPred) {
// system("cls"); // Removed MPI does not like this feature
printf(" WELCOME TO THE PREY VS PREDATOR SIMULATOR\n");
printf("\t by Gordon Johnson (k1451760)\n\n");
printf(" -------------------------------------------\n");
printf(" | Statistic \t| Results\n");
printf(" -------------------------------------------\n");
printf(" | Speed \t| %f\n", time);
printf(" | Iteration Count \t| %d\n", iteration);
printf(" -------------------------------------------\n");
printf(" | Living Prey \t| %d\n", lPrey);
printf(" | Dying Prey \t| %d\n", dPrey);
printf(" -------------------------------------------\n");
printf(" | Living Predators \t| %d\n", lPred);
printf(" | Dying Predators \t| %d\n", dPred);
printf(" -------------------------------------------\n");
printf(" | Empty Cells \t| %d\n", empty);
printf(" | Total Cells \t| %d\n", empty + lPrey + lPred);
printf(" -------------------------------------------\n");
fflush(stdout);
}
void Hybrid::UpdateSimulation() {
// generate COPY cell array
// Loop COPY to init and zero off values
// OpenMP Target
#pragma omp parallel num_threads(numThreads)
{
#pragma omp for
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
copyGrid[x][y].type = 0;
copyGrid[x][y].age = 0;
}
}
}
const int contributionY = abs(height / info.numProcs);
srand(time(NULL));
// prepare top and bottom bounderies for evaluating neighbouring states
for (int x = 0; x < width; x++) {
if (info.procRank == MASTER) {
MPI_Send(&mainGrid[x][0], 2, MPI_INT, info.numProcs - 1, x, MPI_COMM_WORLD);
MPI_Recv(&mainGrid[x][height - 1], 2, MPI_INT, info.numProcs - 1, x + width, MPI_COMM_WORLD, &status);
} else if (info.procRank == info.numProcs - 1) {
MPI_Send(&mainGrid[x][height - 1], 2, MPI_INT, 0, x + width, MPI_COMM_WORLD);
MPI_Recv(&mainGrid[x][0], 2, MPI_INT, 0, x, MPI_COMM_WORLD, &status);
}
if (info.procRank != info.numProcs - 1) {
MPI_Send(&mainGrid[x][(contributionY * (info.procRank + 1)) - 1], 2, MPI_INT, info.procRank + 1, x, MPI_COMM_WORLD);
MPI_Recv(&mainGrid[x][(contributionY * (info.procRank + 1))], 2, MPI_INT, info.procRank + 1, x, MPI_COMM_WORLD, &status);
}
if (info.procRank != MASTER) {
MPI_Send(&mainGrid[x][contributionY * info.procRank], 2, MPI_INT, info.procRank - 1, x, MPI_COMM_WORLD);
MPI_Recv(&mainGrid[x][(contributionY * info.procRank) - 1], 2, MPI_INT, info.procRank - 1, x, MPI_COMM_WORLD, &status);
}
}
MPI_Barrier(MPI_COMM_WORLD);
// loop through all cells and determin neighbour count
// OpenMP Target for main loop
#pragma omp parallel num_threads(numThreads)
{
#pragma omp for
for (int x = 0; x < width; x++) {
// Only unique processer dependent y range is processed
for (int y = contributionY * info.procRank; y < contributionY * (info.procRank + 1); y++) {
int preyCount = 0, preyAge = 0, predCount = 0, predAge = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (!(i == 0 && j == 0)) {
int xTest = x + i, yTest = y + j;
if (yTest < 0) { yTest = yTest + height; }
if (xTest < 0) { xTest = xTest + width; }
if (yTest >= height) { yTest = yTest - height; }
if (xTest >= width) { xTest = xTest - width; }
if (mainGrid[xTest][yTest].type > 0) {
preyCount++;
if (mainGrid[xTest][yTest].age >= PREY_BREEDING) {
preyAge++;
}
} else if (mainGrid[xTest][yTest].type < 0) {
predCount++;
if (mainGrid[xTest][yTest].age >= PRED_BREEDING) {
predAge++;
}
}
}
}
}
if (mainGrid[x][y].type > 0) {
//manage prey
if (predCount >= 5 || preyCount == 8 || mainGrid[x][y].age > PREY_LIVE) {
copyGrid[x][y].type = 0;
copyGrid[x][y].age = 0;
deadPrey++;
} else {
copyGrid[x][y].type = mainGrid[x][y].type;
copyGrid[x][y].age = mainGrid[x][y].age + 1;
}
}
else if (mainGrid[x][y].type < 0) {
// manage predator
float random = (float)(rand()) / (float)(RAND_MAX);
if ((predCount >= 6 && preyCount == 0) || random <= PRED_SUDDEN_DEATH || copyGrid[x][y].age > PRED_LIVE) {
copyGrid[x][y].type = 0;
copyGrid[x][y].age = 0;
deadPred++;
} else {
copyGrid[x][y].type = mainGrid[x][y].type;
copyGrid[x][y].age = mainGrid[x][y].age + 1;
}
} else {
// manage empty space
if (preyCount >= NUM_BREEDING && preyAge >= NUM_OF_AGE && predCount < NUM_OF_WITNESSES) {
copyGrid[x][y].type = 1;
copyGrid[x][y].age = 1;
} else if (predCount >= NUM_BREEDING && predAge >= NUM_OF_AGE && preyCount < NUM_OF_WITNESSES) {
copyGrid[x][y].type = -1;
copyGrid[x][y].age = 1;
} else {
copyGrid[x][y].type = 0;
copyGrid[x][y].age = 0;
}
}
}
}
}
// copy the COPY back to the main array
// OpenMP Target
#pragma omp parallel num_threads(numThreads)
{
#pragma omp for
for (int x = 0; x < width; x++) {
// Only unique processer dependent y range is processed
for (int y = contributionY * info.procRank; y < contributionY * (info.procRank + 1); y++) {
mainGrid[x][y] = copyGrid[x][y];
}
}
}
// If setup dissplay is drawing stats to screen the MASTER process needs all grid information sent to it
if (!noDraw) {
int processorCounter = info.numProcs - 1;
while (processorCounter != 0) {
for (int x = 0; x < width; x++) {
for (int y = contributionY * processorCounter; y < height; y++) {
if (info.procRank == processorCounter) {
MPI_Rsend(&mainGrid[x][y], 2, MPI_INT, processorCounter - 1, y * (x + processorCounter), MPI_COMM_WORLD);
}
if (info.procRank == processorCounter - 1) {
MPI_Recv(&mainGrid[x][y], 2, MPI_INT, processorCounter, y * (x + processorCounter), MPI_COMM_WORLD, &status);
}
}
}
processorCounter--;
}
}
}
| [
"gordon.johnson@mychaos.co.uk"
] | gordon.johnson@mychaos.co.uk |
3c7a6bd68ead7aadbd71ec9ea7fd7851cffa0ef9 | 1ecdc79c6a4cf3a1ad71faabe74d8669e611bfa4 | /proj/src/user/type.cpp | 4fc9f239805b7e9799711c14442761df19b804cc | [] | no_license | topnax/kiv-os-sp | f519e87f767f48655cb60fffa95555bd68fe6f61 | b0dadc60db4e817cd35ea504e167ae7cdb128ee7 | refs/heads/master | 2023-02-18T23:54:14.457281 | 2021-01-02T11:18:52 | 2021-01-02T11:18:52 | 300,584,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,286 | cpp | //
// Created by Stanislav Král on 31.10.2020.
//
#include "rtl.h"
#include "error_handler.h"
extern "C" size_t __stdcall type(const kiv_hal::TRegisters ®s) {
const auto std_in = static_cast<kiv_os::THandle>(regs.rax.x);
const auto std_out = static_cast<kiv_os::THandle>(regs.rbx.x);
// flag indicating whether the file to be read has not been found
bool handle_found = false;
// flag indicating whether a file has been opened
bool file_opened = false;
// the handle to be used to read from
kiv_os::THandle handle_to_read_from;
char *file_path = reinterpret_cast<char *>(regs.rdi.r);
// check whether user has specified a file to read from
if (regs.rdi.r != 0 && strlen(file_path) > 0) {
kiv_os::NOS_Error error;
// try to open a file at the specified path
if (kiv_os_rtl::Open_File(file_path, kiv_os::NOpen_File::fmOpen_Always, 0, handle_to_read_from, error)) {
file_opened = true;
handle_found = true;
} else {
handle_error_message(error, std_out);
}
} else {
// a file to be read from not specified, read from std_in
handle_found = true;
handle_to_read_from = std_in;
}
// any file has been found
if (handle_found) {
// define the size of the read buffer
const size_t buffer_size = 100;
char buff[buffer_size];
size_t read;
size_t written;
// read till EOF
bool eot_found = false;
while (!eot_found && kiv_os_rtl::Read_File(handle_to_read_from, buff, buffer_size, read)) {
for (int i = 0; i < read; i++) {
// check whether EOT has been read, if so, then abort reading from the handle and do not print EOT char
if (static_cast<kiv_hal::NControl_Codes>(buff[i]) == kiv_hal::NControl_Codes::EOT) {
eot_found = true;
read = i;
break;
}
}
if (!kiv_os_rtl::Write_File(std_out, buff, read, written)) {
break;
}
}
// close only if opening a file
if (file_opened) {
kiv_os_rtl::Close_Handle(handle_to_read_from);
}
}
return 0;
}
| [
"stanislav.kral@smart-software.cz"
] | stanislav.kral@smart-software.cz |
e4d6860ecb5c8cd14bd81eb802cdda153a5c4b61 | 48e9625fcc35e6bf790aa5d881151906280a3554 | /Sources/Elastos/LibCore/src/elastosx/xml/transform/stream/CStreamResult.cpp | 313887450d1fe12c91be99daa4f88751b10c8e99 | [
"Apache-2.0"
] | permissive | suchto/ElastosRT | f3d7e163d61fe25517846add777690891aa5da2f | 8a542a1d70aebee3dbc31341b7e36d8526258849 | refs/heads/master | 2021-01-22T20:07:56.627811 | 2017-03-17T02:37:51 | 2017-03-17T02:37:51 | 85,281,630 | 4 | 2 | null | 2017-03-17T07:08:49 | 2017-03-17T07:08:49 | null | UTF-8 | C++ | false | false | 2,697 | cpp | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "Elastos.CoreLibrary.IO.h"
#include "CStreamResult.h"
#include "FilePathToURI.h"
namespace Elastosx {
namespace Xml {
namespace Transform {
namespace Stream {
CAR_OBJECT_IMPL(CStreamResult)
CAR_INTERFACE_IMPL_2(CStreamResult, Object, IStreamResult, IResult)
ECode CStreamResult::constructor()
{
return NOERROR;
}
ECode CStreamResult::constructor(
/* [in] */ IOutputStream* outputStream)
{
return SetOutputStream(outputStream);
}
ECode CStreamResult::constructor(
/* [in] */ IWriter* writer)
{
return SetWriter(writer);
}
ECode CStreamResult::constructor(
/* [in] */ const String& systemId)
{
mSystemId = systemId;
return NOERROR;
}
ECode CStreamResult::constructor(
/* [in] */ IFile* f)
{
return SetSystemId(f);
}
ECode CStreamResult::SetOutputStream(
/* [in] */ IOutputStream* outputStream)
{
mOutputStream = outputStream;
return NOERROR;
}
ECode CStreamResult::GetOutputStream(
/* [out] */ IOutputStream** stream)
{
VALIDATE_NOT_NULL(stream);
*stream = mOutputStream;
REFCOUNT_ADD(*stream);
return NOERROR;
}
ECode CStreamResult::SetWriter(
/* [in] */ IWriter* writer)
{
mWriter = writer;
return NOERROR;
}
ECode CStreamResult::GetWriter(
/* [out] */ IWriter** writer)
{
VALIDATE_NOT_NULL(writer);
*writer = mWriter;
REFCOUNT_ADD(*writer);
return NOERROR;
}
ECode CStreamResult::SetSystemId(
/* [in] */ const String& systemId)
{
mSystemId = systemId;
return NOERROR;
}
ECode CStreamResult::SetSystemId(
/* [in] */ IFile* f)
{
assert(f);
String path;
f->GetAbsolutePath(&path);
mSystemId = FilePathToURI::Filepath2URI(path);
return NOERROR;
}
ECode CStreamResult::GetSystemId(
/* [out] */ String* id)
{
VALIDATE_NOT_NULL(id);
*id = mSystemId;
return NOERROR;
}
} // namespace Stream
} // namespace Transform
} // namespace Xml
} // namespace Elastosx
| [
"cao.jing@kortide.com"
] | cao.jing@kortide.com |
95de79e47e84727e4cee3213157eb374eef95d97 | bc6acbcfa7f8124493ef72ae2597fa5ef95bd126 | /Secventa_numere_maxima.cpp | cba0061b0f827c039740c228914f0fe008296add | [] | no_license | adyoblu/CPP | e9aabb0d479b6b1a3f71f5703e262847432b4471 | 7c394f3046a7ee0738d80891aa8fa65658570be5 | refs/heads/master | 2021-06-16T12:38:40.918830 | 2021-03-08T10:44:32 | 2021-03-08T10:44:32 | 176,030,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | cpp | #include <iostream>
#include <limits>
using namespace std;
//secventa de suma maxima complexitate O(n)
int main()
{
int n;
int a[100];
int scrt = 0;
int sum = INT_MIN;
cout<<"n=";
cin>>n;
for(int i = 0; i <=n-1; i++){
cout<<"a["<<i<<"]=";
cin>>a[i];
}
for(int i = 0; i <= n-1; i++)
{
if(scrt < 0)
{scrt = a[i];}
else
{ scrt += a[i];}
if(scrt > sum) sum = scrt;
}
//secventa de suma maxima complexitate O(n^2)
int smax = a[0];
int scr;
for(int i=0;i<=n-1;i++)
{
scr = 0;
for(int j = i;j<= n-1;j++)
{
scr += a[j];
if(smax <= scr) smax = scr;
}
}
cout<<"Secventa suma maxima complexitate o(n) este : "<<sum<<endl;
cout<<"Secventa suma maxima complexitate o(n^2) este : "<<smax;
return 0;
}
| [
"adyoblu2000@yahoo.com"
] | adyoblu2000@yahoo.com |
06c9c5f8b52a8eac8b59e3a2203194faa389f42e | 5ee0eb940cfad30f7a3b41762eb4abd9cd052f38 | /Case_save/case3/1400/phi | 4b7d0c53f9015ebfdaf75dab3e77344fb2b3af7e | [] | no_license | mamitsu2/aircond5_play4 | 052d2ff593661912b53379e74af1f7cee20bf24d | c5800df67e4eba5415c0e877bdeff06154d51ba6 | refs/heads/master | 2020-05-25T02:11:13.406899 | 2019-05-20T04:56:10 | 2019-05-20T04:56:10 | 187,570,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,643 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "1400";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 0 -1 0 0 0 0];
internalField nonuniform List<scalar>
852
(
-0.00304822
0.00310798
-0.00413956
0.00109134
-0.00494699
0.000807432
-0.00555872
0.000611719
-0.00594263
0.000383911
-0.00607445
0.000131816
-0.00593291
-0.000141543
-0.00550935
-0.000423572
-0.00483407
-0.000675277
-0.00397709
-0.000856986
-0.00303238
-0.000944718
-0.00209895
-0.000933434
-0.00126607
-0.000832884
-0.000579704
-0.000686367
-0.00057763
-0.000822809
0.000826474
-0.000493186
-0.000329627
0.000184046
-0.000677236
0.000731528
-0.000547486
0.00110361
-0.00037209
0.00134004
-0.000236433
0.0014696
-0.000129559
0.00153289
-6.32904e-05
0.00156822
-3.534e-05
0.00158992
-2.17081e-05
0.00160221
-1.22887e-05
0.00160656
-4.35982e-06
0.00160117
5.39197e-06
0.00157726
2.3902e-05
0.00151115
6.61046e-05
0.00136307
0.000148074
0.0011192
0.000243869
0.000814315
0.000304881
0.000819253
-0.00217055
0.00543917
-0.00322291
0.00214369
-0.00404798
0.0016325
-0.00464892
0.00121266
-0.00502635
0.000761337
-0.00516421
0.000269666
-0.00503887
-0.000266882
-0.00464912
-0.000813324
-0.00403779
-0.00128662
-0.00328106
-0.00161372
-0.00246712
-0.00175867
-0.00167685
-0.00172371
-0.00098227
-0.00152746
-0.000455321
-0.00121332
-0.000217235
-0.00081572
9.24023e-05
-0.000309693
9.23462e-05
0.000348871
0.0004882
0.000794048
-0.000774809
0.00107551
-0.000958704
0.00131718
-0.000789157
0.00150427
-0.000559184
0.0016195
-0.000351666
0.00163903
-0.000149096
0.0016438
-6.80618e-05
0.00164951
-4.10621e-05
0.00165428
-2.64747e-05
0.00165739
-1.54071e-05
0.00165893
-5.90682e-06
0.00165804
6.27757e-06
0.00165089
3.10516e-05
0.00160676
0.000110231
0.00141883
0.000336002
0.00109723
0.000565467
0.000697766
0.000704336
0.00152961
-0.00151457
0.00719923
-0.00241695
0.00304607
-0.00314373
0.00235927
-0.00365374
0.00172266
-0.00397586
0.00108346
-0.0040876
0.000381394
-0.0039451
-0.000409377
-0.00355344
-0.00120499
-0.00297929
-0.00186078
-0.00230766
-0.00228535
-0.0016173
-0.00244903
-0.000964623
-0.00237639
-0.000396216
-0.00209588
5.64019e-05
-0.00166594
0.000353075
-0.0011124
0.000489762
-0.000446384
0.000582104
0.00162325
-0.00112368
0.00185699
-0.00100855
0.00181516
-0.000916878
0.00180696
-0.000780959
0.00183316
-0.000585394
0.00186382
-0.000382332
0.00171488
0.00164697
0.00160605
0.00157973
0.00156447
0.00155871
0.00156514
0.00159634
0.00170672
0.00139928
0.000643438
0.00103215
0.000932595
0.000584737
0.00115174
0.00213338
-0.00105215
0.00856917
-0.00176192
0.00375583
-0.00223567
0.00283302
-0.00256018
0.00204716
-0.00275224
0.00127551
-0.0027668
0.000395959
-0.00254161
-0.000634572
-0.00211887
-0.00162773
-0.00159297
-0.00238669
-0.00104269
-0.00283563
-0.000521732
-0.00296999
-5.32279e-05
-0.00284489
0.000350594
-0.0024997
0.000691611
-0.00200696
0.0010041
-0.00142489
0.0013749
-0.000817194
0.00225994
-0.000302941
0.00268071
-0.000410529
0.00226209
-0.00070507
0.00211198
-0.00085844
0.00197914
-0.000784039
0.00186494
-0.000666766
0.0017991
-0.000519554
0.00175945
-0.000342685
0.00190507
-0.000145783
0.00199391
-8.89976e-05
0.00206216
-6.84e-05
0.0021104
-4.83966e-05
0.00212293
-1.26907e-05
0.00207807
4.47043e-05
0.00195129
0.000126616
0.00170994
0.0002412
0.00129682
0.000412957
0.00114542
0.000794842
0.000821768
0.00125624
0.000334723
0.00163879
0.00249301
-0.000732758
0.00968116
-0.00126616
0.00428923
-0.00135049
0.00291734
-0.00138645
0.00208311
-0.0013607
0.00124976
-0.00115623
0.000191476
-0.000766621
-0.00102418
-0.000319239
-0.00207512
0.000100965
-0.0028069
0.000453731
-0.0031884
0.000730927
-0.00324719
0.000939336
-0.00305331
0.00110536
-0.00266573
0.0012531
-0.00215471
0.00141561
-0.0015874
0.00163987
-0.00104146
0.00196739
-0.000630459
0.00208061
-0.000523756
0.0019795
-0.000603959
0.0017841
-0.000663048
0.0016153
-0.000615245
0.00147521
-0.000526674
0.00137708
-0.000421433
0.00133637
-0.000301978
0.00138498
-0.000194393
0.00144182
-0.000145836
0.00150128
-0.000127868
0.00155873
-0.00010585
0.00160157
-5.55371e-05
0.00160897
3.73031e-05
0.00156108
0.000174507
0.00144686
0.000355416
0.00126845
0.000591366
0.0011102
0.000953088
0.000936514
0.00142992
0.000541087
0.00203421
0.000425526
0.00260856
-0.00111039
0.00153571
-0.00157472
0.000464125
-0.00152082
-0.000634387
0.0107467
-0.000989814
0.00464465
-0.000527431
0.00245496
-8.5284e-05
0.00164096
0.000332495
0.000831981
0.000865747
-0.000341779
0.00138919
-0.00154763
0.00176556
-0.00245149
0.00197512
-0.00301646
0.00204456
-0.00325785
0.00201321
-0.00321585
0.0019124
-0.0029525
0.00178194
-0.00253527
0.00165875
-0.00203152
0.00157316
-0.00150181
0.00154604
-0.00101434
0.00156555
-0.000649979
0.00152321
-0.00048142
0.00138025
-0.000460998
0.00118148
-0.000464284
0.00100196
-0.000435728
0.000861573
-0.000386289
0.000768895
-0.000328758
0.000734661
-0.000267747
0.000759396
-0.000219132
0.000815217
-0.000201661
0.000887503
-0.000200158
0.000969797
-0.000188146
0.0010552
-0.000140943
0.00112727
-3.47736e-05
0.00116794
0.000133834
0.0011786
0.00034476
0.0011669
0.00060306
0.00118246
0.000937527
0.00127866
0.00133371
0.00146324
0.00184962
0.00195835
0.00211345
0.00224095
0.0012531
0.00185048
0.000854586
0.000394227
-0.000658381
0.0118835
-0.000504043
0.00449031
0.000740629
0.00121028
0.00168454
0.000697039
0.00256234
-4.5822e-05
0.0033563
-0.00113574
0.00383072
-0.00202205
0.00398994
-0.00261072
0.00388555
-0.00291206
0.00358598
-0.00295829
0.00316354
-0.0027934
0.00268281
-0.00247178
0.00220244
-0.0020549
0.00176924
-0.00159833
0.00141045
-0.00114303
0.00113935
-0.000743236
0.000945769
-0.0004564
0.000777661
-0.000313315
0.000596349
-0.000279689
0.000413142
-0.00028108
0.000255961
-0.000278549
0.000138438
-0.00026877
6.58508e-05
-0.000256174
4.25157e-05
-0.000244415
6.46342e-05
-0.000241253
0.000116054
-0.000253084
0.000185229
-0.000269336
0.00027012
-0.000273041
0.000374727
-0.000245553
0.000503623
-0.000163672
0.000636858
5.96021e-07
0.000765207
0.000216408
0.00090664
0.000461623
0.00109988
0.000744285
0.00139807
0.00103551
0.00187539
0.0013723
0.00261644
0.0013724
0.00321484
0.000654691
0.00327786
0.000791569
0.00374122
0.00278587
0.00963349
0.0035755
0.00370068
0.00422399
0.000561789
0.00526635
-0.000345325
0.00619327
-0.000972744
0.00662755
-0.00157002
0.00661423
-0.00200874
0.00623055
-0.00222705
0.00556964
-0.00225116
0.00473406
-0.00212271
0.00382306
-0.00188241
0.00291938
-0.00156811
0.00208946
-0.00122497
0.00137928
-0.00088816
0.000805248
-0.000568994
0.000378419
-0.00031641
8.63964e-05
-0.00016438
-0.000118401
-0.000108521
-0.000283069
-0.000115023
-0.000423818
-0.000140335
-0.000538527
-0.000163844
-0.000623971
-0.000183328
-0.000679234
-0.000200915
-0.000704594
-0.000219057
-0.000704769
-0.000241082
-0.000690062
-0.000267793
-0.000666864
-0.000292536
-0.000634128
-0.00030578
-0.000582362
-0.000297322
-0.000491061
-0.000254976
-0.000330258
-0.00016021
-0.000128971
1.51189e-05
9.79555e-05
0.000234694
0.000379838
0.000462399
0.000723189
0.000692155
0.00117982
0.000915671
0.00166521
0.000887001
0.00180416
0.000515741
0.000974168
0.00162156
0.00500798
0.0102272
0.013924
0.0129863
0.00149949
0.0123627
0.000278276
0.011581
-0.000191094
0.0105105
-0.000499546
0.00917369
-0.000671895
0.00768514
-0.000738504
0.00614837
-0.000714387
0.0046525
-0.000626851
0.00327529
-0.000505193
0.00206631
-0.000359129
0.00105703
-0.000215703
0.000254565
-8.56962e-05
-0.000328084
1.36521e-05
-0.000694533
5.00363e-05
-0.000905929
4.70133e-05
-0.00103921
2.47551e-05
-0.00114514
-9.09598e-06
-0.00123972
-4.57594e-05
-0.00132355
-8.00175e-05
-0.00139597
-0.000110904
-0.00145798
-0.000138915
-0.00151237
-0.000164668
-0.00156481
-0.000188641
-0.00162368
-0.000208929
-0.0016968
-0.000219416
-0.00179184
-0.000210751
-0.00191826
-0.000170905
-0.00208848
-8.47571e-05
-0.00230882
6.01309e-05
-0.00256626
0.000272552
-0.00290347
0.0005719
-0.00341879
0.000977714
-0.00420933
0.0014827
-0.00533087
0.0020372
-0.00689181
0.00244794
-0.00874364
0.00236757
-0.00811908
0.00099699
-0.00278615
0.00438004
0.00336036
0.00335097
0.00130735
0.00362139
-0.000461518
0.00353547
-0.000413621
0.00305448
-0.000190905
0.00234757
-3.15962e-05
0.00152915
0.000104033
0.000695456
0.000206841
-7.38926e-05
0.000264154
-0.000708584
0.000275561
-0.00117552
0.000251228
-0.00148443
0.000223215
-0.00165953
0.000188744
-0.00175568
0.000146192
-0.00181509
0.000106417
-0.00186231
7.19716e-05
-0.00191251
4.10978e-05
-0.00197175
1.34849e-05
-0.00203911
-1.26678e-05
-0.0021104
-3.96173e-05
-0.00218607
-6.32467e-05
-0.00226869
-8.20497e-05
-0.00236175
-9.5581e-05
-0.00246833
-0.000102354
-0.00258896
-9.87843e-05
-0.00272054
-7.91774e-05
-0.00285459
-3.68629e-05
-0.00297694
3.75899e-05
-0.00308012
0.000163308
-0.00316839
0.00036082
-0.00325181
0.000655323
-0.00334188
0.00106778
-0.003442
0.00158281
-0.0034934
0.0020886
-0.0034057
0.00236024
-0.00298167
0.00194353
-0.00165468
-0.000330004
-0.00435624
-0.000785466
0.00423035
-0.000368255
0.000890139
-0.00106711
0.000237342
-0.00160602
0.000125284
-0.00197278
0.000175849
-0.00224077
0.000236395
-0.00242545
0.000288711
-0.00254885
0.000330241
-0.002625
0.000340299
-0.00266215
0.000312707
-0.00267174
0.000260819
-0.00265408
0.000205547
-0.00261899
0.000153659
-0.00258177
0.000108961
-0.00255049
7.51349e-05
-0.00252917
5.06535e-05
-0.0025202
3.2128e-05
-0.00252354
1.68228e-05
-0.00253816
1.94157e-06
-0.0025632
-1.45734e-05
-0.00259821
-2.82461e-05
-0.00264231
-3.79495e-05
-0.00269451
-4.33857e-05
-0.00275307
-4.37993e-05
-0.00281447
-3.73842e-05
-0.00287264
-2.10137e-05
-0.00291882
9.3187e-06
-0.00293781
5.65722e-05
-0.00290742
0.000132913
-0.00280066
0.000254061
-0.00258227
0.000436931
-0.00222343
0.000708933
-0.00172609
0.00108548
-0.00107317
0.00143566
-4.49029e-05
0.00133197
0.00127392
0.000624705
0.001594
-0.000650085
-0.00266914
-0.0078858
-0.0111456
-0.00686035
-0.00594246
-0.00568625
-0.00554583
-0.00535717
-0.00510958
-0.0048108
-0.00447122
-0.00412198
-0.00380041
-0.0035306
-0.00331582
-0.00315266
-0.00303393
-0.00294879
-0.00288791
-0.00284537
-0.00281802
-0.00280548
-0.00280946
-0.00282717
-0.00285468
-0.00288776
-0.00292143
-0.00294888
-0.00296019
-0.00294142
-0.0028757
-0.00273394
-0.00247138
-0.00202631
-0.00130964
-0.000216851
0.00122551
0.00256386
0.00319492
0.00255143
)
;
boundaryField
{
floor
{
type calculated;
value nonuniform List<scalar>
29
(
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
-4.94301e-06
-1.25925e-05
-1.9044e-05
-2.49035e-05
-2.0782e-06
-3.66923e-06
-1.06017e-05
-1.13757e-05
-1.02401e-05
)
;
}
ceiling
{
type calculated;
value nonuniform List<scalar>
43
(
-5.8917e-05
-5.67019e-05
-5.49238e-05
-2.77594e-05
-1.88701e-05
-1.51338e-05
-1.28199e-05
-1.11955e-05
-1.00724e-05
-9.33874e-06
-8.94644e-06
-8.86052e-06
-8.9966e-06
-9.23702e-06
-9.50391e-06
-9.76509e-06
-1.001e-05
-1.023e-05
-1.04111e-05
-1.05376e-05
-1.06e-05
-1.05959e-05
-1.05402e-05
-1.04413e-05
-1.0305e-05
-1.01354e-05
-9.93549e-06
-9.7068e-06
-9.44863e-06
-9.15961e-06
-8.84472e-06
-8.50409e-06
-8.1374e-06
-7.74251e-06
-7.31467e-06
-6.69505e-06
-6.38889e-06
-6.3514e-06
-6.59589e-06
-6.22134e-06
6.26285e-06
3.84335e-06
-8.45279e-05
)
;
}
sWall
{
type calculated;
value uniform -0.000278843;
}
nWall
{
type calculated;
value nonuniform List<scalar> 6(-5.41078e-05 -6.45705e-05 -6.91383e-05 -8.45895e-05 -9.31004e-05 -0.000111499);
}
sideWalls
{
type empty;
value nonuniform 0();
}
glass1
{
type calculated;
value nonuniform List<scalar> 9(-5.977e-05 -0.000160638 -0.000245494 -0.000317791 -0.000379239 -0.000431111 -0.000478483 -0.000535852 -0.000599928);
}
glass2
{
type calculated;
value nonuniform List<scalar> 2(-0.000292593 -0.000324955);
}
sun
{
type calculated;
value uniform 0;
}
heatsource1
{
type calculated;
value nonuniform List<scalar> 3(2.05013e-07 2.04911e-07 2.04931e-07);
}
heatsource2
{
type calculated;
value nonuniform List<scalar> 4(5.14262e-08 5.15234e-08 0 0);
}
Table_master
{
type calculated;
value nonuniform List<scalar> 9(-1.53765e-07 -1.53861e-07 -1.53895e-07 -1.53917e-07 -1.53933e-07 -1.53943e-07 -1.53947e-07 -1.5394e-07 -1.53905e-07);
}
Table_slave
{
type calculated;
value nonuniform List<scalar> 9(1.53621e-07 1.53644e-07 1.53621e-07 1.53604e-07 1.536e-07 1.53603e-07 1.53624e-07 1.53674e-07 1.53765e-07);
}
inlet
{
type calculated;
value uniform -0.00624091;
}
outlet
{
type calculated;
value nonuniform List<scalar> 2(0.00822356 0.00331653);
}
}
// ************************************************************************* //
| [
"mitsuaki.makino@tryeting.jp"
] | mitsuaki.makino@tryeting.jp | |
415dc4e9dde4d37bcfa0964c593a067fc8f70c9a | e0133373a91bca13fe12b6dabf90f02e4990eb37 | /Examples/Effect/R_O_I/R_O_I_Strings.cpp | bd25a9f7feefacc3ae57b99ede0a8745e4d1aef8 | [
"MIT"
] | permissive | rlalance/AfterEffectsExperimentations | 2ea96e0019118fee3aef49ec41dd859d7a89a246 | 5eae44e81c867ee44d00f88aaefaef578f7c3de7 | refs/heads/master | 2022-06-29T19:56:07.395307 | 2019-12-26T15:13:41 | 2019-12-26T15:15:43 | 230,270,898 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | /* R_O_I_Strings.cpp */
#include "R_O_I.h"
typedef struct {
unsigned long index;
char str[256];
} TableString;
TableString g_strs[StrID_NUMTYPES] = {
StrID_NONE, "",
StrID_Name, "R_O_I",
StrID_Description, "A SmartFX-ified exercise of our processing callbacks.\nCopyright 2007 Adobe Systems Incorporated.",
StrID_Color_Param_Name, "Color to mix",
StrID_Rect_Size_Param_Name, "Size of Rect",
StrID_Checkbox_Param_Name, "Use Downsample Factors",
StrID_Checkbox_Description, "(important!)",
StrID_DependString1, "All Dependencies requested.",
StrID_DependString2, "Missing Dependencies requested.",
StrID_Err_LoadSuite, "Error loading suite.",
StrID_Err_FreeSuite, "Error releasing suite.",
StrID_Popup_Choices, "Old Skool|New Skool|(-|Alpha Ignant",
StrID_Popup_Param_Name, "Kick it..."
};
char *GetStringPtr(int strNum)
{
return g_strs[strNum].str;
}
| [
"Richard.Lalancette@youi.tv"
] | Richard.Lalancette@youi.tv |
8a9598c7df71246c7b50a91a9dcc0b9878c31a38 | 4367dbc646a980fac95fa26440a309c9591c5747 | /src/Magnum/Math/Test/RangeTest.cpp | f2c953f46da3339bb93ba498a36bd5c8e19283e7 | [
"MIT"
] | permissive | williamjcm/magnum | 1b7e1657d6dec14e42d00642dd2a584a345e50e6 | da5d2fa958f22844adaec90e894e85270ed0a631 | refs/heads/master | 2022-10-30T22:34:55.831298 | 2022-09-07T07:34:55 | 2022-09-07T11:44:14 | 167,661,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,892 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022 Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <sstream>
#include <Corrade/TestSuite/Tester.h>
#include <Corrade/Utility/DebugStl.h>
#include <Corrade/Utility/TypeTraits.h> /* CORRADE_STD_IS_TRIVIALLY_TRAITS_SUPPORTED */
#include "Magnum/Math/FunctionsBatch.h"
#include "Magnum/Math/Range.h"
#include "Magnum/Math/StrictWeakOrdering.h"
struct Dim {
float offset, size;
};
struct Rect {
float x, y, w, h;
};
struct Box {
float x, y, z, w, h, d;
};
namespace Magnum { namespace Math {
namespace Implementation {
template<> struct RangeConverter<1, Float, Dim> {
constexpr static Range<1, Float> from(const Dim& other) {
/* Doing it this way to preserve constexpr */
return {other.offset, other.offset + other.size};
}
constexpr static Dim to(const Range<1, Float>& other) {
return {other.min(),
/* Doing it this way to preserve constexpr */
other.max() - other.min()};
}
};
template<> struct RangeConverter<2, Float, Rect> {
constexpr static Range<2, Float> from(const Rect& other) {
/* Doing it this way to preserve constexpr */
return {{other.x, other.y}, {other.x + other.w, other.y + other.h}};
}
constexpr static Rect to(const Range<2, Float>& other) {
return {other.min().x(), other.min().y(),
/* Doing it this way to preserve constexpr */
other.max().x() - other.min().x(),
other.max().y() - other.min().y()};
}
};
template<> struct RangeConverter<3, Float, Box> {
constexpr static Range<3, Float> from(const Box& other) {
return {{other.x, other.y, other.z},
/* Doing it this way to preserve constexpr */
{other.x + other.w,
other.y + other.h,
other.z + other.d}};
}
constexpr static Box to(const Range<3, Float>& other) {
return {other.min().x(), other.min().y(), other.min().z(),
/* Doing it this way to preserve constexpr */
other.max().x() - other.min().x(),
other.max().y() - other.min().y(),
other.max().z() - other.min().z()};
}
};
}
namespace Test { namespace {
struct RangeTest: Corrade::TestSuite::Tester {
explicit RangeTest();
void construct();
void construct1DFromVectors();
void constructDefault();
void constructNoInit();
void constructFromSize();
void constructFromCenter();
void constructPair();
void constructConversion();
void constructCopy();
void convert();
void data();
void access();
void compare();
void dimensionSlice();
void size();
void center();
/* Testing 1D separately because it's a scalar, not vector. The above
functions test all dimensions explicitly. */
void translated();
void translated1D();
void padded();
void padded1D();
void scaled();
void scaled1D();
void scaledFromCenter();
void scaledFromCenter1D();
void containsPoint();
void containsPoint1D();
void containsRange();
void containsRange1D();
void intersectIntersects();
void intersectIntersects1D();
void join();
void join1D();
void strictWeakOrdering();
void subclassTypes();
void subclass();
void debug();
};
typedef Math::Range1D<Float> Range1D;
typedef Math::Range2D<Float> Range2D;
typedef Math::Range3D<Float> Range3D;
typedef Math::Range1D<Int> Range1Di;
typedef Math::Range2D<Int> Range2Di;
typedef Math::Range3D<Int> Range3Di;
typedef Vector2<Int> Vector2i;
typedef Vector3<Int> Vector3i;
RangeTest::RangeTest() {
addTests({&RangeTest::construct,
&RangeTest::construct1DFromVectors,
&RangeTest::constructDefault,
&RangeTest::constructNoInit,
&RangeTest::constructFromSize,
&RangeTest::constructFromCenter,
&RangeTest::constructPair,
&RangeTest::constructConversion,
&RangeTest::constructCopy,
&RangeTest::convert,
&RangeTest::data,
&RangeTest::access,
&RangeTest::compare,
&RangeTest::dimensionSlice,
&RangeTest::size,
&RangeTest::center,
&RangeTest::translated,
&RangeTest::translated1D,
&RangeTest::padded,
&RangeTest::padded1D,
&RangeTest::scaled,
&RangeTest::scaled1D,
&RangeTest::scaledFromCenter,
&RangeTest::scaledFromCenter1D,
&RangeTest::containsPoint,
&RangeTest::containsPoint1D,
&RangeTest::containsRange,
&RangeTest::containsRange1D,
&RangeTest::intersectIntersects,
&RangeTest::intersectIntersects1D,
&RangeTest::join,
&RangeTest::join1D,
&RangeTest::strictWeakOrdering,
&RangeTest::subclassTypes,
&RangeTest::subclass,
&RangeTest::debug});
}
void RangeTest::construct() {
constexpr Range1Di a = {3, 23};
constexpr Range2Di b = {{3, 5}, {23, 78}};
constexpr Range3Di c = {{3, 5, -7}, {23, 78, 2}};
CORRADE_COMPARE(a, (Range<1, Int>(3, 23)));
CORRADE_COMPARE(b, (Range<2, Int>({3, 5}, {23, 78})));
CORRADE_COMPARE(c, (Range<3, Int>({3, 5, -7}, {23, 78, 2})));
CORRADE_VERIFY(std::is_nothrow_constructible<Range1Di, Int, Int>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range2Di, Vector2i, Vector2i>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range3Di, Vector3i, Vector3i>::value);
}
void RangeTest::construct1DFromVectors() {
/* Used by EigenIntegration for Range3D conversion. Implementing the same
there would be a massive verbose pain and this could be useful elsewhere
as well, so implementing that directly on a Range. */
constexpr Range1Di a = {Vector<1, Int>{3}, Vector<1, Int>{23}};
CORRADE_COMPARE(a, (Range<1, Int>(3, 23)));
CORRADE_VERIFY(std::is_nothrow_constructible<Range1Di, Vector<1, Int>, Vector<1, Int>>::value);
}
void RangeTest::constructDefault() {
constexpr Range1Di a1;
constexpr Range2Di b1;
constexpr Range3Di c1;
constexpr Range1Di a2{ZeroInit};
constexpr Range2Di b2{ZeroInit};
constexpr Range3Di c2{ZeroInit};
CORRADE_COMPARE(a1, Range1Di(0, 0));
CORRADE_COMPARE(a2, Range1Di(0, 0));
CORRADE_COMPARE(b1, Range2Di({0, 0}, {0, 0}));
CORRADE_COMPARE(b2, Range2Di({0, 0}, {0, 0}));
CORRADE_COMPARE(c1, Range3Di({0, 0, 0}, {0, 0, 0}));
CORRADE_COMPARE(c2, Range3Di({0, 0, 0}, {0, 0, 0}));
CORRADE_VERIFY(std::is_nothrow_default_constructible<Range1Di>::value);
CORRADE_VERIFY(std::is_nothrow_default_constructible<Range2Di>::value);
CORRADE_VERIFY(std::is_nothrow_default_constructible<Range3Di>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range1Di, ZeroInitT>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range2Di, ZeroInitT>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range3Di, ZeroInitT>::value);
/* Implicit construction is not allowed */
CORRADE_VERIFY(!std::is_convertible<ZeroInitT, Range1Di>::value);
CORRADE_VERIFY(!std::is_convertible<ZeroInitT, Range2Di>::value);
CORRADE_VERIFY(!std::is_convertible<ZeroInitT, Range3Di>::value);
}
void RangeTest::constructNoInit() {
Range1Di a{3, 23};
Range2Di b{{3, 5}, {23, 78}};
Range3Di c{{3, 5, -7}, {23, 78, 2}};
new(&a) Range1Di{Magnum::NoInit};
new(&b) Range2Di{Magnum::NoInit};
new(&c) Range3Di{Magnum::NoInit};
{
/* Explicitly check we're not on Clang because certain Clang-based IDEs
inherit __GNUC__ if GCC is used instead of leaving it at 4 like
Clang itself does */
#if defined(CORRADE_TARGET_GCC) && !defined(CORRADE_TARGET_CLANG) && __GNUC__*100 + __GNUC_MINOR__ >= 601 && __OPTIMIZE__
CORRADE_EXPECT_FAIL("GCC 6.1+ misoptimizes and overwrites the value.");
#endif
CORRADE_COMPARE(a, (Range1Di{3, 23}));
CORRADE_COMPARE(b, (Range2Di{{3, 5}, {23, 78}}));
CORRADE_COMPARE(c, (Range3Di{{3, 5, -7}, {23, 78, 2}}));
}
CORRADE_VERIFY(std::is_nothrow_constructible<Range1Di, Magnum::NoInitT>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range2Di, Magnum::NoInitT>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range3Di, Magnum::NoInitT>::value);
/* Implicit construction is not allowed */
CORRADE_VERIFY(!std::is_convertible<Magnum::NoInitT, Range1Di>::value);
CORRADE_VERIFY(!std::is_convertible<Magnum::NoInitT, Range2Di>::value);
CORRADE_VERIFY(!std::is_convertible<Magnum::NoInitT, Range3Di>::value);
}
void RangeTest::constructFromSize() {
CORRADE_COMPARE(Range1Di::fromSize(3, 23), Range1Di(3, 26));
CORRADE_COMPARE(Range2Di::fromSize({3, 5}, {23, 78}), Range2Di({3, 5}, {26, 83}));
CORRADE_COMPARE(Range3Di::fromSize({3, 5, -7}, {23, 78, 9}), Range3Di({3, 5, -7}, {26, 83, 2}));
}
void RangeTest::constructFromCenter() {
CORRADE_COMPARE(Range1Di::fromCenter(15, 3), (Range1Di{12, 18}));
CORRADE_COMPARE(Range2Di::fromCenter({15, 5}, {3, 10}), (Range2Di{{12, -5}, {18, 15}}));
CORRADE_COMPARE(Range3Di::fromCenter({15, 5, -7}, {3, 10, 9}), (Range3Di{{12, -5, -16}, {18, 15, 2}}));
}
void RangeTest::constructPair() {
Vector2i a{10, 22};
Vector2i b{30, 18};
Vector2i c{20, 25};
/* Conversion should be implicit, so not using {} */
Range1Di bounds1a = Math::minmax({a.x(), b.x(), c.x()});
Range1Di bounds1c{10, 30};
CORRADE_COMPARE(bounds1a, bounds1c);
Range2Di bounds2a = Math::minmax({a, b, c});
Range2Di bounds2b = std::pair<Math::Vector<2, Int>, Math::Vector<2, Int>>{{10, 18}, {30, 25}};
Range2Di bounds2c{{10, 18}, {30, 25}};
CORRADE_COMPARE(bounds2a, bounds2c);
CORRADE_COMPARE(bounds2b, bounds2c);
Vector3i a3{a, 122};
Vector3i b3{b, 122};
Vector3i c3{c, 123};
Range3Di bounds3a = Math::minmax({a3, b3, c3});
Range3Di bounds3b = std::pair<Math::Vector<3, Int>, Math::Vector<3, Int>>{{10, 18, 122}, {30, 25, 123}};
Range3Di bounds3c{{10, 18, 122}, {30, 25, 123}};
CORRADE_COMPARE(bounds3a, bounds3c);
CORRADE_COMPARE(bounds3b, bounds3c);
}
void RangeTest::constructConversion() {
constexpr Range1D a(1.3f, -15.0f);
constexpr Range2D b({1.3f, 2.7f}, {-15.0f, 7.0f});
constexpr Range3D c({1.3f, 2.7f, -1.5f}, {-15.0f, 7.0f, 0.3f});
constexpr Range1Di d(a);
CORRADE_COMPARE(d, Range1Di(1, -15));
constexpr Range2Di e(b);
CORRADE_COMPARE(e, Range2Di({1, 2}, {-15, 7}));
constexpr Range3Di f(c);
CORRADE_COMPARE(f, Range3Di({1, 2, -1}, {-15, 7, 0}));
/* Implicit conversion is not allowed */
CORRADE_VERIFY(!std::is_convertible<Range<2, Float>, Range<2, Int>>::value);
CORRADE_VERIFY(!std::is_convertible<Range1D, Range1Di>::value);
CORRADE_VERIFY(!std::is_convertible<Range2D, Range2Di>::value);
CORRADE_VERIFY(!std::is_convertible<Range3D, Range3Di>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range1D, Range1Di>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range2D, Range2Di>::value);
CORRADE_VERIFY(std::is_nothrow_constructible<Range3D, Range3Di>::value);
}
void RangeTest::constructCopy() {
constexpr Range1Di a(3, 23);
constexpr Range2Di b({3, 5}, {23, 78});
constexpr Range3Di c({3, 5, -7}, {23, 78, 2});
constexpr Range1Di d(a);
constexpr Range2Di e(b);
constexpr Range3Di f(c);
CORRADE_COMPARE(d, Range1Di(3, 23));
CORRADE_COMPARE(e, Range2Di({3, 5}, {23, 78}));
CORRADE_COMPARE(f, Range3Di({3, 5, -7}, {23, 78, 2}));
#ifdef CORRADE_STD_IS_TRIVIALLY_TRAITS_SUPPORTED
CORRADE_VERIFY(std::is_trivially_copy_constructible<Range1Di>::value);
CORRADE_VERIFY(std::is_trivially_copy_constructible<Range2Di>::value);
CORRADE_VERIFY(std::is_trivially_copy_constructible<Range3Di>::value);
CORRADE_VERIFY(std::is_trivially_copy_assignable<Range1Di>::value);
CORRADE_VERIFY(std::is_trivially_copy_assignable<Range2Di>::value);
CORRADE_VERIFY(std::is_trivially_copy_assignable<Range3Di>::value);
#endif
CORRADE_VERIFY(std::is_nothrow_copy_constructible<Range1Di>::value);
CORRADE_VERIFY(std::is_nothrow_copy_constructible<Range2Di>::value);
CORRADE_VERIFY(std::is_nothrow_copy_constructible<Range3Di>::value);
CORRADE_VERIFY(std::is_nothrow_copy_assignable<Range1Di>::value);
CORRADE_VERIFY(std::is_nothrow_copy_assignable<Range2Di>::value);
CORRADE_VERIFY(std::is_nothrow_copy_assignable<Range3Di>::value);
}
void RangeTest::convert() {
/* It's position/size, not min/max */
constexpr Dim a{1.5f, 3.5f};
constexpr Rect b{1.5f, -2.0f, 3.5f, 0.5f};
constexpr Box c{1.5f, -2.0f, -0.5f, 3.5f, 0.5f, 9.5f};
constexpr Range1D d{1.5f, 5.0f};
constexpr Range2D e{{1.5f, -2.0f}, {5.0f, -1.5f}};
constexpr Range3D f{{1.5f, -2.0f, -0.5f}, {5.0f, -1.5f, 9.0f}};
/* GCC 5.1 had a bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66450
Hopefully this does not reappear. */
constexpr Range<2, Float> g{b};
constexpr Range1D h{a};
constexpr Range2D i{b};
constexpr Range3D j{c};
CORRADE_COMPARE(g, e);
CORRADE_COMPARE(h, d);
CORRADE_COMPARE(i, e);
CORRADE_COMPARE(j, f);
constexpr Dim k(d);
CORRADE_COMPARE(k.offset, a.offset);
CORRADE_COMPARE(k.size, a.size);
constexpr Rect l(e);
CORRADE_COMPARE(l.x, b.x);
CORRADE_COMPARE(l.y, b.y);
CORRADE_COMPARE(l.w, b.w);
CORRADE_COMPARE(l.h, b.h);
constexpr Box m(f);
CORRADE_COMPARE(m.x, c.x);
CORRADE_COMPARE(m.y, c.y);
CORRADE_COMPARE(m.z, c.z);
CORRADE_COMPARE(m.w, c.w);
CORRADE_COMPARE(m.h, c.h);
CORRADE_COMPARE(m.d, c.d);
/* Implicit conversion is not allowed */
CORRADE_VERIFY(!std::is_convertible<Rect, Range<2, Float>>::value);
CORRADE_VERIFY(!std::is_convertible<Dim, Range1D>::value);
CORRADE_VERIFY(!std::is_convertible<Rect, Range2D>::value);
CORRADE_VERIFY(!std::is_convertible<Box, Range3D>::value);
CORRADE_VERIFY(!std::is_convertible<Range1D, Dim>::value);
CORRADE_VERIFY(!std::is_convertible<Range2D, Rect>::value);
CORRADE_VERIFY(!std::is_convertible<Range3D, Box>::value);
}
void RangeTest::data() {
Range1Di line(34, 47);
Range2Di rect({34, 23}, {47, 30});
Range3Di cube({34, 23, -17}, {47, 30, 12});
constexpr Range1Di cline(34, 47);
constexpr Range2Di crect({34, 23}, {47, 30});
constexpr Range3Di ccube({34, 23, -17}, {47, 30, 12});
/* Not constexpr anymore, as it has to reinterpret to return a
correctly-sized array */
CORRADE_COMPARE(line.data()[1], 47);
CORRADE_COMPARE(cline.data()[1], 47);
CORRADE_COMPARE(*rect.data(), 34);
CORRADE_COMPARE(*crect.data(), 34);
CORRADE_COMPARE(cube.data()[2], -17);
CORRADE_COMPARE(ccube.data()[2], -17);
/* It actually returns an array */
CORRADE_COMPARE(Corrade::Containers::arraySize(line.data()), 2);
CORRADE_COMPARE(Corrade::Containers::arraySize(cline.data()), 2);
CORRADE_COMPARE(Corrade::Containers::arraySize(rect.data()), 4);
CORRADE_COMPARE(Corrade::Containers::arraySize(crect.data()), 4);
CORRADE_COMPARE(Corrade::Containers::arraySize(cube.data()), 6);
CORRADE_COMPARE(Corrade::Containers::arraySize(ccube.data()), 6);
}
void RangeTest::access() {
Range1Di line(34, 47);
Range2Di rect({34, 23}, {47, 30});
Range3Di cube({34, 23, -17}, {47, 30, 12});
constexpr Range1Di cline(34, 47);
constexpr Range2Di crect({34, 23}, {47, 30});
constexpr Range3Di ccube({34, 23, -17}, {47, 30, 12});
CORRADE_COMPARE(line.min(), 34);
CORRADE_COMPARE(cline.min(), 34);
CORRADE_COMPARE(line.max(), 47);
CORRADE_COMPARE(cline.max(), 47);
CORRADE_COMPARE(rect.bottomLeft(), Vector2i(34, 23));
CORRADE_COMPARE(rect.topRight(), Vector2i(47, 30));
constexpr Vector2i bottomLeft = crect.bottomLeft();
constexpr Vector2i topRight = crect.topRight();
CORRADE_COMPARE(bottomLeft, Vector2i(34, 23));
CORRADE_COMPARE(topRight, Vector2i(47, 30));
CORRADE_COMPARE(rect.left(), 34);
CORRADE_COMPARE(rect.right(), 47);
CORRADE_COMPARE(rect.bottom(), 23);
CORRADE_COMPARE(rect.top(), 30);
constexpr Int left2 = crect.left();
constexpr Int right2 = crect.right();
constexpr Int bottom2 = crect.bottom();
constexpr Int top2 = crect.top();
CORRADE_COMPARE(left2, 34);
CORRADE_COMPARE(right2, 47);
CORRADE_COMPARE(bottom2, 23);
CORRADE_COMPARE(top2, 30);
CORRADE_COMPARE(cube.backBottomLeft(), Vector3i(34, 23, -17));
CORRADE_COMPARE(cube.frontTopRight(), Vector3i(47, 30, 12));
constexpr Vector3i backBottomLeft = ccube.backBottomLeft();
constexpr Vector3i frontTopRight = ccube.frontTopRight();
CORRADE_COMPARE(backBottomLeft, Vector3i(34, 23, -17));
CORRADE_COMPARE(frontTopRight, Vector3i(47, 30, 12));
CORRADE_COMPARE(cube.left(), 34);
CORRADE_COMPARE(cube.right(), 47);
CORRADE_COMPARE(cube.bottom(), 23);
CORRADE_COMPARE(cube.top(), 30);
CORRADE_COMPARE(cube.back(), -17);
CORRADE_COMPARE(cube.front(), 12);
constexpr Int left3 = ccube.left();
constexpr Int right3 = ccube.right();
constexpr Int bottom3 = ccube.bottom();
constexpr Int top3 = ccube.top();
constexpr Int back3 = ccube.back();
constexpr Int front3 = ccube.front();
CORRADE_COMPARE(left3, 34);
CORRADE_COMPARE(right3, 47);
CORRADE_COMPARE(bottom3, 23);
CORRADE_COMPARE(top3, 30);
CORRADE_COMPARE(back3, -17);
CORRADE_COMPARE(front3, 12);
CORRADE_COMPARE(rect.bottomRight(), Vector2i(47, 23));
CORRADE_COMPARE(rect.topLeft(), Vector2i(34, 30));
CORRADE_COMPARE(cube.backBottomRight(), Vector3i(47, 23, -17));
CORRADE_COMPARE(cube.backTopLeft(), Vector3i(34, 30, -17));
CORRADE_COMPARE(cube.backTopRight(), Vector3i(47, 30, -17));
CORRADE_COMPARE(cube.frontBottomLeft(), Vector3i(34, 23, 12));
CORRADE_COMPARE(cube.frontBottomRight(), Vector3i(47, 23, 12));
CORRADE_COMPARE(cube.frontTopLeft(), Vector3i(34, 30, 12));
}
void RangeTest::compare() {
CORRADE_VERIFY(Range2Di({34, 23}, {47, 30}) == Range2Di({34, 23}, {47, 30}));
CORRADE_VERIFY(Range2Di({34, 23}, {47, 30}) != Range2Di({34, 23}, {48, 30}));
CORRADE_VERIFY(Range2Di({34, 23}, {47, 30}) != Range2Di({35, 23}, {47, 30}));
CORRADE_VERIFY(Range1D(1.0f, 1.0f) != Range1D(1.0f + TypeTraits<Float>::epsilon()*2, 1.0f));
CORRADE_VERIFY(Range1D(1.0f, 1.0f) != Range1D(1.0f, 1.0f + TypeTraits<Float>::epsilon()*2));
CORRADE_VERIFY(Range1D(1.0f, 1.0f) == Range1D(1.0f + TypeTraits<Float>::epsilon()/2.0f,
1.0f + TypeTraits<Float>::epsilon()/2.0f));
}
void RangeTest::dimensionSlice() {
constexpr Range1Di lineX{34, 47};
constexpr Range1Di lineY{23, 30};
constexpr Range1Di lineZ{-17, 12};
constexpr Range2Di rect{{34, 23}, {47, 30}};
constexpr Range3Di cube{{34, 23, -17}, {47, 30, 12}};
constexpr Range1Di x2 = rect.x();
constexpr Range1Di x3 = cube.x();
CORRADE_COMPARE(x2, lineX);
CORRADE_COMPARE(x3, lineX);
CORRADE_COMPARE(rect.x(), lineX);
CORRADE_COMPARE(cube.x(), lineX);
constexpr Range1Di y2 = rect.y();
constexpr Range1Di y3 = cube.y();
CORRADE_COMPARE(y2, lineY);
CORRADE_COMPARE(y3, lineY);
CORRADE_COMPARE(rect.y(), lineY);
CORRADE_COMPARE(cube.y(), lineY);
constexpr Range1Di z = cube.z();
CORRADE_COMPARE(z, lineZ);
CORRADE_COMPARE(cube.z(), lineZ);
#ifndef CORRADE_MSVC2015_COMPATIBILITY
constexpr /* No clue. Also, IDGAF. */
#endif
Range2Di xy = cube.xy();
CORRADE_COMPARE(xy, rect);
CORRADE_COMPARE(cube.xy(), rect);
}
void RangeTest::size() {
const Range1Di line(34, 47);
const Range2Di rect({34, 23}, {47, 30});
const Range3Di cube({34, 23, -17}, {47, 30, 12});
CORRADE_COMPARE(line.size(), 13);
CORRADE_COMPARE(rect.size(), Vector2i(13, 7));
CORRADE_COMPARE(cube.size(), Vector3i(13, 7, 29));
CORRADE_COMPARE(rect.sizeX(), 13);
CORRADE_COMPARE(rect.sizeY(), 7);
CORRADE_COMPARE(cube.sizeX(), 13);
CORRADE_COMPARE(cube.sizeY(), 7);
CORRADE_COMPARE(cube.sizeZ(), 29);
}
void RangeTest::center() {
const Range1Di line(34, 47);
const Range2Di rect({34, 23}, {47, 30});
const Range3Di cube({34, 23, -17}, {47, 30, 12});
CORRADE_COMPARE(line.center(), 40);
CORRADE_COMPARE(rect.center(), Vector2i(40, 26));
CORRADE_COMPARE(cube.center(), Vector3i(40, 26, -2));
CORRADE_COMPARE(rect.centerX(), 40);
CORRADE_COMPARE(rect.centerY(), 26);
CORRADE_COMPARE(cube.centerX(), 40);
CORRADE_COMPARE(cube.centerY(), 26);
CORRADE_COMPARE(cube.centerZ(), -2);
}
void RangeTest::translated() {
Range2Di a({34, 23}, {47, 30});
Range2Di b({17, 63}, {30, 70});
CORRADE_COMPARE(a.translated({-17, 40}), b);
CORRADE_COMPARE(a.size(), b.size());
}
void RangeTest::translated1D() {
Range1Di a(34, 47);
Range1Di b(17, 30);
CORRADE_COMPARE(a.translated(-17), b);
CORRADE_COMPARE(a.size(), b.size());
}
void RangeTest::padded() {
Range2Di a({34, 23}, {47, 30});
Range2Di b({31, 28}, {50, 25});
CORRADE_COMPARE(a.padded({3, -5}), b);
CORRADE_COMPARE(a.center(), b.center());
}
void RangeTest::padded1D() {
Range1Di a{34, 47};
Range1Di b{31, 50};
CORRADE_COMPARE(a.padded(3), b);
CORRADE_COMPARE(a.center(), b.center());
}
void RangeTest::scaled() {
Range2Di a({34, 23}, {47, 30});
Range2Di b({68, -69}, {94, -90});
CORRADE_COMPARE(a.scaled({2, -3}), b);
CORRADE_COMPARE((a.size()*Vector2i{2, -3}), b.size());
}
void RangeTest::scaled1D() {
Range1Di a{34, 47};
Range1Di b{68, 94};
CORRADE_COMPARE(a.scaled(2), b);
CORRADE_COMPARE(a.size()*2, b.size());
}
void RangeTest::scaledFromCenter() {
Range2Di a{{34, 22}, {48, 30}};
Range2Di b{{27, 38}, {55, 14}};
CORRADE_COMPARE(a.scaledFromCenter({2, -3}), b);
CORRADE_COMPARE(a.center(), b.center());
CORRADE_COMPARE((a.size()*Vector2i{2, -3}), b.size());
}
void RangeTest::scaledFromCenter1D() {
Range1Di a{34, 48};
Range1Di b{27, 55};
CORRADE_COMPARE(a.scaledFromCenter(2), b);
CORRADE_COMPARE(a.center(), b.center());
CORRADE_COMPARE(a.size()*2, b.size());
}
void RangeTest::containsPoint() {
Range2Di a({34, 23}, {47, 30});
CORRADE_VERIFY(a.contains({40, 23}));
CORRADE_VERIFY(!a.contains({33, 23}));
CORRADE_VERIFY(!a.contains({40, 30}));
/* Contains a point at min, but not at max */
CORRADE_VERIFY(a.contains({34, 23}));
CORRADE_VERIFY(!a.contains({47, 30}));
}
void RangeTest::containsPoint1D() {
Range1Di a{34, 47};
CORRADE_VERIFY(a.contains(40));
CORRADE_VERIFY(!a.contains(33));
/* Contains a point at min, but not at max */
CORRADE_VERIFY(a.contains(34));
CORRADE_VERIFY(!a.contains(47));
}
void RangeTest::containsRange() {
Range2Di a({34, 23}, {47, 30});
/* Contains whole range with a gap, not the other way around */
Range2Di b{{35, 25}, {40, 28}};
CORRADE_VERIFY(a.contains(b));
CORRADE_VERIFY(!b.contains(a));
/* Contains itself, empty range contains itself as well */
Range2Di c;
CORRADE_VERIFY(a.contains(a));
CORRADE_VERIFY(b.contains(b));
CORRADE_VERIFY(c.contains(c));
/* Contains zero-sized range inside but not outside */
Range2Di d{{34, 23}, {34, 23}};
Range2Di e{{33, 23}, {33, 23}};
Range2Di f{{47, 30}, {47, 30}};
Range2Di g{{47, 31}, {47, 31}};
CORRADE_VERIFY(a.contains(d));
CORRADE_VERIFY(!a.contains(e));
CORRADE_VERIFY(a.contains(f));
CORRADE_VERIFY(!a.contains(g));
/* Doesn't contain a range that overlaps */
Range2Di h{{30, 25}, {35, 105}};
CORRADE_VERIFY(!a.contains(h));
CORRADE_VERIFY(!h.contains(a));
/* Doesn't contain a range touching the edges from the outside */
Range2Di i{{20, 30}, {34, 40}};
Range2Di j{{47, 20}, {60, 23}};
CORRADE_VERIFY(!a.contains(i));
CORRADE_VERIFY(!a.contains(j));
}
void RangeTest::containsRange1D() {
Range1Di a{34, 47};
/* Contains whole range with a gap, not the other way around */
Range1Di b{35, 40};
CORRADE_VERIFY(a.contains(b));
CORRADE_VERIFY(!b.contains(a));
/* Contains itself, empty range contains itself as well */
Range1Di c;
CORRADE_VERIFY(a.contains(a));
CORRADE_VERIFY(b.contains(b));
CORRADE_VERIFY(c.contains(c));
/* Contains zero-sized range inside but not outside */
Range1Di d{34, 34};
Range1Di e{33, 33};
Range1Di f{47, 47};
Range1Di g{48, 48};
CORRADE_VERIFY(a.contains(d));
CORRADE_VERIFY(!a.contains(e));
CORRADE_VERIFY(a.contains(f));
CORRADE_VERIFY(!a.contains(g));
/* Doesn't contain a range that overlaps */
Range1Di h{30, 35};
CORRADE_VERIFY(!a.contains(h));
CORRADE_VERIFY(!h.contains(a));
/* Doesn't contain a range touching the edges from the outside */
Range1Di i{20, 34};
Range1Di j{47, 60};
CORRADE_VERIFY(!a.contains(i));
CORRADE_VERIFY(!a.contains(j));
}
void RangeTest::intersectIntersects() {
Range2Di a({34, 23}, {47, 30});
/* Intersects itself */
CORRADE_VERIFY(Math::intersects(a, a));
CORRADE_COMPARE(Math::intersect(a, a), a);
/* Non-empty intersection */
Range2Di b{{30, 25}, {35, 105}};
Range2Di c{{34, 25}, {35, 30}};
CORRADE_VERIFY(Math::intersects(a, b));
CORRADE_VERIFY(Math::intersects(b, a));
CORRADE_COMPARE(Math::intersect(a, b), c);
CORRADE_COMPARE(Math::intersect(b, a), c);
/* Intersecting with an empty range outside produces a default-constructed range */
Range2Di d{{130, -15}, {130, -15}};
CORRADE_VERIFY(!Math::intersects(a, d));
CORRADE_VERIFY(!Math::intersects(d, a));
CORRADE_COMPARE(Math::intersect(a, d), Range2Di{});
CORRADE_COMPARE(Math::intersect(d, a), Range2Di{});
/* Intersecting with an empty range inside produces an empty range */
Range2Di e{{40, 25}, {40, 25}};
CORRADE_VERIFY(Math::intersects(a, e));
CORRADE_VERIFY(Math::intersects(e, a));
CORRADE_COMPARE(Math::intersect(a, e), e);
CORRADE_COMPARE(Math::intersect(e, a), e);
/* Doesn't intersect a range touching the edges from the outside */
Range2Di i{{20, 30}, {34, 40}};
Range2Di j{{47, 20}, {60, 23}};
Range2Di k{{20, 20}, {34, 23}};
Range2Di l{{47, 30}, {60, 40}};
CORRADE_VERIFY(!Math::intersects(a, i));
CORRADE_VERIFY(!Math::intersects(a, j));
CORRADE_VERIFY(!Math::intersects(a, k));
CORRADE_VERIFY(!Math::intersects(a, l));
CORRADE_VERIFY(!Math::intersects(i, a));
CORRADE_VERIFY(!Math::intersects(j, a));
CORRADE_VERIFY(!Math::intersects(k, a));
CORRADE_VERIFY(!Math::intersects(l, a));
CORRADE_COMPARE(Math::intersect(a, i), Range2Di{});
CORRADE_COMPARE(Math::intersect(a, j), Range2Di{});
CORRADE_COMPARE(Math::intersect(a, k), Range2Di{});
CORRADE_COMPARE(Math::intersect(a, l), Range2Di{});
CORRADE_COMPARE(Math::intersect(i, a), Range2Di{});
CORRADE_COMPARE(Math::intersect(j, a), Range2Di{});
CORRADE_COMPARE(Math::intersect(k, a), Range2Di{});
CORRADE_COMPARE(Math::intersect(l, a), Range2Di{});
}
void RangeTest::intersectIntersects1D() {
Range1Di a(34, 47);
/* Intersects itself */
CORRADE_VERIFY(Math::intersects(a, a));
CORRADE_COMPARE(Math::intersect(a, a), a);
/* Non-empty intersection */
Range1Di b{30, 35};
Range1Di c{34, 35};
CORRADE_VERIFY(Math::intersects(a, b));
CORRADE_VERIFY(Math::intersects(b, a));
CORRADE_COMPARE(Math::intersect(a, b), c);
CORRADE_COMPARE(Math::intersect(b, a), c);
/* Intersecting with an empty range outside produces a default-constructed range */
Range1Di d{130, 130};
CORRADE_VERIFY(!Math::intersects(a, d));
CORRADE_VERIFY(!Math::intersects(d, a));
CORRADE_COMPARE(Math::intersect(a, d), Range1Di{});
CORRADE_COMPARE(Math::intersect(d, a), Range1Di{});
/* Intersecting with an empty range inside produces an empty range */
Range1Di e{40, 40};
CORRADE_VERIFY(Math::intersects(a, e));
CORRADE_VERIFY(Math::intersects(e, a));
CORRADE_COMPARE(Math::intersect(a, e), e);
CORRADE_COMPARE(Math::intersect(e, a), e);
/* Doesn't intersect a range touching the edges from the outside */
Range1Di i{20, 34};
Range1Di j{47, 60};
CORRADE_VERIFY(!Math::intersects(a, i));
CORRADE_VERIFY(!Math::intersects(a, j));
CORRADE_VERIFY(!Math::intersects(i, a));
CORRADE_VERIFY(!Math::intersects(j, a));
CORRADE_COMPARE(Math::intersect(a, i), Range1Di{});
CORRADE_COMPARE(Math::intersect(a, j), Range1Di{});
CORRADE_COMPARE(Math::intersect(i, a), Range1Di{});
CORRADE_COMPARE(Math::intersect(j, a), Range1Di{});
}
void RangeTest::join() {
Range2Di a{{12, 20}, {15, 35}};
Range2Di b{{10, 25}, {17, 105}};
Range2Di c{{130, -15}, {130, -15}};
Range2Di d{{10, 20}, {17, 105}};
CORRADE_COMPARE(Math::join(a, b), d);
CORRADE_COMPARE(Math::join(b, a), d);
CORRADE_COMPARE(Math::join(a, c), a);
CORRADE_COMPARE(Math::join(c, a), a);
}
void RangeTest::join1D() {
Range1Di a{12, 15};
Range1Di b{10, 17};
Range1Di c{130, 130};
Range1Di d{10, 17};
CORRADE_COMPARE(Math::join(a, b), d);
CORRADE_COMPARE(Math::join(b, a), d);
CORRADE_COMPARE(Math::join(a, c), a);
CORRADE_COMPARE(Math::join(c, a), a);
}
void RangeTest::strictWeakOrdering() {
StrictWeakOrdering o;
const Range1D a{1.0f, 2.0f};
const Range1D b{2.0f, 3.0f};
const Range1D c{1.0f, 3.0f};
CORRADE_VERIFY( o(a, b));
CORRADE_VERIFY(!o(b, a));
CORRADE_VERIFY( o(a, c));
CORRADE_VERIFY(!o(c, a));
CORRADE_VERIFY( o(c, b));
CORRADE_VERIFY(!o(b, c));
CORRADE_VERIFY(!o(a, a));
}
template<class T> class BasicRect: public Math::Range<2, T> {
public:
template<class ...U> constexpr BasicRect(U&&... args): Math::Range<2, T>{args...} {}
MAGNUM_RANGE_SUBCLASS_IMPLEMENTATION(2, BasicRect, Vector2)
};
typedef BasicRect<Int> Recti;
void RangeTest::subclassTypes() {
const Vector2i a;
CORRADE_VERIFY(std::is_same<decltype(Recti::fromSize(a, a)), Recti>::value);
const Recti r;
CORRADE_VERIFY(std::is_same<decltype(r.translated(a)), Recti>::value);
CORRADE_VERIFY(std::is_same<decltype(r.padded(a)), Recti>::value);
CORRADE_VERIFY(std::is_same<decltype(r.scaled(a)), Recti>::value);
}
void RangeTest::subclass() {
/* Constexpr constructor */
constexpr Recti a{Vector2i{34, 23}, Vector2i{47, 30}};
CORRADE_COMPARE(a.min(), (Vector2i{34, 23}));
CORRADE_COMPARE(Recti::fromSize({3, 5}, {23, 78}),
Recti(Vector2i{3, 5}, Vector2i{26, 83}));
CORRADE_COMPARE(Recti(Vector2i{34, 23}, Vector2i{47, 30}).translated({-17, 40}),
Recti(Vector2i{17, 63}, Vector2i{30, 70}));
CORRADE_COMPARE(Recti(Vector2i{34, 23}, Vector2i{47, 30}).padded({3, -5}),
Recti(Vector2i{31, 28}, Vector2i{50, 25}));
CORRADE_COMPARE(Recti(Vector2i{34, 23}, Vector2i{47, 30}).scaled({2, -3}),
Recti(Vector2i{68, -69}, Vector2i{94, -90}));
}
void RangeTest::debug() {
std::ostringstream o;
Debug(&o) << Range2Di({34, 23}, {47, 30});
CORRADE_COMPARE(o.str(), "Range({34, 23}, {47, 30})\n");
}
}}}}
CORRADE_TEST_MAIN(Magnum::Math::Test::RangeTest)
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
b062de5bb0da1aa4e71d7e6930c848729dfaebac | 520b75c144414d2af5a655e592fa65787ee89aaa | /AtCoder/ABC/053/B.cpp | e3c9e5cdd7cccb0113822f0011e406dea433a733 | [] | no_license | arrows-1011/CPro | 4ac069683c672ba685534444412aa2e28026879d | 2e1a9242b2433851f495468e455ee854a8c4dac7 | refs/heads/master | 2020-04-12T09:36:40.846130 | 2017-06-10T08:02:10 | 2017-06-10T08:02:10 | 46,426,455 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin >> s;
int N = s.size();
int l = 0, r = N - 1;
while (l < N && s[l] != 'A') {
l += 1;
}
while (r >= 0 && s[r] != 'Z') {
r -= 1;
}
cout << max(0, r - l + 1) << endl;
return 0;
}
| [
"s1210207@gmail.com"
] | s1210207@gmail.com |
0e9f5c52acc4cd66a90817e12643b5981d948001 | 66033adddff903d4ad540aefa39fdffe9934e403 | /Seep/includes/panojs/bioView/libsrc/pole/pole.cpp | 71c8c0cb9a9733ecfcf60d96b7248c097e2b99e8 | [] | no_license | kay54068/Hide-Seep | 361ef4c783f8ccff186eb98fee01c1219e7664ef | 785a0f93d64068d630a884d5283fae3e09d0d8d8 | refs/heads/master | 2020-09-14T07:13:09.723462 | 2015-02-07T20:15:55 | 2015-02-07T20:15:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,030 | cpp | /* POLE - Portable C++ library to access OLE Storage
Copyright (C) 2002-2005 Ariya Hidayat <ariya@kde.org>
Performance optimization: Dmitry Fedorov
Copyright 2009 <www.bioimage.ucsb.edu> <www.dimin.net>
Version: 0.3
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the authors nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <fstream>
#include <iostream>
#include <list>
#include <string>
#include <vector>
#include <cstring>
#include "pole.h"
// enable to activate debugging output
// #define POLE_DEBUG
namespace POLE
{
class Header
{
public:
unsigned char id[8]; // signature, or magic identifier
unsigned b_shift; // bbat->blockSize = 1 << b_shift
unsigned s_shift; // sbat->blockSize = 1 << s_shift
unsigned num_bat; // blocks allocated for big bat
unsigned dirent_start; // starting block for directory info
unsigned threshold; // switch from small to big file (usually 4K)
unsigned sbat_start; // starting block index to store small bat
unsigned num_sbat; // blocks allocated for small bat
unsigned mbat_start; // starting block to store meta bat
unsigned num_mbat; // blocks allocated for meta bat
unsigned long bb_blocks[109];
Header();
bool valid();
void load( const unsigned char* buffer );
void save( unsigned char* buffer );
void debug();
};
class AllocTable
{
public:
static const unsigned Eof;
static const unsigned Avail;
static const unsigned Bat;
static const unsigned MetaBat;
unsigned blockSize;
AllocTable();
void clear();
unsigned long count();
void resize( unsigned long newsize );
void preserve( unsigned long n );
void set( unsigned long index, unsigned long val );
unsigned unused();
void setChain( std::vector<unsigned long> );
std::vector<unsigned long> follow( unsigned long start );
unsigned long operator[](unsigned long index );
void load( const unsigned char* buffer, unsigned len );
void save( unsigned char* buffer );
unsigned size();
void debug();
private:
std::vector<unsigned long> data;
AllocTable( const AllocTable& );
AllocTable& operator=( const AllocTable& );
};
class DirEntry
{
public:
bool valid; // false if invalid (should be skipped)
std::string name; // the name, not in unicode anymore
bool dir; // true if directory
unsigned long size; // size (not valid if directory)
unsigned long start; // starting block
unsigned prev; // previous sibling
unsigned next; // next sibling
unsigned child; // first child
};
class DirTree
{
public:
static const unsigned End;
DirTree();
void clear();
inline unsigned entryCount();
DirEntry* entry( unsigned index );
DirEntry* entry( const std::string& name, bool create=false );
int indexOf( DirEntry* e );
int parent( unsigned index );
std::string fullName( unsigned index );
std::vector<unsigned> children( unsigned index );
unsigned find_child( unsigned index, const std::string& name );
void load( unsigned char* buffer, unsigned len );
void save( unsigned char* buffer );
unsigned size();
void debug();
private:
std::vector<DirEntry> entries;
DirTree( const DirTree& );
DirTree& operator=( const DirTree& );
};
class StorageIO
{
public:
Storage* storage; // owner
std::string filename; // filename
std::fstream file; // associated with above name
int result; // result of operation
bool opened; // true if file is opened
unsigned long filesize; // size of the file
Header* header; // storage header
DirTree* dirtree; // directory tree
AllocTable* bbat; // allocation table for big blocks
AllocTable* sbat; // allocation table for small blocks
std::vector<unsigned long> sb_blocks; // blocks for "small" files
std::list<Stream*> streams;
StorageIO( Storage* storage, const char* filename );
~StorageIO();
bool open();
void close();
void flush();
void load();
void create();
unsigned long loadBigBlocks( std::vector<unsigned long> blocks, unsigned char* buffer, unsigned long maxlen );
unsigned long loadBigBlock( unsigned long block, unsigned char* buffer, unsigned long maxlen );
unsigned long loadSmallBlocks( std::vector<unsigned long> blocks, unsigned char* buffer, unsigned long maxlen );
unsigned long loadSmallBlock( unsigned long block, unsigned char* buffer, unsigned long maxlen );
StreamIO* streamIO( const std::string& name );
private:
// no copy or assign
StorageIO( const StorageIO& );
StorageIO& operator=( const StorageIO& );
};
class StreamIO
{
public:
StorageIO* io;
DirEntry* entry;
std::string fullName;
bool eof;
bool fail;
StreamIO( StorageIO* io, DirEntry* entry );
~StreamIO();
unsigned long size();
void seek( unsigned long pos );
unsigned long tell();
int getch();
unsigned long read( unsigned char* data, unsigned long maxlen );
unsigned long read( unsigned long pos, unsigned char* data, unsigned long maxlen );
private:
std::vector<unsigned long> blocks;
// no copy or assign
StreamIO( const StreamIO& );
StreamIO& operator=( const StreamIO& );
// pointer for read
unsigned long m_pos;
// simple cache system to speed-up getch()
unsigned char* cache_data;
unsigned long cache_size;
unsigned long cache_pos;
void updateCache();
};
}; // namespace POLE
using namespace POLE;
static inline unsigned long readU16( const unsigned char* ptr )
{
return ptr[0]+(ptr[1]<<8);
}
static inline unsigned long readU32( const unsigned char* ptr )
{
return ptr[0]+(ptr[1]<<8)+(ptr[2]<<16)+(ptr[3]<<24);
}
static inline void writeU16( unsigned char* ptr, unsigned long data )
{
ptr[0] = (unsigned char)(data & 0xff);
ptr[1] = (unsigned char)((data >> 8) & 0xff);
}
static inline void writeU32( unsigned char* ptr, unsigned long data )
{
ptr[0] = (unsigned char)(data & 0xff);
ptr[1] = (unsigned char)((data >> 8) & 0xff);
ptr[2] = (unsigned char)((data >> 16) & 0xff);
ptr[3] = (unsigned char)((data >> 24) & 0xff);
}
static const unsigned char pole_magic[] =
{ 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1 };
// =========== Header ==========
Header::Header()
{
b_shift = 9;
s_shift = 6;
num_bat = 0;
dirent_start = 0;
threshold = 4096;
sbat_start = 0;
num_sbat = 0;
mbat_start = 0;
num_mbat = 0;
for( unsigned i = 0; i < 8; i++ )
id[i] = pole_magic[i];
for( unsigned i=0; i<109; i++ )
bb_blocks[i] = AllocTable::Avail;
}
bool Header::valid()
{
if( threshold != 4096 ) return false;
if( num_bat == 0 ) return false;
if( (num_bat > 109) && (num_bat > (num_mbat * 127) + 109)) return false;
if( (num_bat < 109) && (num_mbat != 0) ) return false;
if( s_shift > b_shift ) return false;
if( b_shift <= 6 ) return false;
if( b_shift >=31 ) return false;
return true;
}
void Header::load( const unsigned char* buffer )
{
b_shift = readU16( buffer + 0x1e );
s_shift = readU16( buffer + 0x20 );
num_bat = readU32( buffer + 0x2c );
dirent_start = readU32( buffer + 0x30 );
threshold = readU32( buffer + 0x38 );
sbat_start = readU32( buffer + 0x3c );
num_sbat = readU32( buffer + 0x40 );
mbat_start = readU32( buffer + 0x44 );
num_mbat = readU32( buffer + 0x48 );
for( unsigned i = 0; i < 8; i++ )
id[i] = buffer[i];
for( unsigned i=0; i<109; i++ )
bb_blocks[i] = readU32( buffer + 0x4C+i*4 );
}
void Header::save( unsigned char* buffer )
{
memset( buffer, 0, 0x4c );
memcpy( buffer, pole_magic, 8 ); // ole signature
writeU32( buffer + 8, 0 ); // unknown
writeU32( buffer + 12, 0 ); // unknown
writeU32( buffer + 16, 0 ); // unknown
writeU16( buffer + 24, 0x003e ); // revision ?
writeU16( buffer + 26, 3 ); // version ?
writeU16( buffer + 28, 0xfffe ); // unknown
writeU16( buffer + 0x1e, b_shift );
writeU16( buffer + 0x20, s_shift );
writeU32( buffer + 0x2c, num_bat );
writeU32( buffer + 0x30, dirent_start );
writeU32( buffer + 0x38, threshold );
writeU32( buffer + 0x3c, sbat_start );
writeU32( buffer + 0x40, num_sbat );
writeU32( buffer + 0x44, mbat_start );
writeU32( buffer + 0x48, num_mbat );
for( unsigned i=0; i<109; i++ )
writeU32( buffer + 0x4C+i*4, bb_blocks[i] );
}
void Header::debug()
{
std::cout << std::endl;
std::cout << "b_shift " << b_shift << std::endl;
std::cout << "s_shift " << s_shift << std::endl;
std::cout << "num_bat " << num_bat << std::endl;
std::cout << "dirent_start " << dirent_start << std::endl;
std::cout << "threshold " << threshold << std::endl;
std::cout << "sbat_start " << sbat_start << std::endl;
std::cout << "num_sbat " << num_sbat << std::endl;
std::cout << "mbat_start " << mbat_start << std::endl;
std::cout << "num_mbat " << num_mbat << std::endl;
unsigned s = (num_bat<=109) ? num_bat : 109;
std::cout << "bat blocks: ";
for( unsigned i = 0; i < s; i++ )
std::cout << bb_blocks[i] << " ";
std::cout << std::endl;
}
// =========== AllocTable ==========
const unsigned AllocTable::Avail = 0xffffffff;
const unsigned AllocTable::Eof = 0xfffffffe;
const unsigned AllocTable::Bat = 0xfffffffd;
const unsigned AllocTable::MetaBat = 0xfffffffc;
AllocTable::AllocTable()
{
blockSize = 4096;
// initial size
resize( 128 );
}
unsigned long AllocTable::count()
{
return data.size();
}
void AllocTable::resize( unsigned long newsize )
{
unsigned oldsize = data.size();
data.resize( newsize );
if( newsize > oldsize )
for( unsigned i = oldsize; i<newsize; i++ )
data[i] = Avail;
}
// make sure there're still free blocks
void AllocTable::preserve( unsigned long n )
{
std::vector<unsigned long> pre;
for( unsigned i=0; i < n; i++ )
pre.push_back( unused() );
}
unsigned long AllocTable::operator[]( unsigned long index )
{
unsigned long result;
result = data[index];
return result;
}
void AllocTable::set( unsigned long index, unsigned long value )
{
if( index >= count() ) resize( index + 1);
data[ index ] = value;
}
void AllocTable::setChain( std::vector<unsigned long> chain )
{
if( chain.size() )
{
for( unsigned i=0; i<chain.size()-1; i++ )
set( chain[i], chain[i+1] );
set( chain[ chain.size()-1 ], AllocTable::Eof );
}
}
// follow
std::vector<unsigned long> AllocTable::follow( unsigned long start )
{
std::vector<unsigned long> chain;
if( start >= count() ) return chain;
unsigned long p = start;
while( p < count() )
{
if( p == (unsigned long)Eof ) break;
if( p == (unsigned long)Bat ) break;
if( p == (unsigned long)MetaBat ) break;
if( p >= count() ) break;
chain.push_back( p );
if( data[p] >= count() ) break;
p = data[ p ];
}
return chain;
}
unsigned AllocTable::unused()
{
// find first available block
for( unsigned i = 0; i < data.size(); i++ )
if( data[i] == Avail )
return i;
// completely full, so enlarge the table
unsigned block = data.size();
resize( data.size()+10 );
return block;
}
void AllocTable::load( const unsigned char* buffer, unsigned len )
{
resize( len / 4 );
for( unsigned i = 0; i < count(); i++ )
set( i, readU32( buffer + i*4 ) );
}
// return space required to save this dirtree
unsigned AllocTable::size()
{
return count() * 4;
}
void AllocTable::save( unsigned char* buffer )
{
for( unsigned i = 0; i < count(); i++ )
writeU32( buffer + i*4, data[i] );
}
void AllocTable::debug()
{
std::cout << "block size " << data.size() << std::endl;
for( unsigned i=0; i< data.size(); i++ )
{
if( data[i] == Avail ) continue;
std::cout << i << ": ";
if( data[i] == Eof ) std::cout << "[eof]";
else if( data[i] == Bat ) std::cout << "[bat]";
else if( data[i] == MetaBat ) std::cout << "[metabat]";
else std::cout << data[i];
std::cout << std::endl;
}
}
// =========== DirTree ==========
const unsigned DirTree::End = 0xffffffff;
DirTree::DirTree()
{
clear();
}
void DirTree::clear()
{
// leave only root entry
entries.resize( 1 );
entries[0].valid = true;
entries[0].name = "Root Entry";
entries[0].dir = true;
entries[0].size = 0;
entries[0].start = End;
entries[0].prev = End;
entries[0].next = End;
entries[0].child = End;
}
inline unsigned DirTree::entryCount()
{
return entries.size();
}
DirEntry* DirTree::entry( unsigned index )
{
if( index >= entryCount() ) return (DirEntry*) 0;
return &entries[ index ];
}
int DirTree::indexOf( DirEntry* e )
{
for( unsigned i = 0; i < entryCount(); i++ )
if( entry( i ) == e ) return i;
return -1;
}
int DirTree::parent( unsigned index )
{
// brute-force, basically we iterate for each entries, find its children
// and check if one of the children is 'index'
for( unsigned j=0; j<entryCount(); j++ )
{
std::vector<unsigned> chi = children( j );
for( unsigned i=0; i<chi.size();i++ )
if( chi[i] == index )
return j;
}
return -1;
}
std::string DirTree::fullName( unsigned index )
{
// don't use root name ("Root Entry"), just give "/"
if( index == 0 ) return "/";
std::string result = entry( index )->name;
result.insert( 0, "/" );
int p = parent( index );
DirEntry * _entry = 0;
while( p > 0 )
{
_entry = entry( p );
if (_entry->dir && _entry->valid)
{
result.insert( 0, _entry->name);
result.insert( 0, "/" );
}
--p;
index = p;
if( index <= 0 ) break;
}
return result;
}
// given a fullname (e.g "/ObjectPool/_1020961869"), find the entry
// if not found and create is false, return 0
// if create is true, a new entry is returned
DirEntry* DirTree::entry( const std::string& name, bool create )
{
if( !name.length() ) return (DirEntry*)0;
// quick check for "/" (that's root)
if( name == "/" ) return entry( 0 );
// split the names, e.g "/ObjectPool/_1020961869" will become:
// "ObjectPool" and "_1020961869"
std::list<std::string> names;
std::string::size_type start = 0, end = 0;
if( name[0] == '/' ) start++;
while( start < name.length() )
{
end = name.find_first_of( '/', start );
if( end == std::string::npos ) end = name.length();
names.push_back( name.substr( start, end-start ) );
start = end+1;
}
// start from root
int index = 0 ;
// trace one by one
std::list<std::string>::iterator it;
for( it = names.begin(); it != names.end(); ++it )
{
// find among the children of index
unsigned child = 0;
/*
// dima: this block is really inefficient
std::vector<unsigned> chi = children( index );
for( unsigned i = 0; i < chi.size(); i++ )
{
DirEntry* ce = entry( chi[i] );
if( ce )
if( ce->valid && ( ce->name.length()>1 ) )
if( ce->name == *it ) {
child = chi[i];
break;
}
}
*/
// dima: performace optimisation of the previous
child = find_child( index, *it );
// traverse to the child
if( child > 0 ) index = child;
else
{
// not found among children
if( !create ) return (DirEntry*)0;
// create a new entry
unsigned parent = index;
entries.push_back( DirEntry() );
index = entryCount()-1;
DirEntry* e = entry( index );
e->valid = true;
e->name = *it;
e->dir = false;
e->size = 0;
e->start = 0;
e->child = End;
e->prev = End;
e->next = entry(parent)->child;
entry(parent)->child = index;
}
}
return entry( index );
}
// helper function: recursively find siblings of index
void dirtree_find_siblings( DirTree* dirtree, std::vector<unsigned>& result,
unsigned index )
{
DirEntry* e = dirtree->entry( index );
if( !e ) return;
if( !e->valid ) return;
// prevent infinite loop
for( unsigned i = 0; i < result.size(); i++ )
if( result[i] == index ) return;
// add myself
result.push_back( index );
// visit previous sibling, don't go infinitely
unsigned prev = e->prev;
if( ( prev > 0 ) && ( prev < dirtree->entryCount() ) )
{
for( unsigned i = 0; i < result.size(); i++ )
if( result[i] == prev ) prev = 0;
if( prev ) dirtree_find_siblings( dirtree, result, prev );
}
// visit next sibling, don't go infinitely
unsigned next = e->next;
if( ( next > 0 ) && ( next < dirtree->entryCount() ) )
{
for( unsigned i = 0; i < result.size(); i++ )
if( result[i] == next ) next = 0;
if( next ) dirtree_find_siblings( dirtree, result, next );
}
}
std::vector<unsigned> DirTree::children( unsigned index )
{
std::vector<unsigned> result;
DirEntry* e = entry( index );
if( e ) if( e->valid && e->child < entryCount() )
dirtree_find_siblings( this, result, e->child );
return result;
}
unsigned dirtree_find_sibling( DirTree* dirtree, unsigned index, const std::string& name ) {
unsigned count = dirtree->entryCount();
DirEntry* e = dirtree->entry( index );
if (!e || !e->valid) return 0;
if (e->name == name) return index;
if (e->next>0 && e->next<count) {
unsigned r = dirtree_find_sibling( dirtree, e->next, name );
if (r>0) return r;
}
if (e->prev>0 && e->prev<count) {
unsigned r = dirtree_find_sibling( dirtree, e->prev, name );
if (r>0) return r;
}
return 0;
}
unsigned DirTree::find_child( unsigned index, const std::string& name ) {
unsigned count = entryCount();
DirEntry* p = entry( index );
if (p && p->valid && p->child < count )
return dirtree_find_sibling( this, p->child, name );
return 0;
}
void DirTree::load( unsigned char* buffer, unsigned size )
{
entries.clear();
for( unsigned i = 0; i < size/128; i++ )
{
unsigned p = i * 128;
// would be < 32 if first char in the name isn't printable
unsigned prefix = 32;
// parse name of this entry, which stored as Unicode 16-bit
std::string name;
int name_len = readU16( buffer + 0x40+p );
if( name_len > 64 ) name_len = 64;
for( int j=0; ( buffer[j+p]) && (j<name_len); j+= 2 )
name.append( 1, buffer[j+p] );
// first char isn't printable ? remove it...
if( buffer[p] < 32 )
{
prefix = buffer[0];
name.erase( 0,1 );
}
// 2 = file (aka stream), 1 = directory (aka storage), 5 = root
unsigned type = buffer[ 0x42 + p];
DirEntry e;
e.valid = true;
e.name = name;
e.start = readU32( buffer + 0x74+p );
e.size = readU32( buffer + 0x78+p );
e.prev = readU32( buffer + 0x44+p );
e.next = readU32( buffer + 0x48+p );
e.child = readU32( buffer + 0x4C+p );
e.dir = ( type!=2 );
// sanity checks
if( (type != 2) && (type != 1 ) && (type != 5 ) ) e.valid = false;
if( name_len < 1 ) e.valid = false;
entries.push_back( e );
}
}
// return space required to save this dirtree
unsigned DirTree::size()
{
return entryCount() * 128;
}
void DirTree::save( unsigned char* buffer )
{
memset( buffer, 0, size() );
// root is fixed as "Root Entry"
DirEntry* root = entry( 0 );
std::string name = "Root Entry";
for( unsigned j = 0; j < name.length(); j++ )
buffer[ j*2 ] = name[j];
writeU16( buffer + 0x40, name.length()*2 + 2 );
writeU32( buffer + 0x74, 0xffffffff );
writeU32( buffer + 0x78, 0 );
writeU32( buffer + 0x44, 0xffffffff );
writeU32( buffer + 0x48, 0xffffffff );
writeU32( buffer + 0x4c, root->child );
buffer[ 0x42 ] = 5;
buffer[ 0x43 ] = 1;
for( unsigned i = 1; i < entryCount(); i++ )
{
DirEntry* e = entry( i );
if( !e ) continue;
if( e->dir )
{
e->start = 0xffffffff;
e->size = 0;
}
// max length for name is 32 chars
std::string name = e->name;
if( name.length() > 32 )
name.erase( 32, name.length() );
// write name as Unicode 16-bit
for( unsigned j = 0; j < name.length(); j++ )
buffer[ i*128 + j*2 ] = name[j];
writeU16( buffer + i*128 + 0x40, name.length()*2 + 2 );
writeU32( buffer + i*128 + 0x74, e->start );
writeU32( buffer + i*128 + 0x78, e->size );
writeU32( buffer + i*128 + 0x44, e->prev );
writeU32( buffer + i*128 + 0x48, e->next );
writeU32( buffer + i*128 + 0x4c, e->child );
buffer[ i*128 + 0x42 ] = e->dir ? 1 : 2;
buffer[ i*128 + 0x43 ] = 1; // always black
}
}
void DirTree::debug()
{
for( unsigned i = 0; i < entryCount(); i++ )
{
DirEntry* e = entry( i );
if( !e ) continue;
std::cout << i << ": ";
if( !e->valid ) std::cout << "INVALID ";
std::cout << e->name << " ";
if( e->dir ) std::cout << "(Dir) ";
else std::cout << "(File) ";
std::cout << e->size << " ";
std::cout << "s:" << e->start << " ";
std::cout << "(";
if( e->child == End ) std::cout << "-"; else std::cout << e->child;
std::cout << " ";
if( e->prev == End ) std::cout << "-"; else std::cout << e->prev;
std::cout << ":";
if( e->next == End ) std::cout << "-"; else std::cout << e->next;
std::cout << ")";
std::cout << std::endl;
}
}
// =========== StorageIO ==========
StorageIO::StorageIO( Storage* st, const char* fname )
{
storage = st;
filename = fname;
result = Storage::Ok;
opened = false;
header = new Header();
dirtree = new DirTree();
bbat = new AllocTable();
sbat = new AllocTable();
filesize = 0;
bbat->blockSize = 1 << header->b_shift;
sbat->blockSize = 1 << header->s_shift;
}
StorageIO::~StorageIO()
{
if( opened ) close();
delete sbat;
delete bbat;
delete dirtree;
delete header;
}
bool StorageIO::open()
{
// already opened ? close first
if( opened ) close();
load();
return result == Storage::Ok;
}
void StorageIO::load()
{
unsigned char* buffer = 0;
unsigned long buflen = 0;
std::vector<unsigned long> blocks;
// open the file, check for error
result = Storage::OpenFailed;
file.open( filename.c_str(), std::ios::binary | std::ios::in );
if( !file.good() ) return;
// find size of input file
file.seekg( 0, std::ios::end );
filesize = file.tellg();
// load header
buffer = new unsigned char[512];
file.seekg( 0 );
file.read( (char*)buffer, 512 );
header->load( buffer );
delete[] buffer;
// check OLE magic id
result = Storage::NotOLE;
for( unsigned i=0; i<8; i++ )
if( header->id[i] != pole_magic[i] )
return;
// sanity checks
result = Storage::BadOLE;
if( !header->valid() ) return;
if( header->threshold != 4096 ) return;
// important block size
bbat->blockSize = 1 << header->b_shift;
sbat->blockSize = 1 << header->s_shift;
// find blocks allocated to store big bat
// the first 109 blocks are in header, the rest in meta bat
blocks.clear();
blocks.resize( header->num_bat );
for( unsigned i = 0; i < 109; i++ )
if( i >= header->num_bat ) break;
else blocks[i] = header->bb_blocks[i];
if( (header->num_bat > 109) && (header->num_mbat > 0) )
{
unsigned char* buffer2 = new unsigned char[ bbat->blockSize ];
unsigned k = 109;
for( unsigned r = 0; r < header->num_mbat; r++ )
{
loadBigBlock( header->mbat_start+r, buffer2, bbat->blockSize );
for( unsigned s=0; s < bbat->blockSize; s+=4 )
{
if( k >= header->num_bat ) break;
else blocks[k++] = readU32( buffer2 + s );
}
}
delete[] buffer2;
}
// load big bat
buflen = blocks.size()*bbat->blockSize;
if( buflen > 0 )
{
buffer = new unsigned char[ buflen ];
loadBigBlocks( blocks, buffer, buflen );
bbat->load( buffer, buflen );
delete[] buffer;
}
// load small bat
blocks.clear();
blocks = bbat->follow( header->sbat_start );
buflen = blocks.size()*bbat->blockSize;
if( buflen > 0 )
{
buffer = new unsigned char[ buflen ];
loadBigBlocks( blocks, buffer, buflen );
sbat->load( buffer, buflen );
delete[] buffer;
}
// load directory tree
blocks.clear();
blocks = bbat->follow( header->dirent_start );
buflen = blocks.size()*bbat->blockSize;
buffer = new unsigned char[ buflen ];
loadBigBlocks( blocks, buffer, buflen );
dirtree->load( buffer, buflen );
unsigned sb_start = readU32( buffer + 0x74 );
delete[] buffer;
// fetch block chain as data for small-files
sb_blocks = bbat->follow( sb_start ); // small files
// for troubleshooting, just enable this block
#if 0
header->debug();
sbat->debug();
bbat->debug();
dirtree->debug();
#endif
// so far so good
result = Storage::Ok;
opened = true;
}
void StorageIO::create()
{
// std::cout << "Creating " << filename << std::endl;
file.open( filename.c_str(), std::ios::out|std::ios::binary );
if( !file.good() )
{
std::cerr << "Can't create " << filename << std::endl;
result = Storage::OpenFailed;
return;
}
// so far so good
opened = true;
result = Storage::Ok;
}
void StorageIO::flush()
{
/* Note on Microsoft implementation:
- directory entries are stored in the last block(s)
- BATs are as second to the last
- Meta BATs are third to the last
*/
}
void StorageIO::close()
{
if( !opened ) return;
file.close();
opened = false;
std::list<Stream*>::iterator it;
for( it = streams.begin(); it != streams.end(); ++it )
delete *it;
}
StreamIO* StorageIO::streamIO( const std::string& name )
{
// sanity check
if( !name.length() ) return (StreamIO*)0;
// search in the entries
DirEntry* entry = dirtree->entry( name );
//if( entry) std::cout << "FOUND\n";
if( !entry ) return (StreamIO*)0;
//if( !entry->dir ) std::cout << " NOT DIR\n";
if( entry->dir ) return (StreamIO*)0;
StreamIO* result = new StreamIO( this, entry );
result->fullName = name;
return result;
}
unsigned long StorageIO::loadBigBlocks( std::vector<unsigned long> blocks,
unsigned char* data, unsigned long maxlen )
{
// sentinel
if( !data ) return 0;
if( !file.good() ) return 0;
if( blocks.size() < 1 ) return 0;
if( maxlen == 0 ) return 0;
// read block one by one, seems fast enough
unsigned long bytes = 0;
for( unsigned long i=0; (i < blocks.size() ) & ( bytes<maxlen ); i++ )
{
unsigned long block = blocks[i];
unsigned long pos = bbat->blockSize * ( block+1 );
unsigned long p = (bbat->blockSize < maxlen-bytes) ? bbat->blockSize : maxlen-bytes;
if( pos + p > filesize ) p = filesize - pos;
file.seekg( pos );
file.read( (char*)data + bytes, p );
bytes += p;
}
return bytes;
}
unsigned long StorageIO::loadBigBlock( unsigned long block,
unsigned char* data, unsigned long maxlen )
{
// sentinel
if( !data ) return 0;
if( !file.good() ) return 0;
// wraps call for loadBigBlocks
std::vector<unsigned long> blocks;
blocks.resize( 1 );
blocks[ 0 ] = block;
return loadBigBlocks( blocks, data, maxlen );
}
// return number of bytes which has been read
unsigned long StorageIO::loadSmallBlocks( std::vector<unsigned long> blocks,
unsigned char* data, unsigned long maxlen )
{
// sentinel
if( !data ) return 0;
if( !file.good() ) return 0;
if( blocks.size() < 1 ) return 0;
if( maxlen == 0 ) return 0;
// our own local buffer
unsigned char* buf = new unsigned char[ bbat->blockSize ];
// read small block one by one
unsigned long bytes = 0;
for( unsigned long i=0; ( i<blocks.size() ) & ( bytes<maxlen ); i++ )
{
unsigned long block = blocks[i];
// find where the small-block exactly is
unsigned long pos = block * sbat->blockSize;
unsigned long bbindex = pos / bbat->blockSize;
if( bbindex >= sb_blocks.size() ) break;
loadBigBlock( sb_blocks[ bbindex ], buf, bbat->blockSize );
// copy the data
unsigned offset = pos % bbat->blockSize;
unsigned long p = (maxlen-bytes < bbat->blockSize-offset ) ? maxlen-bytes : bbat->blockSize-offset;
p = (sbat->blockSize<p ) ? sbat->blockSize : p;
memcpy( data + bytes, buf + offset, p );
bytes += p;
}
delete[] buf;
return bytes;
}
unsigned long StorageIO::loadSmallBlock( unsigned long block,
unsigned char* data, unsigned long maxlen )
{
// sentinel
if( !data ) return 0;
if( !file.good() ) return 0;
// wraps call for loadSmallBlocks
std::vector<unsigned long> blocks;
blocks.resize( 1 );
blocks.assign( 1, block );
return loadSmallBlocks( blocks, data, maxlen );
}
// =========== StreamIO ==========
StreamIO::StreamIO( StorageIO* s, DirEntry* e)
{
io = s;
entry = e;
eof = false;
fail = false;
m_pos = 0;
if( entry->size >= io->header->threshold )
blocks = io->bbat->follow( entry->start );
else
blocks = io->sbat->follow( entry->start );
// prepare cache
cache_pos = 0;
cache_size = 4096; // optimal ?
cache_data = new unsigned char[cache_size];
updateCache();
}
// FIXME tell parent we're gone
StreamIO::~StreamIO()
{
delete[] cache_data;
}
void StreamIO::seek( unsigned long pos )
{
m_pos = pos;
}
unsigned long StreamIO::tell()
{
return m_pos;
}
int StreamIO::getch()
{
// past end-of-file ?
if( m_pos > entry->size ) return -1;
// need to update cache ?
if( !cache_size || ( m_pos < cache_pos ) ||
( m_pos >= cache_pos + cache_size ) )
updateCache();
// something bad if we don't get good cache
if( !cache_size ) return -1;
int data = cache_data[m_pos - cache_pos];
m_pos++;
return data;
}
unsigned long StreamIO::read( unsigned long pos, unsigned char* data, unsigned long maxlen )
{
// sanity checks
if( !data ) return 0;
if( maxlen == 0 ) return 0;
unsigned long totalbytes = 0;
if ( entry->size < io->header->threshold )
{
// small file
unsigned long index = pos / io->sbat->blockSize;
if( index >= blocks.size() ) return 0;
unsigned char* buf = new unsigned char[ io->sbat->blockSize ];
unsigned long offset = pos % io->sbat->blockSize;
while( totalbytes < maxlen )
{
if( index >= blocks.size() ) break;
io->loadSmallBlock( blocks[index], buf, io->bbat->blockSize );
unsigned long count = io->sbat->blockSize - offset;
if( count > maxlen-totalbytes ) count = maxlen-totalbytes;
memcpy( data+totalbytes, buf + offset, count );
totalbytes += count;
offset = 0;
index++;
}
delete[] buf;
}
else
{
// big file
unsigned long index = pos / io->bbat->blockSize;
if( index >= blocks.size() ) return 0;
unsigned char* buf = new unsigned char[ io->bbat->blockSize ];
unsigned long offset = pos % io->bbat->blockSize;
while( totalbytes < maxlen )
{
if( index >= blocks.size() ) break;
io->loadBigBlock( blocks[index], buf, io->bbat->blockSize );
unsigned long count = io->bbat->blockSize - offset;
if( count > maxlen-totalbytes ) count = maxlen-totalbytes;
memcpy( data+totalbytes, buf + offset, count );
totalbytes += count;
index++;
offset = 0;
}
delete [] buf;
}
return totalbytes;
}
unsigned long StreamIO::read( unsigned char* data, unsigned long maxlen )
{
unsigned long bytes = read( tell(), data, maxlen );
m_pos += bytes;
return bytes;
}
void StreamIO::updateCache()
{
// sanity check
if( !cache_data ) return;
cache_pos = m_pos - ( m_pos % cache_size );
unsigned long bytes = cache_size;
if( cache_pos + bytes > entry->size ) bytes = entry->size - cache_pos;
cache_size = read( cache_pos, cache_data, bytes );
}
// =========== Storage ==========
Storage::Storage( const char* filename )
{
io = new StorageIO( this, filename );
}
Storage::~Storage()
{
delete io;
}
int Storage::result()
{
return io->result;
}
bool Storage::open()
{
return io->open();
}
void Storage::close()
{
io->close();
}
std::list<std::string> Storage::entries( const std::string& path )
{
std::list<std::string> result;
DirTree* dt = io->dirtree;
DirEntry* e = dt->entry( path, false );
if( e && e->dir )
{
unsigned parent = dt->indexOf( e );
std::vector<unsigned> children = dt->children( parent );
for( unsigned i = 0; i < children.size(); i++ )
result.push_back( dt->entry( children[i] )->name );
}
return result;
}
bool Storage::isDirectory( const std::string& name )
{
DirEntry* e = io->dirtree->entry( name, false );
return e ? e->dir : false;
}
// =========== Stream ==========
Stream::Stream( Storage* storage, const std::string& name )
{
io = storage->io->streamIO( name );
}
// FIXME tell parent we're gone
Stream::~Stream()
{
delete io;
}
std::string Stream::fullName()
{
return io ? io->fullName : std::string();
}
unsigned long Stream::tell()
{
return io ? io->tell() : 0;
}
void Stream::seek( unsigned long newpos )
{
if( io ) io->seek( newpos );
}
unsigned long Stream::size()
{
return io ? io->entry->size : 0;
}
int Stream::getch()
{
return io ? io->getch() : 0;
}
unsigned long Stream::read( unsigned char* data, unsigned long maxlen )
{
return io ? io->read( data, maxlen ) : 0;
}
bool Stream::eof()
{
return io ? io->eof : false;
}
bool Stream::fail()
{
return io ? io->fail : true;
}
| [
"wjbeaver@gmail.com"
] | wjbeaver@gmail.com |
a6cec8d27d428586709b60fa7e23d4a5abbcf6ee | 2034641d74f1d075c27bf6670e6bf4f456704640 | /waveType.cpp | 298a71c6e5195ac929e9aaecd7a039374cfaa68a | [] | no_license | Jake-Howell/Synth-OS | 4da8ba6ead5caa57aa137af2b5845b2e4f2a24f5 | f84b1341a8e02b5e53d336963f1ae891ddbb99f8 | refs/heads/master | 2023-08-20T08:02:45.427738 | 2021-10-29T15:05:19 | 2021-10-29T15:05:19 | 260,003,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | //This file is a public member function of the UpdateOutput class.
//It is used to quickly select the type of output wave required
//and pass any relavent data to them for each sample
//waveType() gets the current sample number and time samplesInPeriod
//from the "output_mail_box" struct that's updated by main()
//it then passes these varibles to the user selected wave type
//which are all initalised as private member functions of the UpdateOutput class
#include "updateOutput.h"
//#define RUNTIME_LOGGING
void UpdateOutput::type(){
switch(waveType)
{
case OFF:
Vout = 0.0f;
break;
case SINE:
#ifdef RUNTIME_LOGGING
runTimeTest.reset();
runTimeTest.start();
#endif
Vout = sinWave();
break;
case TRIANGLE:
#ifdef RUNTIME_LOGGING
runTimeTest.reset();
runTimeTest.start();
#endif
Vout = triangleWave();
break;
case SAW:
#ifdef RUNTIME_LOGGING
runTimeTest.reset();
runTimeTest.start();
#endif
Vout = sawWave();
break;
case SQUARE:
#ifdef RUNTIME_LOGGING
runTimeTest.reset();
runTimeTest.start();
#endif
Vout = squareWave();
break;
default:
waveType = OFF;
break;
}//end of wave type switch case
dac.write(Vout);
} | [
"jakehowell8@gmail.com"
] | jakehowell8@gmail.com |
72badb74c22f60932e4ee7704cb9b3b84e1f10d6 | af9b7ec8cc4b1102001b710034b2f2e245b7d320 | /src/qt/bitcoin.cpp | 45f89079dfcbcc854b0a3581aee78a3d43ba39e5 | [
"MIT"
] | permissive | fubendong2/lvyecoin | a2144fe4b7c50fd10e95e57b838412f6596b288a | 87b1249ff066dd2de9b356e78f894f44d82ba07e | refs/heads/master | 2020-04-08T14:48:55.607764 | 2014-03-21T06:52:47 | 2014-03-21T06:52:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,163 | cpp | /*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Lvyecoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Lvyecoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Lvyecoin");
app.setOrganizationDomain("TODO: replace");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Lvyecoin-Qt-testnet");
else
app.setApplicationName("Lvyecoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
| [
"fubendong100@163.com"
] | fubendong100@163.com |
34597244843a93ac3fb1595e13443842d50f8f8d | 8bb6d8ce77b9064da19fe3915a706904223f3f0a | /LeetCode/0983 - Minimum Cost For Tickets.cpp | 0450e2492d4c9e96887feff506305381a127897e | [] | no_license | wj32/Judge | 8c92eb2c108839395bc902454030745b97ed7f29 | d0bd7805c0d441c892c28a718470a378a38e7124 | refs/heads/master | 2023-08-16T19:16:59.475037 | 2023-08-02T03:46:12 | 2023-08-02T03:46:12 | 8,853,058 | 6 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 557 | cpp | class Solution {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
vector<int> r(days.size() + 1);
r[0] = 0;
for (int i = 1; i <= days.size(); ++i) {
const auto findPriorIndex = [&](const auto offset) {
return distance(days.begin(), upper_bound(days.begin(), days.begin() + i - 1, days[i - 1] - offset));
};
r[i] = min({costs[0] + r[i - 1], costs[1] + r[findPriorIndex(7)], costs[2] + r[findPriorIndex(30)]});
}
return r[days.size()];
}
}; | [
"wj32.64@gmail.com"
] | wj32.64@gmail.com |
61397b4c0cdcaf414766b54baa1df3c47d4b179f | 8042492efe5c71fc031b904bbe97cd5162513c12 | /tensorflow/compiler/xla/service/mlir_gpu/mlir_compiler.cc | 2afbb7389baea3daaa1f99bd9319c0396affc9b4 | [
"Apache-2.0"
] | permissive | OwletCare/tensorflow | bee48306c5b29207edc80c6ada13e1e7ff2c4614 | 39f47a417daedc81e0b265b6062e23acb0c4211d | refs/heads/master | 2020-07-07T00:39:22.124841 | 2019-08-19T13:27:45 | 2019-08-19T13:33:00 | 203,185,316 | 0 | 0 | Apache-2.0 | 2019-08-19T14:06:48 | 2019-08-19T14:06:47 | null | UTF-8 | C++ | false | false | 4,025 | cc | /* Copyright 2019 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/mlir_gpu/mlir_compiler.h"
#include "mlir/LLVMIR/LLVMDialect.h" // TF:local_config_mlir
#include "tensorflow/compiler/xla/service/gpu/gpu_constants.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/gpu/nvptx_compiler.h"
#include "tensorflow/compiler/xla/service/gpu/target_constants.h"
#include "tensorflow/compiler/xla/service/mlir_gpu/failover_compiler.h"
#include "tensorflow/core/lib/core/errors.h"
namespace xla {
namespace mlir {
using ::mlir::MLIRContext;
using ::mlir::LLVM::LLVMDialect;
namespace {
int64 ConfigureLLVMModuleAndGetPointerSize(MLIRContext* context) {
LLVMDialect* dialect = context->getRegisteredDialect<LLVMDialect>();
llvm::Module& module = dialect->getLLVMModule();
module.setTargetTriple(gpu::nvptx::kTargetTriple);
module.setDataLayout(gpu::nvptx::kDataLayout);
return module.getDataLayout().getPointerSize();
}
} // namespace
MlirCompiler::MlirCompiler()
: pointer_size_(ConfigureLLVMModuleAndGetPointerSize(&context_)) {}
se::Platform::Id MlirCompiler::PlatformId() const {
return stream_executor::cuda::kCudaPlatformId;
}
StatusOr<std::unique_ptr<HloModule>> MlirCompiler::RunHloPasses(
std::unique_ptr<HloModule> module, se::StreamExecutor* stream_exec,
se::DeviceMemoryAllocator* device_allocator) {
// Until we find a reason to do something different, run the same passes
// that the normal GPU backend runs.
gpu::NVPTXCompiler xla_compiler;
TF_RETURN_IF_ERROR(xla_compiler.OptimizeHloModule(module.get(), stream_exec,
device_allocator));
TF_RETURN_IF_ERROR(xla_compiler.PrepareHloModuleForIrEmitting(module.get()));
return std::move(module);
}
StatusOr<std::unique_ptr<Executable>> MlirCompiler::RunBackend(
std::unique_ptr<HloModule> module, se::StreamExecutor* stream_exec,
se::DeviceMemoryAllocator* device_allocator) {
return Unimplemented("Not yet implemented in MLIR compiler");
}
StatusOr<std::vector<std::unique_ptr<Executable>>>
MlirCompiler::RunBackendOnModuleGroup(
std::unique_ptr<HloModuleGroup> module_group,
std::vector<std::vector<se::StreamExecutor*>> stream_exec,
se::DeviceMemoryAllocator* device_allocator) {
return Unimplemented("Not yet implemented in MLIR compiler");
}
StatusOr<std::vector<std::unique_ptr<Executable>>> MlirCompiler::Compile(
std::unique_ptr<HloModuleGroup> module_group,
std::vector<std::vector<se::StreamExecutor*>> stream_execs,
se::DeviceMemoryAllocator* device_allocator) {
return Unimplemented("Not yet implemented in MLIR compiler");
}
StatusOr<std::vector<std::unique_ptr<AotCompilationResult>>>
MlirCompiler::CompileAheadOfTime(std::unique_ptr<HloModuleGroup> module_group,
const AotCompilationOptions& options) {
return Unimplemented("Not yet implemented in MLIR compiler");
}
} // namespace mlir
} // namespace xla
static bool InitModule() {
xla::Compiler::RegisterCompilerFactory(
stream_executor::cuda::kCudaPlatformId, []() {
return absl::make_unique<xla::FailoverCompiler>(
absl::make_unique<xla::mlir::MlirCompiler>(),
absl::make_unique<xla::gpu::NVPTXCompiler>());
});
return true;
}
static bool module_initialized = InitModule();
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
888a0472af6c3934081674eb2bc70a8a16bd3122 | e35c07c1a2c2d38e01e314977fc535a0b78a7f57 | /src/main.cpp | e976360288ec08aa4eb3d62b5c8ff0e7f31517ef | [
"MIT"
] | permissive | Luckshya/httpreq-squirrel | 0e598ea09f0274c8c56926be8a588d5cb2771c3c | f5bd0e16922cf678e5fa388763bcf0908ce5be4b | refs/heads/master | 2022-11-14T23:50:11.052635 | 2020-06-27T08:15:15 | 2020-06-27T08:15:15 | 241,582,890 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,416 | cpp | // Main include
#include "main.h"
#if defined(WIN32) || defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
#include "SqImports.h"
#include "sqrat.h"
#include "CRequest.h"
#include "CResponse.h"
#include "Misc.h"
// Definitions
HSQAPI sq;
HSQUIRRELVM v;
// Global variables (meh)
PluginFuncs * gFuncs;
using namespace SqHTTP;
uint8_t SqHTTP_OnSquirrelScriptLoad()
{
// See if we have any imports from Squirrel
size_t size;
int sqId = gFuncs->FindPlugin( "SQHost2" );
// Is there a squirrel host plugin?
if (sqId < 0)
{
OutputMsg("Unable to locate the host plug-in");
return 0;
}
const void ** sqExports = gFuncs->GetPluginExports( sqId, &size );
// We do!
if( sqExports != NULL && size > 0 )
{
// Cast to a SquirrelImports structure
SquirrelImports ** sqDerefFuncs = (SquirrelImports **)sqExports;
// Now let's change that to a SquirrelImports pointer
SquirrelImports * sqFuncs = (SquirrelImports *)(*sqDerefFuncs);
// Now we get the virtual machine
if( sqFuncs )
{
// Get a pointer to the VM and API
sq = *(sqFuncs->GetSquirrelAPI());
v = *(sqFuncs->GetSquirrelVM());
Sqrat::ErrorHandling::Enable(true);
Sqrat::DefaultVM::Set(v);
Sqrat::Table HTTPcn(v);
Sqrat::RootTable(v).Bind("SqHTTP", HTTPcn);
SqHTTP::GetRequest::Register(HTTPcn);
return 1;
}
}
else
{
OutputMsg( "Failed to attach to SQHost2." );
}
return 0;
}
uint8_t SqHTTP_OnPluginCommand(uint32_t command_identifier, const char* /*message*/)
{
switch( command_identifier )
{
case 0x7D6E22D8: return SqHTTP_OnSquirrelScriptLoad();
default:
break;
}
return 1;
}
uint8_t SqHTTP_OnServerInitialise()
{
printf( "\n" );
OutputMsg( "Loaded SqHTTP module for VC:MP 0.4 by Luckshya." );
return 1;
}
void SqHTTP_OnServerFrame(float)
{
Response::Update();
}
void SqHTTP_OnServerShutdown()
{
clearFuture();
Response::Clear();
}
EXPORT unsigned int VcmpPluginInit( PluginFuncs* functions, PluginCallbacks* callbacks, PluginInfo* info )
{
// Set our plugin information
info->pluginVersion = 0x1001; // 1.0.01
info->apiMajorVersion = PLUGIN_API_MAJOR;
info->apiMinorVersion = PLUGIN_API_MINOR;
sprintf(info->name, "%s", "HTTP Requests for VC:MP");
// Store functions for later use
gFuncs = functions;
// Store callback
callbacks->OnServerInitialise = SqHTTP_OnServerInitialise;
callbacks->OnPluginCommand = SqHTTP_OnPluginCommand;
callbacks->OnServerFrame = SqHTTP_OnServerFrame;
callbacks->OnServerShutdown = SqHTTP_OnServerShutdown;
// Done!
return 1;
}
namespace SqHTTP
{
void OutputDebug(const char * msg)
{
#ifdef _DEBUG
OutputMsg(msg);
#endif
}
void OutputMsg(const char * msg)
{
#if defined(WIN32) || defined(_WIN32)
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbBefore;
GetConsoleScreenBufferInfo(hstdout, &csbBefore);
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN);
printf("[MODULE] ");
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("%s\n", msg);
SetConsoleTextAttribute(hstdout, csbBefore.wAttributes);
#else
printf("%c[0;32m[MODULE]%c[0;37m %s\n", 27, 27, msg);
#endif
}
void OutputErr(const char * msg)
{
#ifdef WIN32
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbBefore;
GetConsoleScreenBufferInfo(hstdout, &csbBefore);
SetConsoleTextAttribute(hstdout, FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("[ERROR] ");
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("%s\n", msg);
SetConsoleTextAttribute(hstdout, csbBefore.wAttributes);
#else
printf("%c[0;31m[ERROR]%c[0;37m %s\n", 27, 27, msg);
#endif
}
void OutputWarn(const char * msg)
{
#ifdef WIN32
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbBefore;
GetConsoleScreenBufferInfo(hstdout, &csbBefore);
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
std::cout << "[WARNING] ";
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY);
std::cout << msg << std::endl;
SetConsoleTextAttribute(hstdout, csbBefore.wAttributes);
#else
printf("%c[1;33m[WARNING]%c[0;37m %s\n", 27, 27, msg);
#endif
}
} // Namespace - SqHTTP | [
"luckshyaverma@gmail.com"
] | luckshyaverma@gmail.com |
077d7dadb1ed4669976469c49967e0cfa076406f | 21553f6afd6b81ae8403549467230cdc378f32c9 | /arm/cortex/Spansion/MB9AF11xL/include/arch/reg/dtim.hpp | d78478b195849a135d85ee574bcd97c64a4b1309 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | digint/openmptl-reg-arm-cortex | 3246b68dcb60d4f7c95a46423563cab68cb02b5e | 88e105766edc9299348ccc8d2ff7a9c34cddacd3 | refs/heads/master | 2021-07-18T19:56:42.569685 | 2017-10-26T11:11:35 | 2017-10-26T11:11:35 | 108,407,162 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,525 | hpp | /*
* OpenMPTL - C++ Microprocessor Template Library
*
* This program is a derivative representation of a CMSIS System View
* Description (SVD) file, and is subject to the corresponding license
* (see "License.txt" in the parent directory).
*
* 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.
*/
////////////////////////////////////////////////////////////////////////
//
// Import from CMSIS-SVD: "Spansion/MB9AF11xL.svd"
//
// name: MB9AF11xL
// version: 1.7
// description: MB9AF11xL
// --------------------------------------------------------------------
//
// C++ Header file, containing architecture specific register
// declarations for use in OpenMPTL. It has been converted directly
// from a CMSIS-SVD file.
//
// https://digint.ch/openmptl
// https://github.com/posborne/cmsis-svd
//
#ifndef ARCH_REG_DTIM_HPP_INCLUDED
#define ARCH_REG_DTIM_HPP_INCLUDED
#warning "using untested register declarations"
#include <register.hpp>
namespace mptl {
/**
* Dual Timer
*/
struct DTIM
{
static constexpr reg_addr_t base_addr = 0x40015000;
/**
* Load Register
*/
struct TIMER1LOAD
: public reg< uint32_t, base_addr + 0x0, rw, 0x00000000 >
{
};
/**
* Value Register
*/
struct TIMER1VALUE
: public reg< uint32_t, base_addr + 0x4, ro, 0xFFFFFFFF >
{
};
/**
* Control Register
*/
struct TIMER1CONTROL
: public reg< uint32_t, base_addr + 0x8, rw, 0x00000020 >
{
using type = reg< uint32_t, base_addr + 0x8, rw, 0x00000020 >;
using TimerEn = regbits< type, 7, 1 >; /**< Enable bit */
using TimerMode = regbits< type, 6, 1 >; /**< Mode bit */
using IntEnable = regbits< type, 5, 1 >; /**< Interrupt enable bit */
using TimerPre = regbits< type, 2, 2 >; /**< Prescale bits */
using TimerSize = regbits< type, 1, 1 >; /**< Counter size bit */
using OneShot = regbits< type, 0, 1 >; /**< One-shot mode bit */
};
/**
* Interrupt Clear Register
*/
struct TIMER1INTCLR
: public reg< uint32_t, base_addr + 0xc, wo, 0x00000000 >
{
};
/**
* Interrupt Status Register
*/
struct TIMER1RIS
: public reg< uint32_t, base_addr + 0x10, ro, 0x00000000 >
{
using type = reg< uint32_t, base_addr + 0x10, ro, 0x00000000 >;
// fixme: Field name equals parent register name: TIMER1RIS
using TIMER1RIS_ = regbits< type, 0, 1 >; /**< Interrupt Status Register bit */
};
/**
* Masked Interrupt Status Register
*/
struct TIMER1MIS
: public reg< uint32_t, base_addr + 0x14, ro, 0x00000000 >
{
using type = reg< uint32_t, base_addr + 0x14, ro, 0x00000000 >;
// fixme: Field name equals parent register name: TIMER1MIS
using TIMER1MIS_ = regbits< type, 0, 1 >; /**< Masked Interrupt Status bit */
};
/**
* Background Load Register
*/
struct TIMER1BGLOAD
: public reg< uint32_t, base_addr + 0x18, rw, 0x00000000 >
{
};
/**
* Load Register
*
* (derived from: TIMER1LOAD)
*/
struct TIMER2LOAD
: public reg< uint32_t, base_addr + 0x20, rw, 0 /* svd2hpp: missing resetValue! */ >
{
};
/**
* Value Register
*
* (derived from: TIMER1VALUE)
*/
struct TIMER2VALUE
: public reg< uint32_t, base_addr + 0x24, rw, 0 /* svd2hpp: missing resetValue! */ >
{
};
/**
* Control Register
*
* (derived from: TIMER1CONTROL)
*/
struct TIMER2CONTROL
: public reg< uint32_t, base_addr + 0x28, rw, 0 /* svd2hpp: missing resetValue! */ >
{
};
/**
* Interrupt Clear Register
*
* (derived from: TIMER1INTCLR)
*/
struct TIMER2INTCLR
: public reg< uint32_t, base_addr + 0x2c, rw, 0 /* svd2hpp: missing resetValue! */ >
{
};
/**
* Interrupt Status Register
*
* (derived from: TIMER1RIS)
*/
struct TIMER2RIS
: public reg< uint32_t, base_addr + 0x30, rw, 0 /* svd2hpp: missing resetValue! */ >
{
};
/**
* Masked Interrupt Status Register
*
* (derived from: TIMER1MIS)
*/
struct TIMER2MIS
: public reg< uint32_t, base_addr + 0x34, rw, 0 /* svd2hpp: missing resetValue! */ >
{
};
/**
* Background Load Register
*
* (derived from: TIMER1BGLOAD)
*/
struct TIMER2BGLOAD
: public reg< uint32_t, base_addr + 0x38, rw, 0 /* svd2hpp: missing resetValue! */ >
{
};
};
} // namespace mptl
#endif // ARCH_REG_DTIM_HPP_INCLUDED
| [
"axel@tty0.ch"
] | axel@tty0.ch |
32819a5f5490231ba543d1a42569678ff6c84b11 | bff4518b3089c014e9af2e729d98f5521138073b | /Hamiltonian_and_lagrangian.cpp | 5f93d0c23dab4e2f36141d3223607705d28fbf7a | [] | no_license | Aniganesh/100daysofcode | 3d5e2e6c3d8526938620cf9fac700c69175618ec | 2c11d71a5374be0d845b568ef16009bd3f1718da | refs/heads/master | 2021-05-16T22:58:48.915268 | 2020-07-17T18:18:48 | 2020-07-17T18:18:48 | 250,505,128 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | cpp | // https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/hamiltonian-and-lagrangian/
// 05-05-2020 Very-easy/easy
#include<bits/stdc++.h>
#define MOD % 1000000007
typedef long long ll;
using namespace std;
int main(){
int numValues;
cin >> numValues;
int values[numValues];
for(int i = 0; i < numValues; i++){
cin >> values[i];
}
int maxTillI[numValues], maximum = values[numValues-1];
for(int i=numValues-1; i > -1; i--){
maximum = max(maximum,values[i]);
maxTillI[i] = maximum;
}
for(int i = 0; i < numValues-1; i++){
if(values[i] >= maxTillI[i])
cout << values[i] << " ";
}
cout << values[numValues-1];
} | [
"aniganesh741@gmail.com"
] | aniganesh741@gmail.com |
2c1ac073911b7c59157a598b1e5790d0fc8aa1ae | 75c11e41007c4a5564ee170960bdef5bdc072c44 | /wi-fi/wi-fi.ino | 8a72bc61d62cf9bfa44900a69adce317233861e4 | [] | no_license | joss185/PECUS | d549c2fd8bfb2953278340a72ae7b3a2b8941a2d | 80a060672b1370b5c302cd4c3a7199fe8453c6bb | refs/heads/master | 2020-03-28T22:00:45.088859 | 2018-09-18T01:35:37 | 2018-09-18T01:35:37 | 149,199,079 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,521 | ino |
#define DEBUG true
void setup()
{
delay(500);
//Seta ambas seriais para a velocidade de 9600
Serial.begin(9600);
//(em alguns casos a velocidade do seu Serial2 pode estar diferente desta)
Serial2.begin(9600);
//Envia o comandos AT
// reseta o modulo
sendData("AT+RST\r\n",2000,DEBUG);
// configure as access point e estação (ambos)
sendData("AT+CWMODE=3\r\n",1000,DEBUG);
//conecta ao roteador com a senha
//(esta configuração deve ser feita, pois o seu roteador tem nome diferente do meu e senha)
sendData("AT+CWJAP=\"familiamazovargas\",\"Santy25092007\"\r\n",10000,DEBUG);
//Retorna o IP ao qual está conectado e o IP de Station
sendData("AT+CIFSR\r\n",1000,DEBUG);
//Habilita multiplas conexões
sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
//Habilita ao servidor a porta 80
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);
}
void loop()
{
//verifica se o Serial2 esta enviando mensagem e esta disponivel
IniciarWiFi();
}
void IniciarWiFi(){
if(Serial2.available())
{
if(Serial2.find("+IPD,"))
{
// subtrai 48, por que o metodo read() retorna os valores ASCII, o primeiro numero decimal começa em 48
int connectionId = Serial2.read()-48;
//Inicia a montagem da pagina web
//criando a variavel webpage e armazenando os dados nela
String webpage = "<head><meta http-equiv=""refresh"" content=""5""></head>";
webpage+="<h1>Ola Mundo</h1><h2> Serial2</h2></br><h3>Temperatura : ";
//Envia o valor lido do sensor de temperatura
webpage+= "Paso1";
webpage+=" </br> Iluminosidade : ";
//Envia o valor lido do sensor de ldr
webpage+= "paso 2 </h3>";
//cria uma variavel para enviar o comando até
//que enviará as informações para o modulo Serial2
String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend +=webpage.length();
cipSend +="\r\n";
//Envia os comandos para o modulo
sendData(cipSend,1000,DEBUG);
sendData(webpage,1000,DEBUG);
//Encerra os comandos
String closeCommand = "AT+CIPCLOSE=";
closeCommand+=connectionId;
closeCommand+="\r\n";
//Envia os comandos de encerramento
sendData(closeCommand,2000,DEBUG);
delay(5000);
}
}
}
//Metodo que envia os comandos para o Serial2
String sendData(String command, const int timeout, boolean debug)
{
//variavel de resposta do Serial2
String response = "";
// send a leitura dos caracteres para o Serial2
Serial2.println(command);
long int time = millis();
while( (time+timeout) > millis())
{
while(Serial2.available())
{
//Concatena caracter por caractere recebido do modulo Serial2
char c = Serial2.read();
response+=c;
}
}
//debug de resposta do Serial2
if(debug)
{
//Imprime o que o Serial2 enviou para o arduino
Serial.println("Arduino : " + response);
}
return response;
}
//Metodo que converte float em string
long getDecimal(float val)
{
//converte o float para inteiro
int intPart = int(val);
//multiplica por 100
//precisão de 2 casas decimais
long decPart = 100*(val-intPart);
//Se o valor for maior que 0 retorna
if(decPart>0)
//retorna a variavel decPart
return(decPart);
//caso contrario retorna o valor 0
else if(decPart=0)
return(00);
}
| [
"celizondo@gbm.net"
] | celizondo@gbm.net |
9f3f243e5ffce039fa15366d1f9af244b17cc554 | ae956d4076e4fc03b632a8c0e987e9ea5ca89f56 | /SDK/TBP_PlayerWallGrindState_functions.cpp | 3cb811ed965747dcf1cd46df5c82f6e3327ed3c6 | [] | no_license | BrownBison/Bloodhunt-BASE | 5c79c00917fcd43c4e1932bee3b94e85c89b6bc7 | 8ae1104b748dd4b294609717142404066b6bc1e6 | refs/heads/main | 2023-08-07T12:04:49.234272 | 2021-10-02T15:13:42 | 2021-10-02T15:13:42 | 638,649,990 | 1 | 0 | null | 2023-05-09T20:02:24 | 2023-05-09T20:02:23 | null | UTF-8 | C++ | false | false | 10,660 | cpp | // Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.AssignPhysicalMaterial
// Flags -> (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FHitResult Hit (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData, NoDestructor, ContainsInstancedReference)
// struct FName BoneName (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::AssignPhysicalMaterial(const struct FHitResult& Hit, const struct FName& BoneName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.AssignPhysicalMaterial");
UTBP_PlayerWallGrindState_C_AssignPhysicalMaterial_Params params;
params.Hit = Hit;
params.BoneName = BoneName;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.CheckForParticleSystemUpdate
// Flags -> (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FName BoneName (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FHitResult HitResult (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor, ContainsInstancedReference)
// class ACharacter* Character (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::CheckForParticleSystemUpdate(const struct FName& BoneName, const struct FHitResult& HitResult, class ACharacter* Character)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.CheckForParticleSystemUpdate");
UTBP_PlayerWallGrindState_C_CheckForParticleSystemUpdate_Params params;
params.BoneName = BoneName;
params.HitResult = HitResult;
params.Character = Character;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.DestroyParticleSystem
// Flags -> (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FName BoneName (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::DestroyParticleSystem(const struct FName& BoneName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.DestroyParticleSystem");
UTBP_PlayerWallGrindState_C_DestroyParticleSystem_Params params;
params.BoneName = BoneName;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.CreateParticleSystem
// Flags -> (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FName BoneName (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FHitResult HitResult (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor, ContainsInstancedReference)
// class ACharacter* Character (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::CreateParticleSystem(const struct FName& BoneName, const struct FHitResult& HitResult, class ACharacter* Character)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.CreateParticleSystem");
UTBP_PlayerWallGrindState_C_CreateParticleSystem_Params params;
params.BoneName = BoneName;
params.HitResult = HitResult;
params.Character = Character;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.StartEffect
// Flags -> (Event, Protected, HasOutParms, BlueprintEvent)
// Parameters:
// struct FName InAssociatedBoneName (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FHitResult InHitResult (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData, NoDestructor, ContainsInstancedReference)
// class ATigerCharacter* InTigerCharacter (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::StartEffect(const struct FName& InAssociatedBoneName, const struct FHitResult& InHitResult, class ATigerCharacter* InTigerCharacter)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.StartEffect");
UTBP_PlayerWallGrindState_C_StartEffect_Params params;
params.InAssociatedBoneName = InAssociatedBoneName;
params.InHitResult = InHitResult;
params.InTigerCharacter = InTigerCharacter;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.StopEffect
// Flags -> (Event, Protected, HasOutParms, BlueprintEvent)
// Parameters:
// struct FName InAssociatedBoneName (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// class ATigerCharacter* InTigerCharacter (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::StopEffect(const struct FName& InAssociatedBoneName, class ATigerCharacter* InTigerCharacter)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.StopEffect");
UTBP_PlayerWallGrindState_C_StopEffect_Params params;
params.InAssociatedBoneName = InAssociatedBoneName;
params.InTigerCharacter = InTigerCharacter;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.UpdateEffect
// Flags -> (Event, Protected, HasOutParms, BlueprintEvent)
// Parameters:
// struct FName InAssociatedBoneName (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FHitResult InHitResult (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData, NoDestructor, ContainsInstancedReference)
// class ATigerCharacter* InTigerCharacter (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::UpdateEffect(const struct FName& InAssociatedBoneName, const struct FHitResult& InHitResult, class ATigerCharacter* InTigerCharacter)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.UpdateEffect");
UTBP_PlayerWallGrindState_C_UpdateEffect_Params params;
params.InAssociatedBoneName = InAssociatedBoneName;
params.InHitResult = InHitResult;
params.InTigerCharacter = InTigerCharacter;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.ExecuteUbergraph_TBP_PlayerWallGrindState
// Flags -> (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_PlayerWallGrindState_C::ExecuteUbergraph_TBP_PlayerWallGrindState(int EntryPoint)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_PlayerWallGrindState.TBP_PlayerWallGrindState_C.ExecuteUbergraph_TBP_PlayerWallGrindState");
UTBP_PlayerWallGrindState_C_ExecuteUbergraph_TBP_PlayerWallGrindState_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"69031575+leoireo@users.noreply.github.com"
] | 69031575+leoireo@users.noreply.github.com |
59737772228f472a860f09944f386238fdbe9ea9 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /Trigger/TrigHypothesis/TrigHLTJetHypo/src/JVTConditionMT.cxx | 33ae1d96e90246a2a3dc81f381247dd243f960c9 | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,328 | cxx | /*
Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
*/
#include "./JVTConditionMT.h"
#include "./ITrigJetHypoInfoCollector.h"
#include <sstream>
#include <stdexcept>
#include <TLorentzVector.h>
#include <limits>
#include <memory>
JVTConditionMT::JVTConditionMT(double workingPoint):
m_workingPoint(workingPoint) {
}
bool JVTConditionMT::isSatisfied(const HypoJetVector& ips, const std::unique_ptr<ITrigJetHypoInfoCollector>& collector) const{
if(ips.size() != 1){
std::stringstream ss;
ss << "DijetMT::isSatisfied must see exactly 1 particle, but received "
<< ips.size()
<< '\n';
throw std::runtime_error(ss.str());
}
auto jet = ips[0];
// The conditions for each jet are: JVT>JVTwp or |eta|>2.5 or pT>60
auto pt = jet->pt() * 0.001; // MeV -> GeV
float detEta = 0;
if(!(jet->getAttribute("DetectorEta",detEta))){
throw std::runtime_error("JVT condition cannot retrieve variable 'DetectorEta', 'DetectorEta' does not exist");
}
auto absdetEta = std::abs(detEta);
bool jvtApplicable = (absdetEta<m_maxEta and pt<m_maxPt) ? true : false;
bool pass = false;
float jvt = -1.;
if(!jvtApplicable){ // jvt not applicable
pass = true;
} else { // jvt applicable
if(!(jet->getAttribute("Jvt",jvt))){
throw std::runtime_error("JVT condition cannot retrieve variable 'Jvt', 'Jvt' does not exist");
}
pass = (jvt>m_workingPoint) ? true : false;
}
if(collector){
std::stringstream ss0;
const void* address = static_cast<const void*>(this);
ss0 << "JVTConditionMT: (" << address
<< ") jvt " << jvt
<< " pt " << pt
<< " absdetEta " << absdetEta
<< " pass: " <<std::boolalpha << pass << " jet group: \n";
std::stringstream ss1;
for(auto ip : ips){
address = static_cast<const void*>(ip);
ss1 << " " << address << " " << ip->eta() << " pt " << ip->pt() << '\n';
}
ss1 << '\n';
collector -> collect(ss0.str(), ss1.str());
}
return pass;
}
std::string JVTConditionMT::toString() const noexcept {
std::stringstream ss;
const void* address = static_cast<const void*>(this);
ss << "JVTConditionMT: (" << address << ") Capacity: " << s_capacity
<< " workingPoint: " << m_workingPoint << '\n';
return ss.str();
}
| [
"jonathan.bossio@cern.ch"
] | jonathan.bossio@cern.ch |
ef6874b41bdc76df943bfff3c833efc04ec82e6c | eb4098b0a240130ce7d2d039bc13d91d4da0fe31 | /Modules/simulator_utils/include/ode/libs/numeric/odeint/test/adams_bashforth_moulton.cpp | 55af50df8ae056dc043fd18f06ab171cca48c7e9 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | amov-lab/Prometheus | f1d97ebebb58c14527bfe148275037b8dbd71154 | 017c50ee6a0a388caca193fd5a06ba237150bd05 | refs/heads/main | 2023-09-01T12:59:19.777116 | 2023-07-07T07:28:57 | 2023-07-07T07:28:57 | 225,547,305 | 2,129 | 396 | Apache-2.0 | 2022-08-04T03:04:23 | 2019-12-03T06:28:07 | C++ | UTF-8 | C++ | false | false | 3,193 | cpp | /*
[auto_generated]
libs/numeric/odeint/test/adams_bashforth_moulton.cpp
[begin_description]
This file tests the use of the Adams-Bashforth-Moulton.
[end_description]
Copyright 2009-2012 Karsten Ahnert
Copyright 2009-2012 Mario Mulansky
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)
*/
#define BOOST_TEST_MODULE odeint_adams_bashforth_moulton
#include <utility>
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/numeric/odeint/stepper/adams_bashforth_moulton.hpp>
using namespace boost::unit_test;
using namespace boost::numeric::odeint;
typedef double value_type;
struct lorenz
{
template< class State , class Deriv , class Value >
void operator()( const State &_x , Deriv &_dxdt , const Value &dt ) const
{
const value_type sigma = 10.0;
const value_type R = 28.0;
const value_type b = 8.0 / 3.0;
typename boost::range_iterator< const State >::type x = boost::begin( _x );
typename boost::range_iterator< Deriv >::type dxdt = boost::begin( _dxdt );
dxdt[0] = sigma * ( x[1] - x[0] );
dxdt[1] = R * x[0] - x[1] - x[0] * x[2];
dxdt[2] = x[0]*x[1] - b * x[2];
}
};
BOOST_AUTO_TEST_SUITE( adams_bashforth_moulton_test )
typedef boost::mpl::range_c< size_t , 1 , 6 > vector_of_steps;
BOOST_AUTO_TEST_CASE_TEMPLATE( test_init_and_steps , step_type , vector_of_steps )
{
const static size_t steps = step_type::value;
typedef boost::array< value_type , 3 > state_type;
adams_bashforth_moulton< steps , state_type > stepper;
state_type x = {{ 10.0 , 10.0 , 10.0 }};
const value_type dt = 0.01;
value_type t = 0.0;
stepper.initialize( lorenz() , x , t , dt );
BOOST_CHECK_CLOSE( t , value_type( steps - 1 ) * dt , 1.0e-14 );
stepper.do_step( lorenz() , x , t , dt );
}
BOOST_AUTO_TEST_CASE( test_copying )
{
typedef boost::array< double , 1 > state_type;
typedef adams_bashforth_moulton< 2 , state_type > stepper_type;
stepper_type s1;
stepper_type s2( s1 );
stepper_type s3;
s3 = s1;
}
BOOST_AUTO_TEST_CASE( test_instantiation )
{
typedef boost::array< double , 3 > state_type;
adams_bashforth_moulton< 1 , state_type > s1;
adams_bashforth_moulton< 2 , state_type > s2;
adams_bashforth_moulton< 3 , state_type > s3;
adams_bashforth_moulton< 4 , state_type > s4;
adams_bashforth_moulton< 5 , state_type > s5;
adams_bashforth_moulton< 6 , state_type > s6;
adams_bashforth_moulton< 7 , state_type > s7;
adams_bashforth_moulton< 8 , state_type > s8;
state_type x = {{ 10.0 , 10.0 , 10.0 }};
value_type t = 0.0 , dt = 0.01;
s1.do_step( lorenz() , x , t , dt );
s2.do_step( lorenz() , x , t , dt );
s3.do_step( lorenz() , x , t , dt );
s4.do_step( lorenz() , x , t , dt );
s5.do_step( lorenz() , x , t , dt );
s6.do_step( lorenz() , x , t , dt );
// s7.do_step( lorenz() , x , t , dt );
// s8.do_step( lorenz() , x , t , dt );
}
BOOST_AUTO_TEST_SUITE_END()
| [
"fatmoonqyp@126.com"
] | fatmoonqyp@126.com |
15bf418f4179b815735a273a0f0b060cca65dc53 | 83dc8201868cc003eff7f970f9660302f85422e2 | /src/s2/s2text_format.h | f092613c2898252ad4a1bd6d145d6897dd012b2c | [] | no_license | cran/s2 | 7beeeaf29c572a1063353fa356104fef95d1f6f8 | 832e2a76bf56bc71b9eb440bee3bb23c5c90b4bf | refs/heads/master | 2023-05-30T05:55:09.829416 | 2023-05-17T09:40:02 | 2023-05-17T09:40:02 | 72,815,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,690 | h | // Copyright Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef S2_S2TEXT_FORMAT_H_
#define S2_S2TEXT_FORMAT_H_
// s2text_format contains a collection of functions for converting
// geometry to and from a human-readable format. It is mainly
// intended for testing and debugging. Be aware that the
// human-readable format is *not* designed to preserve the full
// precision of the original object, so it should not be used
// for data storage.
#include <memory>
#include <string>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/strings/string_view.h"
#include "s2/s2cell_id.h"
#include "s2/s2cell_union.h"
#include "s2/s2debug.h"
#include "s2/s2latlng_rect.h"
#include "s2/s2point_span.h"
class MutableS2ShapeIndex;
class S2LaxPolygonShape;
class S2LaxPolylineShape;
class S2Loop;
class S2Polygon;
class S2Polyline;
class S2ShapeIndex;
namespace s2textformat {
// Returns an S2Point corresponding to the given a latitude-longitude
// coordinate in degrees. Example of the input format:
// "-20:150"
S2Point MakePointOrDie(absl::string_view str);
// As above, but do not S2_CHECK-fail on invalid input. Returns true if conversion
// is successful.
ABSL_MUST_USE_RESULT bool MakePoint(absl::string_view str, S2Point* point);
ABSL_DEPRECATED("Use MakePointOrDie.")
inline S2Point MakePoint(absl::string_view str) { return MakePointOrDie(str); }
// Parses a string of one or more latitude-longitude coordinates in degrees,
// and return the corresponding vector of S2LatLng points.
// Examples of the input format:
// "" // no points
// "-20:150" // one point
// "-20:150, -20:151, -19:150" // three points
std::vector<S2LatLng> ParseLatLngsOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool ParseLatLngs(absl::string_view str,
std::vector<S2LatLng>* latlngs);
ABSL_DEPRECATED("Use ParseLatLngsOrDie.")
inline std::vector<S2LatLng> ParseLatLngs(absl::string_view str) {
return ParseLatLngsOrDie(str);
}
// Parses a string in the same format as ParseLatLngs, and return the
// corresponding vector of S2Point values.
std::vector<S2Point> ParsePointsOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool ParsePoints(absl::string_view str,
std::vector<S2Point>* vertices);
ABSL_DEPRECATED("Use ParsePointsOrDie.")
inline std::vector<S2Point> ParsePoints(absl::string_view str) {
return ParsePointsOrDie(str);
}
// Given a string in the same format as ParseLatLngs, returns a single S2LatLng.
S2LatLng MakeLatLngOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeLatLng(absl::string_view str, S2LatLng* latlng);
// Given a string in the same format as ParseLatLngs, returns the minimal
// bounding S2LatLngRect that contains the coordinates.
S2LatLngRect MakeLatLngRectOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeLatLngRect(absl::string_view str,
S2LatLngRect* rect);
ABSL_DEPRECATED("Use MakeLatLngRectOrDie.")
inline S2LatLngRect MakeLatLngRect(absl::string_view str) {
return MakeLatLngRectOrDie(str);
}
// Parses an S2CellId in the format "f/dd..d" where "f" is a digit in the
// range [0-5] representing the S2CellId face, and "dd..d" is a string of
// digits in the range [0-3] representing each child's position with respect
// to its parent. (Note that the latter string may be empty.)
//
// For example "4/" represents S2CellId::FromFace(4), and "3/02" represents
// S2CellId::FromFace(3).child(0).child(2).
//
// This function is a wrapper for S2CellId::FromDebugString().
S2CellId MakeCellIdOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeCellId(absl::string_view str, S2CellId* cell_id);
// Parses a comma-separated list of S2CellIds in the format above, and returns
// the corresponding S2CellUnion. (Note that S2CellUnions are automatically
// normalized by sorting, removing duplicates, and replacing groups of 4 child
// cells by their parent cell.)
S2CellUnion MakeCellUnionOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeCellUnion(absl::string_view str,
S2CellUnion* cell_union);
// Given a string of latitude-longitude coordinates in degrees,
// returns a newly allocated loop. Example of the input format:
// "-20:150, 10:-120, 0.123:-170.652"
// The strings "empty" or "full" create an empty or full loop respectively.
std::unique_ptr<S2Loop> MakeLoopOrDie(absl::string_view str,
S2Debug debug_override = S2Debug::ALLOW);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeLoop(absl::string_view str,
std::unique_ptr<S2Loop>* loop,
S2Debug debug_override = S2Debug::ALLOW);
ABSL_DEPRECATED("Use MakeLoopOrDie.")
std::unique_ptr<S2Loop> MakeLoop(absl::string_view str,
S2Debug debug_override = S2Debug::ALLOW);
// Similar to MakeLoop(), but returns an S2Polyline rather than an S2Loop.
std::unique_ptr<S2Polyline> MakePolylineOrDie(
absl::string_view str,
S2Debug debug_override = S2Debug::ALLOW);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakePolyline(absl::string_view str,
std::unique_ptr<S2Polyline>* polyline,
S2Debug debug_override = S2Debug::ALLOW);
ABSL_DEPRECATED("Use MakePolylineOrDie.")
std::unique_ptr<S2Polyline> MakePolyline(
absl::string_view str,
S2Debug debug_override = S2Debug::ALLOW);
// Like MakePolyline, but returns an S2LaxPolylineShape instead.
std::unique_ptr<S2LaxPolylineShape> MakeLaxPolylineOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeLaxPolyline(
absl::string_view str, std::unique_ptr<S2LaxPolylineShape>* lax_polyline);
ABSL_DEPRECATED("Use MakeLaxPolylineOrDie.")
std::unique_ptr<S2LaxPolylineShape> MakeLaxPolyline(absl::string_view str);
// Given a sequence of loops separated by semicolons, returns a newly
// allocated polygon. Loops are automatically normalized by inverting them
// if necessary so that they enclose at most half of the unit sphere.
// (Historically this was once a requirement of polygon loops. It also
// hides the problem that if the user thinks of the coordinates as X:Y
// rather than LAT:LNG, it yields a loop with the opposite orientation.)
//
// Examples of the input format:
// "10:20, 90:0, 20:30" // one loop
// "10:20, 90:0, 20:30; 5.5:6.5, -90:-180, -15.2:20.3" // two loops
// "" // the empty polygon (consisting of no loops)
// "empty" // the empty polygon (consisting of no loops)
// "full" // the full polygon (consisting of one full loop).
std::unique_ptr<S2Polygon> MakePolygonOrDie(
absl::string_view str,
S2Debug debug_override = S2Debug::ALLOW);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakePolygon(absl::string_view str,
std::unique_ptr<S2Polygon>* polygon,
S2Debug debug_override = S2Debug::ALLOW);
ABSL_DEPRECATED("Use MakePolygonOrDie.")
std::unique_ptr<S2Polygon> MakePolygon(absl::string_view str,
S2Debug debug_override = S2Debug::ALLOW);
// Like MakePolygon(), except that it does not normalize loops (i.e., it
// gives you exactly what you asked for).
std::unique_ptr<S2Polygon> MakeVerbatimPolygonOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeVerbatimPolygon(
absl::string_view str, std::unique_ptr<S2Polygon>* polygon);
ABSL_DEPRECATED("Use MakeVerbatimPolygonOrDie.")
std::unique_ptr<S2Polygon> MakeVerbatimPolygon(absl::string_view str);
// Parses a string in the same format as MakePolygon, except that loops must
// be oriented so that the interior of the loop is always on the left, and
// polygons with degeneracies are supported. As with MakePolygon, "full" and
// denotes the full polygon and "" or "empty" denote the empty polygon.
std::unique_ptr<S2LaxPolygonShape> MakeLaxPolygonOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeLaxPolygon(
absl::string_view str, std::unique_ptr<S2LaxPolygonShape>* lax_polygon);
ABSL_DEPRECATED("Use MakeLaxPolygonOrDie.")
std::unique_ptr<S2LaxPolygonShape> MakeLaxPolygon(absl::string_view str);
// Returns a MutableS2ShapeIndex containing the points, polylines, and loops
// (in the form of a single polygon) described by the following format:
//
// point1|point2|... # line1|line2|... # polygon1|polygon2|...
//
// Examples:
// 1:2 | 2:3 # # // Two points
// # 0:0, 1:1, 2:2 | 3:3, 4:4 # // Two polylines
// # # 0:0, 0:3, 3:0; 1:1, 2:1, 1:2 // Two nested loops (one polygon)
// 5:5 # 6:6, 7:7 # 0:0, 0:1, 1:0 // One of each
// # # empty // One empty polygon
// # # empty | full // One empty polygon, one full polygon
//
// Loops should be directed so that the region's interior is on the left.
// Loops can be degenerate (they do not need to meet S2Loop requirements).
//
// CAVEAT: Because whitespace is ignored, empty polygons must be specified
// as the string "empty" rather than as the empty string ("").
std::unique_ptr<MutableS2ShapeIndex> MakeIndexOrDie(absl::string_view str);
// As above, but does not S2_CHECK-fail on invalid input. Returns true if
// conversion is successful.
ABSL_MUST_USE_RESULT bool MakeIndex(
absl::string_view str, std::unique_ptr<MutableS2ShapeIndex>* index);
ABSL_DEPRECATED("Use MakeIndexOrDie.")
std::unique_ptr<MutableS2ShapeIndex> MakeIndex(absl::string_view str);
// Convert an S2Point, S2LatLng, S2LatLngRect, S2CellId, S2CellUnion, loop,
// polyline, or polygon to the string format above.
std::string ToString(const S2Point& point);
std::string ToString(const S2LatLng& latlng);
std::string ToString(const S2LatLngRect& rect);
std::string ToString(const S2CellId& cell_id);
std::string ToString(const S2CellUnion& cell_union);
std::string ToString(const S2Loop& loop);
std::string ToString(S2PointLoopSpan loop);
std::string ToString(const S2Polyline& polyline);
std::string ToString(const S2Polygon& polygon, const char* loop_separator = ";\n");
std::string ToString(const std::vector<S2Point>& points);
std::string ToString(const std::vector<S2LatLng>& points);
std::string ToString(const S2LaxPolylineShape& polyline);
std::string ToString(const S2LaxPolygonShape& polygon,
const char* loop_separator = ";\n");
// Convert the contents of an S2ShapeIndex to the format above. The index may
// contain S2Shapes of any type. Shapes are reordered if necessary so that
// all point geometry (shapes of dimension 0) are first, followed by all
// polyline geometry, followed by all polygon geometry.
std::string ToString(const S2ShapeIndex& index);
} // namespace s2textformat
#endif // S2_S2TEXT_FORMAT_H_
| [
"csardi.gabor+cran@gmail.com"
] | csardi.gabor+cran@gmail.com |
d9d39de2c89c516aba96f0c4039bb698cd44b936 | cad838f9a28c8e97003185b870ece96c00a2e696 | /AERO_HackTM/src/RestSender.h | eee82aac0f0f16411f4670d5aa161823c9f9a5cb | [] | no_license | HackTM2016/SpeedFeed | 6d58fad8ef7373e306c0c13b5aa531003b53e7af | c71fa7ac7f70fdd2b9aec572534221ffa2ead3ff | refs/heads/master | 2020-12-24T20:43:16.876872 | 2016-05-22T14:03:17 | 2016-05-22T14:03:17 | 59,361,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | h | #pragma once
#include <cpprest/http_client.h>
#include <cpprest/json.h>
typedef pplx::task<web::http::http_response> HTTP_RESPONSE;
class CRESTSender
{
public:
CRESTSender(web::http::client::http_client & client);
~CRESTSender();
CRESTSender(CRESTSender const& rs)
: m_httpClient(rs.m_httpClient)
{
}
CRESTSender& operator = (CRESTSender const& rs)
{
if (this != &rs) {
m_httpClient = rs.m_httpClient;
}
return *this;
}
HTTP_RESPONSE task_request(web::http::method mtd,
web::json::value const & jvalue);
HTTP_RESPONSE task_string_request(web::http::method mtd,
const utility::string_t &body_data);
void make_request(web::http::method mtd, web::json::value const & jvalue);
private:
web::http::client::http_client &m_httpClient;
};
| [
"silviu.ardelean@gmail.com"
] | silviu.ardelean@gmail.com |
f2fe6747492296cdbe070020f4ef794539efb5ae | 92e67b30497ffd29d3400e88aa553bbd12518fe9 | /assignment2/part6/Re=110/22.5/U | afd54659b9518b01128e95f36cb2a8f72db7695f | [] | no_license | henryrossiter/OpenFOAM | 8b89de8feb4d4c7f9ad4894b2ef550508792ce5c | c54b80dbf0548b34760b4fdc0dc4fb2facfdf657 | refs/heads/master | 2022-11-18T10:05:15.963117 | 2020-06-28T15:24:54 | 2020-06-28T15:24:54 | 241,991,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,403 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "22.5";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
2000
(
(0.00519035 0.0252535 3.03666e-22)
(0.027049 0.0918325 0)
(0.0611218 0.160778 0)
(0.0920626 0.222507 4.53607e-22)
(0.115878 0.2727 1.63218e-22)
(0.131767 0.311075 2.26011e-22)
(0.140867 0.339462 -2.89506e-22)
(0.145016 0.360244 0)
(0.145988 0.375517 0)
(0.145312 0.386726 0)
(0.0031004 0.017871 0)
(0.0188571 0.0747626 6.34601e-22)
(0.0477281 0.138706 -5.85083e-22)
(0.0766827 0.200033 -5.3058e-22)
(0.101435 0.253309 0)
(0.119908 0.296473 5.17938e-22)
(0.131978 0.329849 -4.81638e-22)
(0.138658 0.354923 0)
(0.141328 0.373481 2.87212e-21)
(0.141594 0.387048 -6.03192e-21)
(0.00194209 0.0113735 0)
(0.012612 0.058301 -4.94789e-21)
(0.0358688 0.115505 0)
(0.0614663 0.174071 -1.75229e-21)
(0.0856271 0.228442 0)
(0.105671 0.27541 -8.78247e-22)
(0.120436 0.313878 0)
(0.12999 0.344154 3.96307e-21)
(0.135033 0.367287 -3.71176e-21)
(0.136938 0.384539 -4.77002e-21)
(0.00150236 0.00593081 1.49238e-21)
(0.00819188 0.0431787 2.52702e-21)
(0.025952 0.0924536 9.25015e-22)
(0.0472784 0.146022 1.23281e-21)
(0.069339 0.198978 4.79835e-22)
(0.0895114 0.247785 2.1175e-22)
(0.106074 0.2904 6.1974e-22)
(0.118297 0.326021 -8.20601e-22)
(0.126094 0.354711 3.04462e-21)
(0.130268 0.377098 4.75911e-21)
(0.00153899 0.00163486 1.52203e-21)
(0.00530428 0.0299313 1.76335e-21)
(0.0181036 0.0707227 1.97904e-21)
(0.034835 0.117558 -9.90014e-22)
(0.0536681 0.166563 0)
(0.0724649 0.21456 0)
(0.089451 0.259235 -1.84933e-21)
(0.103462 0.299106 -2.60586e-21)
(0.113809 0.333362 2.46894e-21)
(0.120296 0.361734 1.06686e-20)
(0.00181162 -0.001511 -1.13244e-21)
(0.0035703 0.0188619 -4.66095e-22)
(0.0122029 0.0512152 3.29789e-21)
(0.0245613 0.090303 -2.72121e-21)
(0.0396345 0.133299 3.70659e-22)
(0.0559031 0.177758 0)
(0.0718853 0.221658 0)
(0.0863474 0.263409 8.75124e-21)
(0.0985016 0.301837 -1.09338e-20)
(0.106311 0.335433 3.19051e-21)
(0.00210906 -0.00357657 -8.282e-21)
(0.00260873 0.0100651 0)
(0.00798278 0.0345107 -4.40763e-21)
(0.0165778 0.0655823 2.3202e-21)
(0.02795 0.101312 0)
(0.0411325 0.140026 6.79386e-22)
(0.055066 0.180285 -2.29418e-21)
(0.0687072 0.220813 -5.85608e-21)
(0.0817944 0.260829 2.73884e-21)
(0.0891199 0.296586 4.10822e-21)
(0.00227502 -0.00468759 1.53396e-20)
(0.00211362 0.00347793 1.17108e-21)
(0.00516109 0.0209029 1.55733e-21)
(0.0108181 0.0443365 2.31844e-21)
(0.0189843 0.0724087 -9.76229e-23)
(0.0291086 0.10406 -6.22904e-22)
(0.0405414 0.138424 2.32634e-22)
(0.0526348 0.174724 0)
(0.065975 0.213171 0)
(0.0713191 0.246863 -1.46271e-21)
(0.00222575 -0.00500621 -7.05763e-21)
(0.00191253 -0.00107084 4.54496e-21)
(0.00355403 0.0104788 -2.73218e-21)
(0.00719225 0.0271671 -2.69354e-21)
(0.0128987 0.0479733 4.26671e-22)
(0.020406 0.0722077 5.67153e-22)
(0.0294202 0.0993758 9.36714e-22)
(0.0398857 0.129184 0)
(0.0531721 0.162743 0)
(0.0568957 0.18936 1.95565e-22)
(0.00195806 -0.00471865 7.06983e-22)
(0.00199674 -0.00382504 -5.45772e-21)
(0.00314548 0.00319555 8.40908e-22)
(0.00572032 0.0144381 0)
(0.00982904 0.0290325 0)
(0.0153589 0.0464169 6.77578e-22)
(0.022267 0.0661873 0)
(0.0310548 0.0881974 -1.48413e-21)
(0.0437983 0.113121 1.018e-21)
(0.0507229 0.128706 3.5176e-22)
(0.139277 0.404725 4.47486e-22)
(0.121429 0.407676 -4.54983e-22)
(0.102079 0.401885 -6.61502e-22)
(0.0848886 0.394997 -7.7308e-22)
(0.0665681 0.389221 -9.13538e-22)
(0.0526367 0.38809 -6.49242e-24)
(0.0347933 0.405054 4.63687e-22)
(0.0263051 0.478987 1.52203e-21)
(0.00432416 0.634666 0)
(0.00719988 0.821569 -1.05196e-21)
(0.136909 0.407922 9.9649e-22)
(0.119037 0.412334 -2.28107e-21)
(0.0999611 0.406955 4.20839e-21)
(0.0830734 0.400247 7.74462e-22)
(0.0650163 0.394183 1.6292e-21)
(0.0512766 0.392539 2.68961e-21)
(0.0338636 0.409079 -9.69564e-22)
(0.0253889 0.482373 -1.01036e-21)
(0.0044477 0.637334 1.93024e-21)
(0.00680771 0.822833 1.04946e-21)
(0.134865 0.410655 0)
(0.117022 0.416954 -1.78618e-21)
(0.0982179 0.412191 -1.25146e-21)
(0.0815525 0.405631 0)
(0.0636335 0.399128 -4.92234e-21)
(0.0500221 0.396822 1.55064e-21)
(0.0329458 0.412602 1.65977e-21)
(0.0244594 0.484888 5.44629e-21)
(0.00450997 0.639342 -1.92399e-21)
(0.00643409 0.823762 3.75307e-21)
(0.132711 0.412085 0)
(0.115263 0.420933 1.80186e-21)
(0.0967935 0.417235 0)
(0.0802769 0.410949 5.67001e-21)
(0.0624066 0.403997 -5.69809e-21)
(0.0488789 0.40097 -3.30317e-21)
(0.0320487 0.415671 -1.52668e-22)
(0.0235431 0.486551 -5.26233e-21)
(0.00454124 0.640481 -8.70827e-22)
(0.00606216 0.824339 -4.62381e-21)
(0.129641 0.410979 2.40019e-21)
(0.113667 0.424648 -2.66219e-21)
(0.0957993 0.42274 9.26403e-22)
(0.0792636 0.41649 -4.64656e-21)
(0.0613081 0.408886 0)
(0.0477986 0.405004 -3.12419e-21)
(0.0311095 0.418328 -1.05116e-22)
(0.0225362 0.487508 6.64096e-21)
(0.00442776 0.64107 8.36699e-22)
(0.00566943 0.82459 -8.3973e-22)
(0.12484 0.404881 -6.01128e-21)
(0.111818 0.426028 5.76463e-21)
(0.0949875 0.427352 4.33534e-21)
(0.0784343 0.421605 -4.33087e-21)
(0.0603989 0.413658 -2.60301e-21)
(0.0468833 0.408985 0)
(0.0302465 0.420662 -5.96288e-21)
(0.0215674 0.487651 2.9574e-21)
(0.00428886 0.640554 3.09239e-21)
(0.00528419 0.824464 3.09591e-21)
(0.117478 0.392684 -4.38079e-22)
(0.109819 0.427534 0)
(0.0946366 0.43319 0)
(0.0777785 0.427221 0)
(0.0595096 0.418551 -2.67216e-21)
(0.0458887 0.412852 5.2657e-21)
(0.0291957 0.422678 5.77598e-21)
(0.0203096 0.487408 -8.65287e-21)
(0.00385063 0.639974 1.4664e-21)
(0.00481015 0.824064 -4.51846e-21)
(0.107665 0.369359 1.56055e-21)
(0.106524 0.422407 5.69047e-21)
(0.0939421 0.435771 -5.63364e-21)
(0.0773521 0.431602 8.99671e-21)
(0.0590898 0.423277 -1.12272e-20)
(0.0453711 0.416869 0)
(0.0285479 0.424555 -2.57769e-21)
(0.0193409 0.486106 1.68751e-22)
(0.00350634 0.637615 -2.60397e-21)
(0.00441174 0.823204 -2.69102e-21)
(0.0961011 0.342906 -7.1475e-22)
(0.103729 0.421873 0)
(0.0935792 0.441607 -7.64362e-21)
(0.0766239 0.437359 1.53207e-20)
(0.0580608 0.428189 -6.0193e-21)
(0.0440613 0.420482 -1.18491e-21)
(0.0270478 0.426176 2.57218e-21)
(0.017486 0.485459 8.03212e-23)
(0.00251169 0.636586 3.79338e-21)
(0.00376415 0.822223 3.90791e-21)
(0.0829624 0.291076 -2.10024e-21)
(0.0973913 0.402775 2.03539e-21)
(0.0922535 0.438626 6.79292e-22)
(0.0770712 0.440487 0)
(0.0588822 0.433081 0)
(0.0447881 0.425014 1.14538e-21)
(0.0274743 0.427788 4.57148e-21)
(0.0170459 0.482016 -4.46319e-21)
(0.00209034 0.631598 -1.1165e-21)
(0.00339424 0.820554 1.07552e-21)
(0.0601526 0.24711 0)
(0.0909343 0.401575 0)
(0.0863607 0.451711 0)
(0.0697721 0.455124 0)
(0.0503707 0.443808 0)
(0.0350911 0.431522 0)
(0.0180067 0.431723 0)
(0.00814387 0.484859 0)
(-0.00282773 0.631633 0)
(0.00112411 0.817369 0)
(0.0430271 0.228993 0)
(0.0723894 0.393796 0)
(0.0686572 0.457756 0)
(0.0572923 0.470952 0)
(0.0438026 0.464793 0)
(0.0316947 0.453994 0)
(0.0151761 0.453216 0)
(0.00210985 0.501259 0)
(-0.00753134 0.639673 0)
(-8.16931e-05 0.819829 0)
(0.0341002 0.233089 0)
(0.0533412 0.395674 0)
(0.0480017 0.468249 0)
(0.0343586 0.481457 0)
(0.018964 0.472297 0)
(0.00641954 0.460002 0)
(-0.00839957 0.459905 0)
(-0.0190912 0.505273 0)
(-0.0223436 0.634407 0)
(-0.00221599 0.808373 0)
(0.0186037 0.23591 0)
(0.0278698 0.38456 0)
(0.030487 0.467706 0)
(0.0284202 0.493805 0)
(0.0192394 0.492025 0)
(0.00609618 0.482085 0)
(-0.0123462 0.480759 0)
(-0.0280529 0.518553 0)
(-0.0343714 0.631351 0)
(-0.00592185 0.795928 0)
(0.00615131 0.256736 0)
(0.00766352 0.390821 0)
(0.00238748 0.467311 0)
(-0.000431409 0.492898 0)
(-0.00804798 0.494226 0)
(-0.0185191 0.489588 0)
(-0.0339057 0.491483 0)
(-0.0470082 0.523829 0)
(-0.0512844 0.616566 0)
(-0.0148886 0.762328 0)
(-0.00939234 0.255225 0)
(-0.00350599 0.383192 0)
(0.00188443 0.469071 0)
(0.00540241 0.503135 0)
(-0.00155178 0.509676 0)
(-0.0141284 0.507903 0)
(-0.0321894 0.510405 0)
(-0.0482292 0.53598 0)
(-0.0557036 0.607311 0)
(-0.0218562 0.725391 0)
(-0.0142259 0.281705 0)
(-0.0213125 0.384936 0)
(-0.0227074 0.46262 0)
(-0.019933 0.497 0)
(-0.0206179 0.511462 0)
(-0.025216 0.517333 0)
(-0.0367263 0.522992 0)
(-0.0483139 0.542866 0)
(-0.0541127 0.593673 0)
(-0.024842 0.679648 0)
(-0.0110174 0.282972 0)
(-0.00816309 0.384375 0)
(0.00048327 0.470902 0)
(-0.00435962 0.504078 0)
(-0.0118331 0.517379 0)
(-0.0183436 0.525853 0)
(-0.0273208 0.535132 0)
(-0.035464 0.552792 0)
(-0.0401727 0.587974 0)
(-0.0201338 0.644 0)
(-0.00622572 0.311023 0)
(-0.0320051 0.369829 0)
(-0.0170689 0.456296 0)
(-0.00890392 0.504128 0)
(-0.0103445 0.522737 0)
(-0.0148482 0.531473 0)
(-0.0219229 0.539975 0)
(-0.0273059 0.554631 0)
(-0.0299366 0.580405 0)
(-0.0152313 0.617769 0)
(0.0359364 0.347314 0)
(0.00665451 0.398138 0)
(-0.000678972 0.456474 0)
(0.00139868 0.500612 0)
(0.000811237 0.524419 0)
(-0.00126802 0.537721 0)
(-0.00609521 0.548149 0)
(-0.00994965 0.560738 0)
(-0.013006 0.577442 0)
(-0.00691522 0.597838 0)
(0.0457418 0.0994531 -1.16471e-23)
(0.0526445 0.128713 1.146e-23)
(0.0517941 0.165558 -1.85174e-22)
(0.0363947 0.189502 0)
(0.0196693 0.217786 0)
(0.003425 0.226749 -2.37491e-22)
(0.000197551 0.258262 3.60382e-22)
(0.00406813 0.2618 -3.53603e-22)
(0.0169796 0.298208 4.05781e-23)
(0.0420443 0.300974 -3.91332e-23)
(0.0562915 0.0701356 -2.83763e-22)
(0.0633629 0.112141 0)
(0.0582816 0.154946 -1.69376e-21)
(0.0408494 0.181692 4.08023e-21)
(0.0226821 0.209232 -2.78435e-21)
(0.00696416 0.220089 2.31028e-22)
(0.00436972 0.250348 -2.93399e-22)
(0.00897901 0.253441 -1.3096e-22)
(0.021951 0.286749 1.16134e-22)
(0.0414487 0.27522 2.269e-23)
(0.0701149 0.0700632 3.92552e-25)
(0.07545 0.11877 1.20055e-21)
(0.0649193 0.159665 -1.18895e-21)
(0.0448012 0.183741 2.39665e-21)
(0.0255653 0.206839 -1.79876e-21)
(0.0110766 0.216821 0)
(0.0086632 0.242507 2.94084e-22)
(0.0133395 0.243033 -1.90209e-23)
(0.0242661 0.267983 -6.63697e-23)
(0.0390633 0.24419 -5.73906e-23)
(0.0860399 0.0877918 -5.24049e-24)
(0.0867876 0.136642 0)
(0.0706237 0.171107 0)
(0.0479605 0.189669 0)
(0.0280043 0.20639 -1.86143e-21)
(0.0146166 0.213311 1.1803e-21)
(0.0119634 0.231944 -1.06053e-22)
(0.0159371 0.227709 5.33351e-23)
(0.0240102 0.241761 -2.0928e-23)
(0.035179 0.209068 -1.05751e-23)
(0.103413 0.112685 -4.16472e-22)
(0.0962558 0.155401 4.12393e-22)
(0.0744618 0.181051 1.3193e-21)
(0.0495822 0.192995 -1.31823e-21)
(0.0292466 0.202883 6.72272e-22)
(0.0166991 0.205409 0)
(0.0134219 0.215748 3.44784e-22)
(0.0160973 0.20551 -2.22305e-22)
(0.0212127 0.208846 6.64539e-23)
(0.0301633 0.171229 3.16964e-23)
(0.119685 0.13559 1.79758e-21)
(0.102805 0.167522 3.10945e-22)
(0.0761049 0.183332 3.58964e-22)
(0.0495537 0.188666 -1.51419e-21)
(0.029114 0.192199 0)
(0.0170672 0.189919 0)
(0.0128038 0.192059 0)
(0.0138498 0.176051 -1.9723e-22)
(0.0164903 0.170843 0)
(0.0245718 0.132274 0)
(0.132119 0.149725 0)
(0.105851 0.168567 -2.05565e-21)
(0.0755827 0.174586 1.40366e-21)
(0.0480807 0.174051 1.72838e-21)
(0.0277199 0.172217 -1.7372e-21)
(0.0157614 0.165528 -5.38752e-22)
(0.0102631 0.160695 6.61576e-22)
(0.00970506 0.140486 7.81692e-22)
(0.0107441 0.129976 -5.28049e-23)
(0.0189656 0.0938657 -2.3431e-24)
(0.139037 0.151039 0)
(0.105428 0.156937 6.5338e-22)
(0.0732349 0.154169 4.8543e-22)
(0.0454961 0.148994 0)
(0.0252958 0.143011 -3.35156e-22)
(0.013048 0.132897 1.15566e-21)
(0.00627817 0.123081 -6.01781e-22)
(0.00447009 0.101054 -4.89946e-23)
(0.00488648 0.0886815 1.06618e-23)
(0.0138383 0.0575053 3.77744e-24)
(0.14023 0.13845 -3.7413e-22)
(0.102093 0.133511 -9.28054e-22)
(0.0696137 0.12361 1.90062e-22)
(0.0421769 0.115238 -2.69997e-22)
(0.0221503 0.106369 -4.55456e-22)
(0.00937908 0.0941623 -5.45053e-22)
(0.00156591 0.0817114 1.20904e-22)
(-0.000982879 0.0604574 6.38629e-23)
(-0.000348097 0.0491736 -1.06967e-23)
(0.0095269 0.024329 -2.45444e-24)
(0.136645 0.113689 1.94311e-22)
(0.0966759 0.101024 -1.97324e-22)
(0.0653097 0.0858098 2.61625e-22)
(0.038491 0.0756244 2.69584e-22)
(0.0186394 0.0650581 -2.15332e-22)
(0.00530722 0.0522181 4.03836e-22)
(-0.0032273 0.0394883 -1.68164e-22)
(-0.00583587 0.0212844 -1.62802e-23)
(-0.00452677 0.0130839 0)
(0.00590436 -0.00501993 2.45259e-24)
(0.129759 0.0803111 -2.08543e-22)
(0.0901147 0.063089 2.11492e-22)
(0.0607779 0.0441727 2.79389e-22)
(0.0347754 0.0333277 2.83285e-22)
(0.0151039 0.0221365 2.19589e-22)
(0.00136166 0.0101069 -2.75371e-23)
(-0.00744006 -0.00090458 -7.93895e-23)
(-0.00949295 -0.0144763 -1.19946e-22)
(-0.00733515 -0.0186494 0)
(0.0035648 -0.0304595 3.24087e-24)
(0.120939 0.0422882 0)
(0.083308 0.0232699 1.06791e-21)
(0.0562721 0.00193579 -1.91188e-21)
(0.0313137 -0.00871808 -2.83699e-22)
(0.011856 -0.0195602 -4.94176e-22)
(-0.00189152 -0.0295749 -5.81838e-22)
(-0.0104625 -0.0374414 1.28304e-22)
(-0.0117299 -0.0456538 7.04624e-23)
(-0.00868488 -0.0457887 -4.38245e-23)
(0.00199137 -0.0524177 -3.23198e-24)
(0.111201 0.0030819 0)
(0.0767727 -0.0154716 9.86861e-22)
(0.052069 -0.0382508 5.57536e-22)
(0.0282886 -0.0481472 0)
(0.0092279 -0.0578188 1.37062e-21)
(-0.00408989 -0.0649764 -4.93879e-22)
(-0.0120902 -0.0689344 -3.15696e-22)
(-0.012581 -0.0719426 -4.9914e-22)
(-0.00885936 -0.068705 4.36813e-23)
(0.00102715 -0.0715482 -1.98201e-23)
(0.101381 -0.0345876 0)
(0.0707471 -0.0510249 -9.94995e-22)
(0.0483789 -0.0744957 0)
(0.0258726 -0.0833131 -2.04949e-21)
(0.00747979 -0.0911787 2.06018e-21)
(-0.00514557 -0.0951327 6.3609e-22)
(-0.0123822 -0.095125 -1.21828e-22)
(-0.0122618 -0.0937527 4.91537e-22)
(-0.00824527 -0.0881608 8.5102e-23)
(0.000517599 -0.0885501 3.58111e-23)
(0.0920488 -0.0688037 -4.55059e-21)
(0.0654223 -0.0822484 1.86708e-21)
(0.0452207 -0.105675 -1.30611e-22)
(0.0242285 -0.1134 2.06657e-21)
(0.00668908 -0.119015 0)
(-0.00508634 -0.119954 6.23501e-22)
(-0.0115692 -0.116487 -2.22088e-22)
(-0.0111158 -0.111932 -7.01037e-22)
(-0.00718936 -0.105049 -1.79753e-23)
(0.00029207 -0.104051 1.79714e-23)
(0.083581 -0.0983534 1.30145e-21)
(0.0609774 -0.108921 -3.47547e-21)
(0.042596 -0.131351 -1.95334e-21)
(0.0233749 -0.138343 1.95231e-21)
(0.00680669 -0.141462 8.7638e-22)
(-0.00413855 -0.140032 0)
(-0.00998418 -0.133951 8.93619e-22)
(-0.00950572 -0.127478 -4.85134e-22)
(-0.00596211 -0.120191 -2.11701e-22)
(0.000216996 -0.118553 -3.31737e-23)
(0.0762342 -0.122701 2.92594e-22)
(0.0574676 -0.131524 0)
(0.0405334 -0.151662 0)
(0.0232036 -0.158659 0)
(0.00767225 -0.159213 6.72019e-22)
(-0.00270931 -0.156351 -1.54676e-21)
(-0.00796958 -0.148599 -8.87158e-22)
(-0.00773276 -0.14131 9.84506e-22)
(-0.00474498 -0.134239 -4.17991e-23)
(0.000210507 -0.132426 7.42483e-23)
(0.0699499 -0.141818 1.653e-23)
(0.054812 -0.150982 -3.02393e-21)
(0.0390553 -0.167189 2.99588e-21)
(0.023562 -0.175199 -3.43148e-21)
(0.0090751 -0.173238 4.20031e-21)
(-0.000887219 -0.169997 0)
(-0.00580344 -0.161452 4.72393e-22)
(-0.00600216 -0.154149 -7.94118e-25)
(-0.00363525 -0.14765 1.39694e-22)
(0.000232722 -0.145928 3.9358e-23)
(0.0638519 -0.155862 1.81966e-22)
(0.0524034 -0.168421 0)
(0.0379986 -0.178869 3.55982e-21)
(0.024233 -0.188917 -6.40484e-21)
(0.0109237 -0.184648 2.39838e-21)
(0.00125111 -0.181923 3.16826e-22)
(-0.00367144 -0.173221 -4.71317e-22)
(-0.00439024 -0.166487 -7.46142e-23)
(-0.0026517 -0.160721 -3.06919e-22)
(0.000274803 -0.159233 -8.34636e-23)
(0.0584865 -0.164703 1.02768e-21)
(0.049568 -0.184963 -1.00053e-21)
(0.0369911 -0.187984 -3.7709e-22)
(0.0245314 -0.200749 0)
(0.0128346 -0.194414 0)
(0.00335783 -0.192822 -3.25937e-22)
(-0.00155592 -0.184403 -7.67019e-22)
(-0.0029053 -0.178617 7.52852e-22)
(-0.00175541 -0.173622 4.76208e-23)
(0.000324431 -0.172458 -4.66017e-23)
(0.0623648 -0.172328 0)
(0.0471721 -0.221759 0)
(0.0360166 -0.20637 0)
(0.0236075 -0.225997 0)
(0.0150494 -0.21586 0)
(0.00555848 -0.217799 0)
(0.00155207 -0.210605 0)
(-0.000627563 -0.207702 0)
(-0.000128219 -0.204412 0)
(0.000309448 -0.203868 0)
(0.0439943 -0.233735 0)
(0.0352286 -0.268445 0)
(0.0301501 -0.253238 0)
(0.0212782 -0.269053 0)
(0.0170072 -0.260353 0)
(0.00775582 -0.26554 0)
(0.00612875 -0.259429 0)
(0.00197849 -0.26015 0)
(0.00185897 -0.257177 0)
(9.12588e-05 -0.257836 0)
(0.0403374 -0.283238 0)
(0.0309179 -0.316148 0)
(0.0272016 -0.300501 0)
(0.0194871 -0.316611 0)
(0.0155216 -0.309086 0)
(0.00858786 -0.315787 0)
(0.0069383 -0.310835 0)
(0.00278831 -0.313446 0)
(0.00250524 -0.310217 0)
(-0.000150603 -0.311908 0)
(0.0349905 -0.338087 0)
(0.02717 -0.369707 0)
(0.0237317 -0.352813 0)
(0.0168991 -0.371464 0)
(0.0138976 -0.362096 0)
(0.00838854 -0.371757 0)
(0.00674729 -0.365641 0)
(0.00331142 -0.370089 0)
(0.00237469 -0.365872 0)
(-5.24818e-05 -0.368337 0)
(0.0298142 -0.401384 0)
(0.0229487 -0.433428 0)
(0.0198261 -0.4151 0)
(0.0144848 -0.435219 0)
(0.0117296 -0.424159 0)
(0.00771451 -0.436005 0)
(0.00627991 -0.428117 0)
(0.00356363 -0.434481 0)
(0.0024277 -0.428052 0)
(0.000127929 -0.431992 0)
(0.0251691 -0.476806 0)
(0.0188198 -0.509372 0)
(0.0163792 -0.489902 0)
(0.0119171 -0.511817 0)
(0.010116 -0.498789 0)
(0.00691079 -0.512808 0)
(0.00591514 -0.503269 0)
(0.00350406 -0.511175 0)
(0.00229717 -0.503178 0)
(0.000135932 -0.509042 0)
(0.019798 -0.572166 0)
(0.014915 -0.604018 0)
(0.0130263 -0.585104 0)
(0.00952835 -0.607839 0)
(0.00816985 -0.594374 0)
(0.00569301 -0.609982 0)
(0.00484638 -0.599383 0)
(0.00279642 -0.608881 0)
(0.00177334 -0.599895 0)
(3.68042e-05 -0.607564 0)
(0.0150608 -0.691632 0)
(0.0108291 -0.718819 0)
(0.00928575 -0.704123 0)
(0.00646662 -0.724309 0)
(0.00563238 -0.713051 0)
(0.00365514 -0.727715 0)
(0.00300426 -0.718003 0)
(0.00128929 -0.727531 0)
(0.000707976 -0.719148 0)
(-0.000226419 -0.727572 0)
(0.00787136 -0.813603 0)
(0.00533286 -0.829452 0)
(0.00459493 -0.823865 0)
(0.00319669 -0.836883 0)
(0.00276783 -0.831501 0)
(0.00150492 -0.840773 0)
(0.000940765 -0.834741 0)
(-0.00021275 -0.840794 0)
(-0.000312613 -0.835159 0)
(-0.00036887 -0.841203 0)
(0.00143263 -0.888415 0)
(0.00101431 -0.898384 0)
(0.000980543 -0.899293 0)
(0.00086941 -0.905425 0)
(0.000678313 -0.90428 0)
(0.000310094 -0.908026 0)
(5.96389e-06 -0.905215 0)
(-0.000349913 -0.907238 0)
(-0.000343091 -0.904264 0)
(-0.0001695 -0.906906 0)
(0.0547462 -0.195625 1.52351e-21)
(0.0438096 -0.252023 -1.49762e-21)
(0.0416479 -0.301446 3.20033e-22)
(0.0360899 -0.357728 0)
(0.0317116 -0.420493 0)
(0.0269072 -0.49609 5.98115e-22)
(0.0215952 -0.590291 -2.91471e-21)
(0.01604 -0.703916 2.90652e-21)
(0.00978326 -0.818979 9.28773e-22)
(0.00308719 -0.88533 -9.21784e-22)
(0.0521417 -0.202847 -1.97011e-21)
(0.0441484 -0.257905 0)
(0.0421837 -0.306992 2.53892e-21)
(0.0366392 -0.363482 -6.26276e-21)
(0.0325997 -0.425944 4.44483e-21)
(0.0276905 -0.501685 -5.39324e-22)
(0.0224052 -0.595408 1.39542e-21)
(0.0165201 -0.707426 3.16013e-21)
(0.0106571 -0.819448 1.0148e-21)
(0.00384385 -0.885245 1.02419e-21)
(0.0502087 -0.209704 2.78699e-21)
(0.0448669 -0.264191 -2.62232e-21)
(0.0429568 -0.312466 2.59744e-21)
(0.0374771 -0.36854 -3.92096e-21)
(0.0337096 -0.430474 2.87459e-21)
(0.0286219 -0.506123 0)
(0.0232868 -0.599232 -1.39891e-21)
(0.0171283 -0.709836 1.55232e-22)
(0.0111991 -0.818862 -1.71251e-21)
(0.00420114 -0.885506 -1.91686e-21)
(0.0488388 -0.216359 -4.84687e-22)
(0.0458454 -0.270564 0)
(0.0440362 -0.318018 0)
(0.0386605 -0.373597 0)
(0.0350904 -0.434978 3.82943e-21)
(0.029757 -0.510358 -2.58299e-21)
(0.0243046 -0.602755 -4.81418e-23)
(0.0178712 -0.711849 -1.95552e-21)
(0.011511 -0.818288 -1.01685e-21)
(0.00425405 -0.884687 -1.11839e-21)
(0.0480127 -0.222648 1.98204e-22)
(0.0470439 -0.276272 -1.79693e-21)
(0.0454054 -0.322905 -1.88121e-21)
(0.0401482 -0.378152 1.88005e-21)
(0.036718 -0.439091 -1.22948e-21)
(0.0310918 -0.514224 0)
(0.0254796 -0.605944 -1.69737e-21)
(0.0187423 -0.71358 4.02421e-21)
(0.0118133 -0.81779 -2.09425e-21)
(0.00422456 -0.88284 2.16073e-21)
(0.0477749 -0.22849 -5.18598e-21)
(0.048526 -0.281094 3.45731e-22)
(0.0470895 -0.326729 -3.73848e-22)
(0.0419097 -0.381716 2.03237e-21)
(0.0385595 -0.442287 0)
(0.0326014 -0.517253 0)
(0.0267978 -0.608401 0)
(0.0197351 -0.714776 2.22572e-21)
(0.0122511 -0.817086 0)
(0.00426202 -0.880445 0)
(0.0481622 -0.2338 0)
(0.0503816 -0.285054 2.59073e-21)
(0.0491558 -0.329476 -1.77779e-21)
(0.0439614 -0.38416 -2.69544e-21)
(0.0406176 -0.44435 2.70951e-21)
(0.0342822 -0.519169 1.89354e-21)
(0.0282488 -0.609841 -1.85094e-21)
(0.020839 -0.715195 -8.01193e-21)
(0.0128471 -0.815966 5.6739e-22)
(0.00439673 -0.877865 -2.10584e-21)
(0.0492037 -0.238452 0)
(0.0526862 -0.288142 -8.15351e-22)
(0.0516657 -0.33118 -5.48332e-22)
(0.0463384 -0.38551 0)
(0.0429222 -0.445265 9.09202e-22)
(0.0361592 -0.519911 -2.74083e-21)
(0.0298471 -0.610162 3.28134e-21)
(0.0220605 -0.714696 1.22504e-21)
(0.0135856 -0.814296 -1.40798e-21)
(0.00461976 -0.875178 2.77577e-21)
(0.0509415 -0.242302 6.6189e-22)
(0.0555038 -0.290289 1.00911e-21)
(0.0546578 -0.331808 -1.77028e-22)
(0.0490686 -0.385777 3.67306e-22)
(0.0455045 -0.445061 8.34031e-22)
(0.0382629 -0.519517 1.51253e-21)
(0.0316162 -0.609404 -6.11108e-22)
(0.0234022 -0.713321 -6.88363e-22)
(0.0144211 -0.812104 1.41264e-21)
(0.004889 -0.872364 7.98346e-22)
(0.0534379 -0.245211 -2.0479e-22)
(0.0588971 -0.29142 2.06522e-22)
(0.0581553 -0.331287 -2.93635e-22)
(0.0521695 -0.384926 -3.66862e-22)
(0.0483887 -0.443702 5.04463e-22)
(0.0406214 -0.51798 -1.03796e-21)
(0.0335859 -0.607562 9.46242e-22)
(0.0248936 -0.71105 3.51303e-22)
(0.0153683 -0.809343 0)
(0.00521446 -0.869309 -8.00094e-22)
(0.0567705 -0.247053 2.1255e-22)
(0.0629261 -0.291499 -2.14469e-22)
(0.0621746 -0.329567 -3.37693e-22)
(0.0556578 -0.382945 -4.22465e-22)
(0.0515894 -0.441173 -5.41238e-22)
(0.0432442 -0.515345 -6.13925e-23)
(0.0357664 -0.604705 3.4286e-22)
(0.026528 -0.708017 1.14868e-21)
(0.0163943 -0.806128 0)
(0.00556094 -0.866031 -9.10437e-22)
(0.0610262 -0.247711 0)
(0.0676429 -0.290525 -1.22022e-21)
(0.0667225 -0.326671 2.29088e-21)
(0.0595471 -0.379824 4.23213e-22)
(0.0551259 -0.437437 1.10969e-21)
(0.0461528 -0.511523 1.90583e-21)
(0.0381878 -0.600724 -7.00908e-22)
(0.028352 -0.704067 -7.86544e-22)
(0.0175676 -0.802312 1.83394e-21)
(0.00598393 -0.862429 9.08275e-22)
(0.0662882 -0.247098 0)
(0.0730781 -0.28856 -1.13309e-21)
(0.0718136 -0.322682 -7.25447e-22)
(0.0638586 -0.375565 0)
(0.0590095 -0.432648 -3.59198e-21)
(0.04934 -0.506637 1.19857e-21)
(0.0408309 -0.595811 1.55897e-21)
(0.030318 -0.699446 5.20798e-21)
(0.0188099 -0.798122 -1.82801e-21)
(0.00640911 -0.858633 4.09931e-21)
(0.0726256 -0.245158 0)
(0.0792439 -0.285676 1.14285e-21)
(0.0774615 -0.317774 0)
(0.0685919 -0.370152 4.43297e-21)
(0.0632663 -0.426761 -4.45565e-21)
(0.0528673 -0.500472 -3.06376e-21)
(0.0437604 -0.589654 -1.06393e-22)
(0.0325294 -0.693716 -5.42921e-21)
(0.0202532 -0.793203 -8.99354e-22)
(0.00695127 -0.854455 -5.09837e-21)
(0.080072 -0.241901 5.80464e-21)
(0.0861225 -0.282024 -2.19198e-21)
(0.0837145 -0.312001 8.95573e-22)
(0.0737885 -0.363625 -3.82286e-21)
(0.0678958 -0.419914 0)
(0.0567062 -0.493373 -3.26016e-21)
(0.0468948 -0.582823 -4.12467e-22)
(0.034837 -0.687594 7.45933e-21)
(0.0216985 -0.788089 1.07773e-21)
(0.00743594 -0.850164 -1.0816e-21)
(0.0885372 -0.237303 -2.21119e-21)
(0.0937526 -0.277389 5.17324e-21)
(0.0906307 -0.305232 4.05372e-21)
(0.079481 -0.35594 -4.05096e-21)
(0.0729328 -0.411874 -2.84378e-21)
(0.0609422 -0.48492 0)
(0.0503929 -0.574502 -7.69689e-21)
(0.0375148 -0.680014 3.84584e-21)
(0.0234564 -0.78198 4.27066e-21)
(0.0081215 -0.845348 4.77957e-21)
(0.0980075 -0.23152 -6.13896e-22)
(0.102092 -0.27206 0)
(0.0981324 -0.297994 0)
(0.0855943 -0.34777 0)
(0.0782797 -0.40347 -3.50237e-21)
(0.0654088 -0.476305 6.33464e-21)
(0.0539881 -0.566306 7.91137e-21)
(0.0401411 -0.672811 -1.27461e-20)
(0.0250653 -0.776122 2.38515e-21)
(0.00861526 -0.840592 -7.09654e-21)
(0.108383 -0.22394 1.78966e-22)
(0.11128 -0.264944 6.73815e-21)
(0.106333 -0.289536 -6.67291e-21)
(0.0923529 -0.338022 1.12944e-20)
(0.0841857 -0.393236 -1.43539e-20)
(0.0704792 -0.465455 0)
(0.0582141 -0.555494 -4.20905e-21)
(0.0434427 -0.663063 -2.4732e-22)
(0.0272466 -0.768633 -5.03068e-21)
(0.00950825 -0.835 -5.22064e-21)
(0.119267 -0.217256 -5.67005e-22)
(0.120705 -0.25922 0)
(0.114664 -0.282554 -1.06041e-20)
(0.0991186 -0.329868 2.13424e-20)
(0.0900136 -0.384965 -8.56476e-21)
(0.0753548 -0.456972 -1.93035e-21)
(0.0620898 -0.547395 4.20017e-21)
(0.0462356 -0.655797 -3.34972e-22)
(0.0289121 -0.762472 7.26128e-21)
(0.00990357 -0.829874 7.72189e-21)
(0.131955 -0.202529 -3.59379e-21)
(0.132462 -0.246791 3.50683e-21)
(0.124839 -0.270756 1.04531e-21)
(0.107697 -0.31634 0)
(0.0973417 -0.371056 0)
(0.0817657 -0.442302 1.86157e-21)
(0.067501 -0.532888 9.06723e-21)
(0.0505384 -0.643057 -8.79349e-21)
(0.0317753 -0.753242 -2.53403e-21)
(0.0111737 -0.823249 2.47699e-21)
(0.161721 -0.210217 0)
(0.161772 -0.250223 0)
(0.146567 -0.269336 0)
(0.122986 -0.312193 0)
(0.110482 -0.365323 0)
(0.0926128 -0.434262 0)
(0.0760513 -0.522859 0)
(0.0566952 -0.630729 0)
(0.0353696 -0.739531 0)
(0.0113419 -0.810345 0)
(0.202397 -0.193278 0)
(0.209248 -0.234786 0)
(0.178791 -0.25094 0)
(0.152448 -0.298 0)
(0.139001 -0.353104 0)
(0.116122 -0.421735 0)
(0.0965268 -0.508662 0)
(0.0726721 -0.613363 0)
(0.0462058 -0.716752 0)
(0.0171944 -0.781076 0)
(0.247038 -0.173214 0)
(0.253696 -0.204279 0)
(0.208145 -0.218874 0)
(0.189974 -0.27228 0)
(0.168938 -0.328728 0)
(0.142868 -0.393232 0)
(0.118725 -0.478729 0)
(0.0892604 -0.580155 0)
(0.0557703 -0.681376 0)
(0.0175088 -0.747783 0)
(0.290177 -0.154115 0)
(0.296544 -0.17324 0)
(0.246523 -0.19434 0)
(0.238091 -0.252531 0)
(0.204757 -0.309543 0)
(0.180813 -0.371525 0)
(0.150368 -0.456182 0)
(0.114824 -0.552188 0)
(0.0733102 -0.644657 0)
(0.0272235 -0.701044 0)
(0.337057 -0.127382 0)
(0.344247 -0.139587 0)
(0.296294 -0.166023 0)
(0.292054 -0.220675 0)
(0.247707 -0.274633 0)
(0.224714 -0.334684 0)
(0.185244 -0.413754 0)
(0.140288 -0.503839 0)
(0.0879953 -0.591232 0)
(0.0271017 -0.650084 0)
(0.403391 -0.108331 0)
(0.412993 -0.121402 0)
(0.367872 -0.152798 0)
(0.362555 -0.202598 0)
(0.31214 -0.253763 0)
(0.28488 -0.311643 0)
(0.234839 -0.379791 0)
(0.179005 -0.46107 0)
(0.1146 -0.535619 0)
(0.043376 -0.578409 0)
(0.495673 -0.0775807 0)
(0.501768 -0.09362 0)
(0.455795 -0.121407 0)
(0.443495 -0.163188 0)
(0.386688 -0.20618 0)
(0.347349 -0.256835 0)
(0.284146 -0.311538 0)
(0.213757 -0.384282 0)
(0.132396 -0.451584 0)
(0.0378509 -0.499615 0)
(0.617274 -0.066136 0)
(0.615218 -0.0833787 0)
(0.570557 -0.107043 0)
(0.546469 -0.140776 0)
(0.485108 -0.174136 0)
(0.432311 -0.215972 0)
(0.356202 -0.258386 0)
(0.268952 -0.318681 0)
(0.170567 -0.36815 0)
(0.0706458 -0.391803 0)
(0.726816 -0.0295916 0)
(0.712181 -0.0408019 0)
(0.663773 -0.0553623 0)
(0.626573 -0.0756509 0)
(0.555735 -0.0953601 0)
(0.489077 -0.121161 0)
(0.394129 -0.145965 0)
(0.287864 -0.1861 0)
(0.163172 -0.225219 0)
(0.0227458 -0.275421 0)
(0.90571 -0.0185955 0)
(0.885557 -0.0233468 0)
(0.844638 -0.0291113 0)
(0.802097 -0.0374889 0)
(0.73642 -0.0459886 0)
(0.664882 -0.0579953 0)
(0.565934 -0.0709316 0)
(0.447141 -0.0924672 0)
(0.299706 -0.121438 0)
(0.178846 -0.17445 0)
(0.194605 -0.16818 1.00245e-21)
(0.24395 -0.152818 -9.90434e-22)
(0.290614 -0.137507 6.52144e-22)
(0.333651 -0.121198 0)
(0.382096 -0.0984897 0)
(0.447949 -0.0813117 1.87617e-21)
(0.538338 -0.0541378 -1.02491e-20)
(0.649811 -0.0462079 1.0216e-20)
(0.753295 -0.0170719 3.33106e-21)
(0.922015 -0.0147214 -3.33927e-21)
(0.204719 -0.149653 1.46742e-21)
(0.254123 -0.134761 0)
(0.300302 -0.122026 5.487e-21)
(0.343985 -0.106874 -1.50175e-20)
(0.393892 -0.0857397 1.14808e-20)
(0.460818 -0.0693844 -1.70698e-21)
(0.550776 -0.0439227 3.97409e-21)
(0.659619 -0.0375002 9.93312e-21)
(0.761175 -0.0115974 3.16322e-21)
(0.926778 -0.0130289 3.02777e-21)
(0.21197 -0.127902 -2.18028e-21)
(0.261135 -0.114201 -3.07694e-21)
(0.306082 -0.104553 3.04777e-21)
(0.349998 -0.0908153 -8.87983e-21)
(0.401051 -0.0714957 6.23771e-21)
(0.469076 -0.0562649 0)
(0.558569 -0.0329668 -3.98393e-21)
(0.665128 -0.028532 -2.63831e-23)
(0.765798 -0.00617839 -5.46413e-21)
(0.929296 -0.011399 -5.93597e-21)
(0.218353 -0.103639 3.25887e-22)
(0.268473 -0.0913573 0)
(0.313063 -0.0848347 0)
(0.357126 -0.0726589 0)
(0.408913 -0.0554661 8.27186e-21)
(0.477284 -0.0418061 -5.76066e-21)
(0.565788 -0.021187 -4.46187e-22)
(0.669619 -0.019303 -5.22927e-21)
(0.769298 -0.000874291 -2.83807e-21)
(0.930963 -0.00984519 -3.01845e-21)
(0.223144 -0.0776198 1.92794e-21)
(0.275007 -0.0665241 4.05151e-22)
(0.32006 -0.0629347 -2.72463e-21)
(0.364767 -0.0523911 2.72303e-21)
(0.417429 -0.0376281 -2.47464e-21)
(0.485873 -0.0260103 0)
(0.57305 -0.00859057 -3.96527e-21)
(0.673935 -0.0097719 9.93882e-21)
(0.7723 0.00437091 -5.1178e-21)
(0.932246 -0.0083442 5.91399e-21)
(0.226181 -0.0500241 2.1518e-21)
(0.280073 -0.0398379 -1.68331e-21)
(0.325673 -0.0389416 -1.37851e-21)
(0.371309 -0.0301677 2.63276e-21)
(0.425031 -0.0181714 0)
(0.493554 -0.0090575 0)
(0.579354 0.00467685 0)
(0.677422 1.36407e-07 4.78505e-21)
(0.774453 0.00956652 0)
(0.932985 -0.00688515 0)
(0.227866 -0.0208795 0)
(0.28386 -0.0113917 1.56147e-21)
(0.329575 -0.012928 -1.24775e-21)
(0.376158 -0.00617117 -4.04554e-21)
(0.430797 0.00268342 4.06668e-21)
(0.499296 0.00882996 3.53208e-21)
(0.583684 0.0184275 -3.15862e-21)
(0.679185 0.00988469 -1.65567e-20)
(0.77514 0.0146554 1.15557e-21)
(0.932816 -0.00548213 -4.44138e-21)
(0.228615 0.00977369 0)
(0.286504 0.0186288 -3.17442e-22)
(0.331809 0.014909 -5.10777e-22)
(0.379304 0.0193427 0)
(0.434517 0.024715 1.57014e-21)
(0.502744 0.0274495 -4.45796e-21)
(0.585572 0.0325006 6.17204e-21)
(0.678718 0.0197536 2.61819e-21)
(0.773929 0.0195629 -2.7586e-21)
(0.931458 -0.00415153 5.89187e-21)
(0.228693 0.0418346 -3.33333e-22)
(0.287902 0.0498851 7.26985e-22)
(0.33235 0.0441821 5.61872e-23)
(0.380724 0.0459961 4.62339e-22)
(0.43618 0.0476369 1.23421e-21)
(0.503876 0.0465823 2.47966e-21)
(0.584988 0.0467466 -1.04996e-21)
(0.675945 0.0294972 -1.26541e-21)
(0.77073 0.0242261 2.76772e-21)
(0.928858 -0.0029113 1.50284e-21)
(0.228161 0.0750729 -5.87573e-23)
(0.287887 0.0818844 5.91833e-23)
(0.331068 0.0743486 -2.79849e-22)
(0.380293 0.0732992 -4.61775e-22)
(0.43572 0.0710753 7.62135e-22)
(0.502699 0.0659522 -1.61749e-21)
(0.582037 0.0609934 1.63715e-21)
(0.670954 0.0390151 6.74877e-22)
(0.76563 0.028605 0)
(0.925109 -0.00175776 -1.50609e-21)
(0.226871 0.10908 9.76778e-23)
(0.286365 0.113989 -9.8339e-23)
(0.327861 0.104772 -3.63528e-22)
(0.37793 0.10069 -5.45067e-22)
(0.433085 0.0945873 -8.10264e-22)
(0.499215 0.0852221 -1.30621e-22)
(0.576849 0.0750251 5.41624e-22)
(0.663896 0.0481833 1.98263e-21)
(0.758829 0.0326466 0)
(0.920399 -0.000703459 -1.57184e-21)
(0.224723 0.143247 0)
(0.283397 0.145457 -1.19481e-21)
(0.322817 0.134777 2.40949e-21)
(0.373701 0.127573 5.46028e-22)
(0.42828 0.117712 1.60097e-21)
(0.493465 0.104028 2.97445e-21)
(0.569505 0.0886105 -1.15328e-21)
(0.654827 0.0568871 -1.36395e-21)
(0.750379 0.0363172 3.0931e-21)
(0.914853 0.000269961 1.56814e-21)
(0.221797 0.176765 0)
(0.279084 0.175527 -1.17044e-21)
(0.316204 0.163689 -8.44305e-22)
(0.367766 0.153383 0)
(0.42144 0.139984 -5.35523e-21)
(0.485624 0.121992 1.75021e-21)
(0.560141 0.101504 2.45433e-21)
(0.643924 0.0649802 8.68339e-21)
(0.740497 0.0395311 -3.0831e-21)
(0.908605 0.00112104 6.62258e-21)
(0.218162 0.208757 0)
(0.273446 0.203534 1.1805e-21)
(0.308249 0.190892 0)
(0.360221 0.177623 6.43029e-21)
(0.412701 0.160974 -6.46315e-21)
(0.475809 0.138789 -4.8816e-21)
(0.548782 0.113519 -2.39564e-22)
(0.631209 0.0723944 -9.0551e-21)
(0.729086 0.0423132 -1.50902e-21)
(0.901659 0.00190308 -8.22699e-21)
(0.213876 0.238417 8.23803e-21)
(0.266575 0.228983 -3.03284e-21)
(0.299244 0.215858 1.53857e-21)
(0.351271 0.199864 -5.49272e-21)
(0.402379 0.18027 0)
(0.464333 0.154094 -5.20498e-21)
(0.53572 0.124394 -7.60011e-22)
(0.617137 0.078925 1.22139e-20)
(0.716584 0.044541 1.69813e-21)
(0.894162 0.00253594 -1.6969e-21)
(0.208906 0.265133 -2.51903e-21)
(0.258494 0.251592 8.07863e-21)
(0.289322 0.238218 6.11447e-21)
(0.340905 0.219831 -6.11039e-21)
(0.39053 0.197615 -4.46488e-21)
(0.451193 0.167782 0)
(0.520891 0.134093 -1.23779e-20)
(0.601528 0.0846937 6.28132e-21)
(0.702457 0.0464433 6.79557e-21)
(0.886102 0.00316419 7.16214e-21)
(0.203593 0.28854 -1.7154e-21)
(0.24968 0.271256 0)
(0.279082 0.25771 0)
(0.329788 0.237259 0)
(0.377931 0.212652 -5.6874e-21)
(0.437207 0.179483 1.0133e-20)
(0.505168 0.142173 1.26753e-20)
(0.585398 0.0892541 -2.03899e-20)
(0.687901 0.0476559 3.60835e-21)
(0.877799 0.00355535 -1.06543e-20)
(0.197463 0.308622 -1.91162e-21)
(0.239585 0.288169 1.1523e-20)
(0.267901 0.274418 -1.14122e-20)
(0.317094 0.252359 1.82765e-20)
(0.363752 0.225692 -2.32573e-20)
(0.4215 0.189701 0)
(0.487648 0.149288 -6.72897e-21)
(0.56753 0.0934434 -2.97852e-22)
(0.671323 0.0488938 -7.54795e-21)
(0.869124 0.0040529 -7.48645e-21)
(0.192734 0.32528 -2.00957e-21)
(0.230739 0.302225 0)
(0.258496 0.287947 -1.80648e-20)
(0.306048 0.264403 3.56746e-20)
(0.351197 0.235641 -1.42263e-20)
(0.407236 0.197026 -3.15769e-21)
(0.471339 0.153754 6.71452e-21)
(0.550697 0.0956171 -2.92633e-22)
(0.655988 0.0489748 1.1118e-20)
(0.860469 0.00411244 1.11153e-20)
(0.18397 0.340762 -1.05753e-20)
(0.217516 0.315525 1.02905e-20)
(0.244729 0.300613 1.85854e-21)
(0.290151 0.276303 0)
(0.3342 0.246001 0)
(0.388811 0.20538 3.06911e-21)
(0.451214 0.159738 1.43621e-20)
(0.530123 0.099411 -1.39826e-20)
(0.637232 0.0501765 -3.67134e-21)
(0.851462 0.0046151 3.51232e-21)
(0.19871 0.343561 0)
(0.219224 0.333503 0)
(0.245323 0.309803 0)
(0.284142 0.282468 0)
(0.320428 0.247155 0)
(0.366902 0.203006 0)
(0.420511 0.153984 0)
(0.494394 0.0938716 0)
(0.604306 0.0459556 0)
(0.8305 0.00384998 0)
(0.185149 0.342069 0)
(0.193395 0.330825 0)
(0.22258 0.298518 0)
(0.250629 0.269687 0)
(0.280978 0.230004 0)
(0.320084 0.184943 0)
(0.36786 0.136044 0)
(0.442066 0.0807748 0)
(0.566318 0.0375852 0)
(0.815863 0.00316186 0)
(0.160798 0.335245 0)
(0.160156 0.317761 0)
(0.192249 0.282077 0)
(0.206709 0.252045 0)
(0.236733 0.20974 0)
(0.268993 0.16638 0)
(0.31446 0.119146 0)
(0.389201 0.0697167 0)
(0.522246 0.0318509 0)
(0.787309 0.00276814 0)
(0.135313 0.327326 0)
(0.132288 0.304701 0)
(0.162338 0.269182 0)
(0.165157 0.237493 0)
(0.197709 0.194819 0)
(0.223315 0.154212 0)
(0.270946 0.108655 0)
(0.351239 0.0636837 0)
(0.499436 0.0284711 0)
(0.782599 0.00352789 0)
(0.108702 0.32136 0)
(0.105058 0.295781 0)
(0.128478 0.262369 0)
(0.124445 0.229739 0)
(0.157156 0.189172 0)
(0.175886 0.151179 0)
(0.223599 0.108331 0)
(0.304291 0.0671279 0)
(0.457705 0.0320039 0)
(0.749608 0.00495947 0)
(0.0858845 0.31772 0)
(0.0818398 0.29376 0)
(0.0987385 0.262818 0)
(0.093515 0.232331 0)
(0.124064 0.195283 0)
(0.140169 0.160381 0)
(0.190891 0.120938 0)
(0.276061 0.0817673 0)
(0.439947 0.0424567 0)
(0.742414 0.00974425 0)
(0.0542257 0.323575 0)
(0.0504188 0.306455 0)
(0.0601663 0.275576 0)
(0.05588 0.253706 0)
(0.0791763 0.220427 0)
(0.0936931 0.193258 0)
(0.142129 0.159225 0)
(0.22257 0.12249 0)
(0.379935 0.0753107 0)
(0.680258 0.0191849 0)
(0.0445585 0.374721 0)
(0.0431133 0.371279 0)
(0.0493834 0.333579 0)
(0.0507199 0.322682 0)
(0.0689195 0.287776 0)
(0.0858358 0.270466 0)
(0.131953 0.237204 0)
(0.206926 0.200552 0)
(0.354932 0.137722 0)
(0.642025 0.0414654 0)
(0.00340546 0.54152 0)
(-0.000611568 0.543819 0)
(-6.74961e-05 0.51007 0)
(0.000710904 0.509698 0)
(0.00961904 0.479242 0)
(0.0239644 0.470036 0)
(0.0575482 0.430235 0)
(0.116252 0.384879 0)
(0.23347 0.282859 0)
(0.477961 0.0838023 0)
(0.0141777 0.784601 0)
(0.0173166 0.784573 0)
(0.0218954 0.769759 0)
(0.0285471 0.768456 0)
(0.0382708 0.749133 0)
(0.0532372 0.734697 0)
(0.0768538 0.690749 0)
(0.114806 0.624593 0)
(0.181917 0.472289 0)
(0.325722 0.157849 0)
(0.187458 0.373577 1.22877e-20)
(0.168408 0.370184 -1.19846e-20)
(0.144173 0.361539 2.24999e-21)
(0.121004 0.35125 0)
(0.0967577 0.343486 0)
(0.076434 0.337026 3.07636e-21)
(0.0488927 0.345596 -1.31968e-20)
(0.0394922 0.402361 1.30463e-20)
(0.00341184 0.567022 3.41935e-21)
(0.0129619 0.794682 -3.4705e-21)
(0.183373 0.376089 -9.50525e-21)
(0.162058 0.372419 0)
(0.137797 0.36479 1.54621e-20)
(0.115454 0.35544 -3.70808e-20)
(0.0919915 0.34842 2.46872e-20)
(0.0726889 0.342608 -2.84575e-21)
(0.0467535 0.352989 5.67733e-21)
(0.0374346 0.412839 1.1876e-20)
(0.00337579 0.576902 2.90839e-21)
(0.0124032 0.798108 2.94884e-21)
(0.17797 0.376393 1.16946e-20)
(0.156106 0.371027 -1.43971e-20)
(0.132258 0.364324 1.42682e-20)
(0.110672 0.356441 -1.93159e-20)
(0.0878666 0.350767 1.40682e-20)
(0.0694692 0.346725 0)
(0.0449165 0.359152 -5.69104e-21)
(0.035619 0.422381 -2.12505e-22)
(0.00331181 0.586011 -5.89458e-21)
(0.0117534 0.80117 -6.02302e-21)
(0.171887 0.379893 -2.21127e-21)
(0.150316 0.373886 0)
(0.127219 0.36707 0)
(0.106407 0.359546 0)
(0.084255 0.354361 1.49387e-20)
(0.0666799 0.351522 -1.0104e-20)
(0.0433167 0.365475 -2.21682e-22)
(0.0340258 0.431556 -5.75263e-21)
(0.00327869 0.594536 -2.84569e-21)
(0.0110641 0.8044 -2.80271e-21)
(0.165948 0.384145 3.49417e-21)
(0.144807 0.379013 -7.28448e-21)
(0.122429 0.37203 -7.9603e-21)
(0.102363 0.364432 7.95773e-21)
(0.080906 0.359201 -4.76994e-21)
(0.0641343 0.357018 0)
(0.0418447 0.372038 -5.32685e-21)
(0.0325963 0.440391 1.09897e-20)
(0.003319 0.602514 -5.43369e-21)
(0.0103912 0.807705 5.71528e-21)
(0.160244 0.387925 -1.60847e-20)
(0.139783 0.384089 4.98527e-22)
(0.118028 0.377182 -1.20338e-21)
(0.0986037 0.369656 7.59865e-21)
(0.0778085 0.364332 0)
(0.0617711 0.362625 0)
(0.0404507 0.378445 0)
(0.0313033 0.448697 5.12877e-21)
(0.00343995 0.60985 0)
(0.00976003 0.810835 0)
(0.154904 0.39129 0)
(0.135241 0.388772 8.69944e-21)
(0.114059 0.382059 -6.07829e-21)
(0.0951881 0.374727 -8.14799e-21)
(0.0749914 0.369376 8.19158e-21)
(0.0595937 0.368117 4.70778e-21)
(0.0391569 0.384456 -4.5332e-21)
(0.0301497 0.456326 -1.75146e-20)
(0.00361684 0.616455 1.24894e-21)
(0.00917109 0.813632 -3.79054e-21)
(0.150053 0.394602 0)
(0.131147 0.393375 -2.63209e-21)
(0.110513 0.386854 -1.56133e-21)
(0.0921268 0.379691 0)
(0.0724834 0.374331 2.23857e-21)
(0.0575921 0.373461 -6.42828e-21)
(0.0379424 0.390129 7.06613e-21)
(0.0291215 0.463215 2.56832e-21)
(0.00382075 0.622238 -2.3528e-21)
(0.00861627 0.816063 5.10576e-21)
(0.145797 0.397986 1.32874e-21)
(0.127477 0.398106 2.72533e-21)
(0.10735 0.391768 -4.52118e-22)
(0.0894041 0.384696 8.60302e-22)
(0.0702689 0.379275 1.99868e-21)
(0.0557713 0.37857 3.18403e-21)
(0.0368094 0.395514 -1.07411e-21)
(0.0281624 0.469379 -1.12118e-21)
(0.00401306 0.627183 2.36058e-21)
(0.00809759 0.81817 1.16359e-21)
(0.14221 0.40138 -4.81437e-22)
(0.124237 0.402893 4.8903e-22)
(0.104539 0.396787 -7.39179e-22)
(0.0869948 0.389793 -8.5926e-22)
(0.0683094 0.384237 9.61237e-22)
(0.0541275 0.38344 -1.9973e-21)
(0.035768 0.40052 1.60765e-21)
(0.0272327 0.474656 5.8454e-22)
(0.00418421 0.631268 0)
(0.00762274 0.819998 -1.16614e-21)
(0.00156231 -0.00403723 0)
(0.00250954 -0.00506158 0)
(0.0040972 -0.0010759 2.41278e-21)
(0.00659334 0.00633273 0)
(0.0100372 0.0163325 1.16117e-22)
(0.014319 0.028338 -1.07602e-22)
(0.0193664 0.0418356 0)
(0.0253502 0.0562723 0)
(0.0333293 0.0709609 -1.71395e-21)
(0.0420134 0.0807127 2.91716e-21)
(0.00122109 -0.00317035 0)
(0.00371811 -0.00506004 2.85967e-21)
(0.00670013 -0.00254918 6.18816e-22)
(0.0101418 0.00282816 1.13633e-21)
(0.0139689 0.0102502 3.16032e-22)
(0.018018 0.0191034 -3.9402e-22)
(0.0221636 0.0289137 0)
(0.0263757 0.0393085 0)
(0.0308955 0.0498168 0)
(0.0360666 0.0579624 -5.17922e-22)
(0.00117239 -0.00229011 0)
(0.00595044 -0.00409423 7.2002e-22)
(0.0112788 -0.00154282 -1.16835e-21)
(0.0166786 0.00360515 -7.27871e-22)
(0.0219762 0.0105254 1.20022e-22)
(0.0269723 0.0185622 2.22813e-22)
(0.0315593 0.0272684 3.10621e-22)
(0.0357713 0.0363861 -2.79653e-22)
(0.0397405 0.0453702 4.30329e-23)
(0.0438001 0.0519715 5.75869e-23)
(0.00167713 -0.00150601 6.49066e-22)
(0.0095358 -0.00239988 -2.83485e-21)
(0.0180898 0.00154667 -2.99564e-21)
(0.0263417 0.00806156 1.65912e-21)
(0.0340388 0.0162813 -6.46732e-22)
(0.0409691 0.0254713 -2.99631e-23)
(0.0470642 0.0351293 -2.77947e-22)
(0.0524475 0.0449713 1.61327e-22)
(0.0573273 0.0543824 -1.00081e-21)
(0.0615988 0.0611407 5.56305e-22)
(0.00296392 -0.000840278 5.98306e-22)
(0.0147506 -0.000132173 -5.68443e-22)
(0.0272493 0.00631655 0)
(0.0390041 0.0154251 -1.47729e-21)
(0.0496825 0.0262318 2.2189e-22)
(0.0590641 0.0378867 7.38637e-23)
(0.0671106 0.0497851 1.10437e-22)
(0.0739771 0.0615601 9.12643e-22)
(0.0799402 0.0726434 -3.96343e-23)
(0.0846742 0.0809088 -2.04443e-21)
(0.00519662 -0.000232691 0)
(0.0217472 0.00266807 2.72611e-21)
(0.0386888 0.01243 -7.39588e-22)
(0.0542525 0.0248879 9.66655e-22)
(0.0680278 0.0389078 -2.50239e-22)
(0.0797922 0.053492 9.41739e-23)
(0.0895468 0.0679255 1.40725e-22)
(0.0974703 0.0817603 -8.72357e-22)
(0.103881 0.0945386 2.14116e-21)
(0.108665 0.104681 -2.62907e-21)
(0.00846133 0.000450935 -4.21986e-22)
(0.0305109 0.00608009 -1.92385e-21)
(0.0521154 0.0196414 0)
(0.071388 0.0356833 -1.00067e-21)
(0.0878654 0.0528217 7.98768e-22)
(0.101365 0.0699 2.43909e-22)
(0.111979 0.0861307 -6.34146e-22)
(0.119976 0.101054 0)
(0.12573 0.114344 0)
(0.129519 0.125461 0)
(0.0127391 0.00139632 3.59973e-22)
(0.0408342 0.0102549 6.53895e-22)
(0.0669904 0.0277545 -6.1618e-22)
(0.0894398 0.0470678 -5.64139e-22)
(0.107742 0.066515 -3.57386e-22)
(0.121852 0.0848236 -3.59856e-22)
(0.132064 0.101232 0)
(0.138846 0.115399 -1.28134e-21)
(0.142733 0.127201 3.8699e-22)
(0.144253 0.137138 0)
(0.0178953 0.00279998 0)
(0.0523012 0.0153354 -1.49062e-21)
(0.082535 0.0365307 6.16018e-22)
(0.107226 0.0582509 3.91366e-22)
(0.126105 0.0785619 9.85439e-24)
(0.139436 0.0962135 1.75906e-22)
(0.147863 0.110644 -3.16331e-22)
(0.152189 0.121804 0)
(0.153214 0.129939 8.12973e-22)
(0.1516 0.136114 1.25641e-21)
(0.0237001 0.00482334 -6.06328e-23)
(0.0643155 0.0213663 5.46244e-22)
(0.0978019 0.0456024 1.90133e-23)
(0.123502 0.0683696 -7.58642e-24)
(0.141552 0.0876641 1.38936e-22)
(0.15274 0.10251 0)
(0.15823 0.112785 3.16255e-22)
(0.159262 0.118923 0)
(0.156958 0.121672 0)
(0.152186 0.122277 0)
(0.0298993 0.00755927 1.20202e-22)
(0.0761887 0.0282354 0)
(0.111816 0.0544587 0)
(0.137177 0.0765828 1.40002e-22)
(0.153101 0.0928776 -8.3654e-23)
(0.161112 0.102974 -5.8862e-23)
(0.163018 0.107434 1.71203e-22)
(0.160538 0.107318 0)
(0.155112 0.103882 0)
(0.147877 0.0984669 0)
(0.0361466 0.0110296 0)
(0.0871971 0.035712 1.74372e-22)
(0.12372 0.0625755 -1.60783e-22)
(0.14751 0.0822979 -1.95749e-22)
(0.160357 0.0938749 0)
(0.164672 0.0978696 -3.83282e-22)
(0.162934 0.0956894 3.56445e-22)
(0.1573 0.0890473 0)
(0.14945 0.079584 -1.53569e-21)
(0.140655 0.0687392 1.46767e-21)
(0.0419635 0.0151411 0)
(0.0965621 0.0433977 -1.15226e-21)
(0.13281 0.0694224 0)
(0.154129 0.0852004 -3.28054e-22)
(0.163449 0.0908942 0)
(0.164087 0.0882058 9.51147e-22)
(0.159123 0.0794029 0)
(0.151031 0.0667293 -2.50409e-21)
(0.141587 0.0520303 2.34544e-21)
(0.131949 0.0367519 3.04424e-21)
(0.0469206 0.0196909 4.4057e-22)
(0.103696 0.0508177 5.75432e-22)
(0.138729 0.0746151 1.45981e-22)
(0.157101 0.0853458 1.97817e-22)
(0.162915 0.0846407 1.20334e-22)
(0.160291 0.0753763 -3.92977e-22)
(0.152758 0.0605507 -5.19228e-22)
(0.142965 0.042739 5.53163e-22)
(0.13263 0.0238205 -2.07686e-21)
(0.12262 0.00512628 -3.05984e-21)
(0.050658 0.0243957 4.02775e-22)
(0.108227 0.0575092 -2.76377e-25)
(0.141425 0.0779652 -8.24886e-22)
(0.156785 0.083065 1.61861e-22)
(0.159463 0.0760107 0)
(0.154203 0.0607393 0)
(0.14481 0.0407774 1.2134e-21)
(0.133967 0.018826 1.69001e-21)
(0.123246 -0.0033132 -1.66457e-21)
(0.113177 -0.0245023 3.28373e-21)
(0.0529135 0.028926 4.89824e-24)
(0.110009 0.0630759 4.00763e-22)
(0.141084 0.0794523 -2.66009e-21)
(0.153685 0.0788143 3.47623e-21)
(0.153816 0.0658582 -4.47632e-22)
(0.14662 0.0453851 0)
(0.13601 0.0212497 0)
(0.124617 -0.00387416 -4.60244e-21)
(0.113844 -0.0283279 7.14963e-21)
(0.103951 -0.0511745 6.27579e-21)
(0.0535516 0.0329446 3.13215e-21)
(0.109102 0.0672167 0)
(0.138042 0.0791662 2.93622e-21)
(0.148352 0.0730514 -2.99216e-21)
(0.146631 0.054868 0)
(0.138197 0.0300776 6.83856e-22)
(0.126918 0.00269555 -2.06455e-21)
(0.115332 -0.0247319 2.11943e-21)
(0.104712 -0.050708 -9.51479e-22)
(0.0951828 -0.0744523 -3.07953e-21)
(0.052573 0.0361447 -9.28416e-21)
(0.105733 0.0697315 -1.43722e-21)
(0.132715 0.0772499 -4.07136e-21)
(0.141317 0.0661671 -7.95698e-21)
(0.138467 0.0435243 -2.12426e-21)
(0.129468 0.0152739 -2.29153e-21)
(0.118014 -0.0145184 -1.43496e-21)
(0.106487 -0.0434967 0)
(0.0961155 -0.0703384 0)
(0.0870641 -0.094328 -1.99802e-21)
(0.0501003 0.0382775 6.15236e-21)
(0.100244 0.0705183 -8.79046e-21)
(0.125549 0.0738686 4.87335e-21)
(0.133047 0.0584597 1.20773e-20)
(0.129763 0.0321237 -3.35869e-21)
(0.120868 0.00117218 6.49886e-22)
(0.109773 -0.0303175 7.89788e-22)
(0.0986221 -0.0602014 0)
(0.0886111 -0.0873726 0)
(0.0800022 -0.111051 4.51454e-22)
(0.0463652 0.0391774 -1.35458e-21)
(0.093055 0.0695603 1.14084e-20)
(0.116979 0.069198 -2.41253e-21)
(0.123907 0.0501533 0)
(0.120796 0.0208003 0)
(0.112641 -0.012296 5.84262e-21)
(0.102583 -0.0450292 0)
(0.0925302 -0.0753743 -2.9258e-21)
(0.0835834 -0.102404 1.00813e-21)
(0.0756088 -0.125052 1.69391e-21)
(0.0416731 0.0387797 0)
(0.0846134 0.0669291 0)
(0.107402 0.0634275 -1.30718e-20)
(0.114161 0.0414481 0)
(0.111635 0.00964321 4.69714e-21)
(0.104641 -0.0253441 -4.35335e-21)
(0.0961382 -0.0595688 0)
(0.0878663 -0.0914001 0)
(0.0807065 -0.120579 -3.47948e-21)
(0.0737281 -0.146685 7.33233e-21)
(0.0363463 0.0370844 0)
(0.0753719 0.062764 -1.17239e-20)
(0.0971873 0.0567757 -5.12951e-21)
(0.104028 0.0325981 -1.36507e-20)
(0.102249 -0.00102968 -6.60181e-21)
(0.0964172 -0.037418 -1.54365e-20)
(0.0892785 -0.0726698 0)
(0.0823164 -0.105181 0)
(0.0760538 -0.134512 0)
(0.0693937 -0.159772 7.76378e-22)
(0.030726 0.0341654 0)
(0.065788 0.0572594 -5.79697e-21)
(0.0867082 0.0494746 6.34681e-21)
(0.0937664 0.023842 1.00661e-20)
(0.092783 -0.0109557 -1.14601e-21)
(0.0880179 -0.0481666 -1.12318e-21)
(0.0820174 -0.0838356 9.79773e-21)
(0.0760793 -0.116264 -8.28224e-21)
(0.0705996 -0.144895 1.3267e-20)
(0.0647622 -0.168957 -1.20265e-20)
(0.0251654 0.0302106 -2.60052e-21)
(0.0562951 0.0506764 1.25876e-20)
(0.0763131 0.0417475 2.03107e-20)
(0.0836523 0.0153487 -2.33025e-20)
(0.0834918 -0.0200249 1.35637e-20)
(0.0797425 -0.0575661 1.18942e-20)
(0.0747881 -0.0932204 -4.43925e-21)
(0.0698247 -0.125207 1.66927e-20)
(0.0652407 -0.15299 3.28682e-22)
(0.0604855 -0.176155 -7.13782e-21)
(0.0199695 0.0254706 -2.61805e-21)
(0.0472627 0.0433124 2.48789e-21)
(0.0663055 0.0338046 0)
(0.0739383 0.00723467 1.96908e-20)
(0.0746256 -0.0282208 -3.65454e-21)
(0.0718942 -0.0657378 -2.84779e-22)
(0.0679778 -0.101156 -5.68566e-21)
(0.0640104 -0.132632 -1.40881e-20)
(0.0604004 -0.1597 7.10771e-22)
(0.0567875 -0.182287 1.1691e-20)
(0.0153707 0.0202284 0)
(0.0389802 0.0354812 -1.44754e-20)
(0.0569291 0.0258441 4.45761e-21)
(0.0648279 -0.000414432 -1.21848e-20)
(0.0663848 -0.0355626 3.72368e-21)
(0.0647016 -0.0728154 9.40214e-23)
(0.0618466 -0.107917 1.41764e-22)
(0.058903 -0.138955 9.75407e-21)
(0.0562916 -0.16551 -1.32626e-20)
(0.0537957 -0.187754 1.27714e-20)
(0.0115216 0.0147774 1.41833e-21)
(0.0316484 0.0274992 9.64171e-21)
(0.0483597 0.018054 0)
(0.0564646 -0.00752758 1.21644e-20)
(0.0589036 -0.0420715 -1.09197e-20)
(0.0583096 -0.0788996 -3.16948e-21)
(0.0565533 -0.113673 8.66779e-21)
(0.0546562 -0.144387 0)
(0.0530387 -0.170617 0)
(0.0515991 -0.192675 0)
(0.00849421 0.00940082 -1.31277e-21)
(0.0253785 0.0196705 -3.35338e-21)
(0.0407047 0.0106111 4.22385e-21)
(0.0489343 -0.0140407 5.80607e-21)
(0.0522573 -0.0477591 5.40967e-21)
(0.0527975 -0.084047 3.10848e-21)
(0.0521852 -0.118501 0)
(0.0513595 -0.149002 5.03692e-21)
(0.0507256 -0.175057 -2.40196e-21)
(0.0502728 -0.197025 0)
(0.00628553 0.00435457 0)
(0.0201974 0.0122735 6.76941e-21)
(0.0340087 0.00367862 -4.22278e-21)
(0.0422733 -0.0198921 -3.85357e-21)
(0.046474 -0.0526258 -3.15852e-23)
(0.0481961 -0.088279 -1.56197e-21)
(0.0487837 -0.122417 1.32679e-21)
(0.049066 -0.152786 0)
(0.0494192 -0.178777 -2.31506e-21)
(0.0498931 -0.200713 -2.27136e-21)
(0.00482847 -0.000146109 1.52371e-22)
(0.0160584 0.0055474 -2.4294e-21)
(0.0282639 -0.00260524 -2.35662e-22)
(0.0364782 -0.0250336 7.23241e-24)
(0.0415452 -0.0566707 -1.23692e-21)
(0.0445009 -0.0915966 0)
(0.0463584 -0.125393 -1.32632e-21)
(0.0478066 -0.155673 0)
(0.0491776 -0.181671 0)
(0.0505438 -0.203608 0)
(0.00400614 -0.00393485 -2.75684e-22)
(0.0128546 -0.000319242 0)
(0.0234209 -0.00814783 0)
(0.0315223 -0.0294665 -1.09766e-21)
(0.0374468 -0.0599433 3.44791e-22)
(0.0416891 -0.0940465 -1.43507e-23)
(0.0448976 -0.127436 -5.956e-22)
(0.0475908 -0.157613 0)
(0.0500449 -0.183638 0)
(0.0523103 -0.20558 0)
(0.00366491 -0.00692078 0)
(0.0104254 -0.00520853 -8.38356e-22)
(0.0193859 -0.0128757 7.73177e-22)
(0.0273549 -0.0331747 1.48916e-21)
(0.0341468 -0.0624572 0)
(0.039737 -0.0956301 1.13345e-21)
(0.0443897 -0.128504 -1.05403e-21)
(0.0484257 -0.158512 0)
(0.0520611 -0.184545 2.017e-21)
(0.055284 -0.206478 -1.94645e-21)
(0.00364106 -0.00906346 0)
(0.00860011 -0.00904994 5.2918e-21)
(0.0160649 -0.0167279 0)
(0.0239317 -0.0361268 4.28465e-21)
(0.0316188 -0.0642063 0)
(0.0386205 -0.0963398 -3.45981e-21)
(0.0448138 -0.128559 0)
(0.0502982 -0.158286 3.57965e-21)
(0.0552339 -0.184264 -3.35257e-21)
(0.0595355 -0.206161 -3.51113e-21)
(0.00377146 -0.0103674 -1.30743e-21)
(0.00721078 -0.0118301 -2.86769e-21)
(0.0133735 -0.0196857 -1.08974e-21)
(0.0212253 -0.0383179 -2.40505e-21)
(0.0298546 -0.0652015 -1.736e-21)
(0.0383258 -0.0961824 1.91866e-21)
(0.0461462 -0.127576 1.4329e-21)
(0.0531759 -0.156863 -4.95568e-22)
(0.0595167 -0.182671 2.81919e-21)
(0.0650744 -0.204469 3.50601e-21)
(0.00390743 -0.0108855 -1.05175e-21)
(0.00610791 -0.0135903 -1.83747e-21)
(0.0112475 -0.0217601 -2.72147e-21)
(0.0192322 -0.0397486 1.48244e-21)
(0.0288712 -0.0654465 0)
(0.0388586 -0.0951594 0)
(0.0483692 -0.125535 -2.21849e-21)
(0.057023 -0.154187 -2.24831e-21)
(0.0648367 -0.179665 2.06618e-21)
(0.0717988 -0.201168 -3.93168e-21)
(0.00392635 -0.0107079 7.3842e-22)
(0.00518186 -0.0144247 6.06394e-22)
(0.00965605 -0.0229836 -2.00948e-21)
(0.0179811 -0.0404109 3.66101e-21)
(0.0287138 -0.0649148 -8.20311e-22)
(0.0402449 -0.0932402 0)
(0.0514663 -0.122397 0)
(0.0617889 -0.15019 7.15682e-21)
(0.0711932 -0.175119 -9.21158e-21)
(0.0796768 -0.196142 -7.95719e-21)
(0.00374211 -0.00996197 2.83356e-21)
(0.00437349 -0.0144623 0)
(0.00861198 -0.0233926 3.61121e-21)
(0.0175316 -0.0402652 -2.77301e-21)
(0.029455 -0.0635319 0)
(0.0425301 -0.0903488 4.01238e-22)
(0.0554344 -0.118092 -2.65247e-22)
(0.0674022 -0.144797 -3.79038e-21)
(0.0784061 -0.168981 1.61316e-21)
(0.0885537 -0.189413 3.8372e-21)
(0.00332299 -0.00880194 -3.7584e-21)
(0.00369071 -0.0138475 -2.81885e-22)
(0.0081767 -0.0230217 5.79578e-22)
(0.0179699 -0.0392491 1.12566e-21)
(0.0311798 -0.0611834 5.36372e-22)
(0.0457722 -0.0863559 1.64013e-21)
(0.0602783 -0.112494 1.82789e-21)
(0.073782 -0.137887 0)
(0.0862361 -0.161114 0)
(0.0980316 -0.180725 4.06188e-21)
(0.00269277 -0.00738873 9.24756e-22)
(0.00321365 -0.012732 1.06554e-21)
(0.00845731 -0.0219 1.72326e-22)
(0.0194061 -0.0372776 -2.87624e-21)
(0.0339812 -0.0577009 1.19808e-21)
(0.0500332 -0.0810536 3.46799e-22)
(0.0660215 -0.105391 -5.02044e-22)
(0.0809203 -0.129265 0)
(0.0945712 -0.151366 0)
(0.107771 -0.170148 -9.72939e-22)
(0.0019328 -0.00587906 1.83523e-22)
(0.00308857 -0.0112553 -1.68805e-21)
(0.00959449 -0.0200432 5.7389e-22)
(0.0219573 -0.0342496 0)
(0.0379505 -0.0528878 0)
(0.0553768 -0.0741736 -4.02646e-21)
(0.0726756 -0.0964329 0)
(0.0887322 -0.11837 3.3464e-21)
(0.102932 -0.138649 -1.12256e-21)
(0.116069 -0.155652 -1.93004e-21)
(0.00117774 -0.00441047 0)
(0.00351325 -0.00952745 0)
(0.0117437 -0.0174532 5.04209e-21)
(0.0257274 -0.0300685 0)
(0.0431706 -0.0465667 -3.39735e-21)
(0.0619436 -0.0654749 3.14843e-21)
(0.0806288 -0.0853169 0)
(0.0984411 -0.104803 0)
(0.114936 -0.122922 3.18498e-21)
(0.130554 -0.139835 -6.0728e-21)
(0.000606114 -0.00308954 0)
(0.00471172 -0.00761576 3.47107e-21)
(0.015051 -0.014122 2.33333e-21)
(0.0307588 -0.0246595 7.52962e-21)
(0.0496296 -0.0386466 4.28468e-21)
(0.0696939 -0.0549194 1.26669e-20)
(0.089756 -0.0722542 0)
(0.109332 -0.0895596 0)
(0.128502 -0.106086 0)
(0.146602 -0.123428 -5.71201e-22)
(0.000429665 -0.00198147 0)
(0.0068942 -0.00553527 2.2294e-21)
(0.0196022 -0.0100191 -2.52606e-21)
(0.0370263 -0.0180041 -5.7585e-21)
(0.0571867 -0.0291406 9.87586e-22)
(0.0783652 -0.0425416 1.02579e-21)
(0.0995965 -0.0572306 -9.58672e-21)
(0.12053 -0.0723552 8.7905e-21)
(0.141186 -0.0875757 -1.37123e-20)
(0.161147 -0.104076 1.09003e-20)
(0.000865701 -0.00108921 4.97842e-22)
(0.0102488 -0.00324073 -3.76237e-21)
(0.0254203 -0.0051291 -8.56582e-21)
(0.0444249 -0.0101494 1.38932e-20)
(0.0656158 -0.0181354 -8.7239e-21)
(0.0875936 -0.028447 -9.41427e-21)
(0.109588 -0.0403117 4.70243e-21)
(0.131274 -0.0530913 -1.76553e-20)
(0.152428 -0.0666683 2.61794e-22)
(0.172701 -0.0811203 7.05526e-21)
(0.00209675 -0.000351202 6.21108e-22)
(0.0149128 -0.000653789 -5.90164e-22)
(0.0324787 0.000554384 0)
(0.0527736 -0.00117364 -1.15637e-20)
(0.074622 -0.0058135 2.34294e-21)
(0.096973 -0.012912 -1.46608e-22)
(0.119216 -0.0218509 5.09012e-21)
(0.141017 -0.0321233 1.42081e-20)
(0.161984 -0.0435952 -5.72106e-22)
(0.181593 -0.0558008 -1.0174e-20)
(0.0042577 0.000338838 0)
(0.0209429 0.00234557 4.63825e-21)
(0.0406785 0.00705333 -1.62949e-21)
(0.0618512 0.00881578 7.06944e-21)
(0.0838916 0.00758608 -2.34409e-21)
(0.106115 0.0036986 1.36353e-22)
(0.128051 -0.00232723 2.25055e-23)
(0.149363 -0.010038 -9.54989e-21)
(0.169608 -0.0191954 1.24415e-20)
(0.188194 -0.0292392 -1.08901e-20)
(0.00742585 0.00112794 -1.57935e-22)
(0.0283037 0.0059134 -2.87139e-21)
(0.0498633 0.0143975 0)
(0.071422 0.0197125 -6.97496e-21)
(0.0931417 0.0218332 7.00573e-21)
(0.114721 0.0210481 2.6168e-21)
(0.135825 0.0178371 -7.53696e-21)
(0.156147 0.0126645 0)
(0.175291 0.00590081 0)
(0.192727 -0.00197698 0)
(0.0116005 0.00219195 2.19246e-22)
(0.0368814 0.0102198 1.00468e-21)
(0.0598396 0.0226259 -1.61934e-21)
(0.0812636 0.0314343 -3.0872e-21)
(0.102158 0.0367512 -3.70267e-21)
(0.122623 0.0388955 -2.20731e-21)
(0.142467 0.0383659 0)
(0.161453 0.0356845 -4.09224e-21)
(0.179288 0.0313552 2.12097e-21)
(0.195583 0.025732 0)
(0.0166936 0.00371419 0)
(0.0464856 0.0154316 -1.74916e-21)
(0.0703893 0.0317835 1.61907e-21)
(0.0911809 0.0439293 1.95493e-21)
(0.110804 0.0522285 1.2872e-22)
(0.129776 0.0571044 1.2225e-21)
(0.148066 0.059124 -8.97851e-22)
(0.165525 0.0588929 0)
(0.18198 0.0570304 1.71156e-21)
(0.197207 0.0537824 1.14418e-21)
(0.02255 0.00586095 -1.8152e-24)
(0.0568671 0.0216908 6.12166e-22)
(0.0812827 0.0419109 1.19567e-22)
(0.101009 0.0571683 3.9276e-23)
(0.119004 0.0682025 7.35525e-22)
(0.136219 0.07561 0)
(0.152784 0.0800595 8.9765e-22)
(0.168644 0.082243 0)
(0.183731 0.0828628 0)
(0.197959 0.0820911 0)
(0.0290184 0.00876614 -4.42994e-24)
(0.0677776 0.0291021 0)
(0.092321 0.0530333 0)
(0.110635 0.0711294 3.98491e-22)
(0.126749 0.0846337 -1.86418e-22)
(0.142048 0.0943726 -7.22741e-25)
(0.156816 0.101133 2.98168e-22)
(0.171075 0.105679 0)
(0.184823 0.108757 0)
(0.198062 0.11051 0)
(0.0358637 0.0125262 0)
(0.0789142 0.037726 2.23545e-22)
(0.103279 0.0651391 -2.06189e-22)
(0.119942 0.085769 -5.70355e-22)
(0.13402 0.10147 0)
(0.14733 0.113338 -4.00972e-22)
(0.160294 0.122279 3.72881e-22)
(0.172983 0.129098 0)
(0.185419 0.134556 -2.56375e-23)
(0.197628 0.138816 2.50109e-23)
(0.0427373 0.0171781 0)
(0.0898916 0.0475656 -1.59975e-21)
(0.113898 0.07819 0)
(0.128796 0.10103 -1.15104e-21)
(0.140787 0.118642 0)
(0.152112 0.13242 3.57293e-22)
(0.163312 0.143371 0)
(0.17448 0.152311 5.38757e-22)
(0.185626 0.159996 -5.04577e-22)
(0.19675 0.16664 -2.22312e-21)
(0.0492969 0.0226795 2.41859e-22)
(0.100326 0.0585368 9.87813e-22)
(0.123929 0.092086 3.52404e-22)
(0.13707 0.116809 8.09151e-22)
(0.147013 0.136038 3.15821e-22)
(0.156413 0.151477 -5.70089e-22)
(0.165916 0.164219 1.97894e-22)
(0.175619 0.175059 1.67288e-22)
(0.185491 0.184728 1.66433e-21)
(0.195468 0.193518 2.22531e-21)
(0.0552105 0.0289113 2.04704e-22)
(0.109844 0.070475 8.03074e-22)
(0.133131 0.106673 8.71235e-22)
(0.144641 0.132966 -3.89128e-22)
(0.152651 0.153511 0)
(0.160232 0.170337 0)
(0.168127 0.184601 -2.20941e-21)
(0.17643 0.197055 -2.94862e-21)
(0.18505 0.208391 3.90334e-21)
(0.193817 0.218987 -4.94672e-21)
(0.0601616 0.0356773 -5.09808e-22)
(0.118089 0.0831345 -4.35101e-22)
(0.14127 0.121742 2.22008e-21)
(0.151383 0.149323 1.4594e-22)
(0.157645 0.170889 -1.79584e-22)
(0.163541 0.188805 0)
(0.169926 0.204285 0)
(0.176883 0.21802 1.97053e-20)
(0.184245 0.230658 -2.1997e-20)
(0.191716 0.242658 -2.00928e-20)
(0.0638691 0.0427109 -6.46042e-21)
(0.12473 0.0961924 0)
(0.148126 0.137031 -2.56183e-21)
(0.157175 0.16567 4.84501e-23)
(0.161931 0.187983 0)
(0.166314 0.206693 3.15485e-21)
(0.171313 0.223066 -1.08235e-20)
(0.177022 0.237739 -1.88205e-20)
(0.183197 0.251313 9.9174e-21)
(0.189368 0.264296 1.24316e-20)
(0.0661084 0.0496877 1.53828e-20)
(0.12948 0.109257 1.3716e-21)
(0.153502 0.152234 2.05866e-21)
(0.161901 0.181773 7.16315e-23)
(0.165448 0.204601 -2.50232e-21)
(0.168508 0.223819 -4.27865e-21)
(0.172232 0.24076 -1.35464e-21)
(0.176727 0.256009 0)
(0.181643 0.270149 0)
(0.186332 0.283721 3.42128e-20)
(0.0667294 0.0562449 -8.92268e-21)
(0.132111 0.121881 9.77258e-21)
(0.157222 0.166999 -3.21003e-21)
(0.165458 0.197376 9.20459e-22)
(0.168142 0.220547 -1.01344e-21)
(0.170108 0.240032 3.63871e-21)
(0.172731 0.257263 5.156e-21)
(0.176207 0.272807 0)
(0.180172 0.287277 0)
(0.183817 0.301188 -1.6612e-20)
(0.0656765 0.0620119 1.60772e-21)
(0.132463 0.133577 -1.18047e-20)
(0.159146 0.180945 1.87348e-21)
(0.16776 0.212211 0)
(0.169968 0.235633 0)
(0.171083 0.255188 7.35549e-21)
(0.172736 0.27244 0)
(0.175181 0.287868 -1.52847e-20)
(0.177851 0.302046 -3.24872e-21)
(0.179533 0.31581 1.71056e-20)
(0.0629948 0.0666491 0)
(0.130452 0.143846 0)
(0.159165 0.193661 6.67422e-21)
(0.168729 0.225985 0)
(0.170884 0.249664 3.17097e-21)
(0.171419 0.269174 -2.93885e-21)
(0.172277 0.286326 0)
(0.173889 0.301678 0)
(0.175941 0.316041 -1.85592e-20)
(0.177828 0.331805 3.80846e-20)
(0.0587513 0.0697859 0)
(0.125995 0.152112 1.18229e-20)
(0.1572 0.20472 3.61296e-21)
(0.168292 0.23839 1.54165e-21)
(0.170861 0.262457 -5.72251e-22)
(0.171138 0.28189 -1.09569e-20)
(0.171435 0.298842 0)
(0.172441 0.314025 0)
(0.174193 0.328083 0)
(0.176326 0.342633 1.99876e-21)
(0.0531368 0.0711128 0)
(0.119229 0.157872 4.17732e-21)
(0.1532 0.213611 -3.10987e-21)
(0.166361 0.249096 -3.31106e-22)
(0.16986 0.273812 4.38009e-22)
(0.170221 0.293238 2.16197e-22)
(0.170167 0.309917 1.16152e-20)
(0.170652 0.324763 -1.48652e-20)
(0.171869 0.33827 3.72833e-20)
(0.173343 0.35122 -4.15181e-20)
(0.0465071 0.0704645 2.72491e-21)
(0.110359 0.160717 -1.23994e-20)
(0.147123 0.219834 -1.18166e-20)
(0.162888 0.25771 2.81638e-21)
(0.167834 0.283507 5.98811e-22)
(0.168642 0.303134 5.42973e-21)
(0.168445 0.319565 -6.96578e-21)
(0.168484 0.333971 3.1674e-20)
(0.169135 0.346776 3.53419e-21)
(0.169904 0.35837 -1.8814e-20)
(0.0392733 0.0678211 2.55134e-21)
(0.0996776 0.160269 -2.42382e-21)
(0.139039 0.222962 0)
(0.157817 0.263832 -3.04603e-21)
(0.164729 0.291278 8.51763e-23)
(0.166383 0.311474 1.31746e-21)
(0.166286 0.327831 -4.4484e-21)
(0.166003 0.34186 -2.35384e-20)
(0.166122 0.354071 -2.08358e-21)
(0.166434 0.364643 3.18035e-20)
(0.0318745 0.0633065 0)
(0.0876087 0.156318 1.19864e-20)
(0.129059 0.222563 -3.27153e-21)
(0.151083 0.26702 2.28777e-21)
(0.160458 0.296804 -2.26061e-22)
(0.163411 0.318088 -1.02814e-21)
(0.163733 0.33469 -9.52636e-22)
(0.163352 0.348493 1.50255e-20)
(0.163143 0.360208 -2.59265e-20)
(0.162992 0.370081 2.89533e-20)
(0.0247453 0.0571841 -1.48269e-21)
(0.0746852 0.14885 -8.43773e-21)
(0.117362 0.218263 0)
(0.142621 0.266781 -2.4212e-21)
(0.154892 0.299671 -1.53208e-22)
(0.159635 0.322724 -2.07375e-21)
(0.16074 0.340042 7.05896e-21)
(0.160464 0.353903 0)
(0.159981 0.36529 0)
(0.159355 0.374579 0)
(0.018272 0.0498338 1.26571e-21)
(0.0615224 0.138079 2.73893e-21)
(0.104225 0.209815 -2.55519e-21)
(0.132387 0.262602 -1.40148e-21)
(0.14785 0.299354 7.27209e-22)
(0.154882 0.324999 1.23437e-21)
(0.157204 0.343689 0)
(0.157307 0.35807 7.10946e-21)
(0.15667 0.36948 -3.01379e-21)
(0.155696 0.378497 0)
(0.0127536 0.0417108 0)
(0.0487805 0.124458 -5.7896e-21)
(0.0900591 0.19717 2.55453e-21)
(0.120398 0.254 1.15818e-21)
(0.139112 0.295216 -3.12193e-22)
(0.148893 0.324365 -9.37411e-22)
(0.15295 0.345282 9.74873e-22)
(0.153839 0.360849 0)
(0.153298 0.372789 -3.64412e-21)
(0.152149 0.381959 -4.48559e-21)
(0.00837544 0.0333199 -1.64573e-22)
(0.037108 0.108692 2.04063e-21)
(0.0754432 0.180562 5.01383e-23)
(0.106812 0.240599 -1.3357e-22)
(0.128466 0.286509 -7.78101e-23)
(0.141307 0.320011 0)
(0.147655 0.344166 -9.74471e-22)
(0.149868 0.361808 0)
(0.149816 0.374964 0)
(0.148727 0.384808 0)
)
;
boundaryField
{
inlet
{
type uniformFixedValue;
uniformValue constant (1 0 0);
value uniform (1 0 0);
}
outlet
{
type pressureInletOutletVelocity;
value nonuniform List<vector>
40
(
(0.0359364 0.347314 0)
(0.00665451 0.398138 0)
(-0.000678972 0.456474 0)
(0.00139868 0.500612 0)
(0.000811237 0.524419 0)
(-0.00126802 0.537721 0)
(-0.00609521 0.548149 0)
(-0.00994965 0.560738 0)
(-0.013006 0.577442 0)
(-0.00691522 0.597838 0)
(0.0420443 0.300974 -3.91332e-23)
(0.0414487 0.27522 2.269e-23)
(0.0390633 0.24419 -5.73906e-23)
(0.035179 0.209068 -1.05751e-23)
(0.0301633 0.171229 3.16964e-23)
(0.0245718 0.132274 0)
(0.0189656 0.0938657 -2.3431e-24)
(0.0138383 0.0575053 3.77744e-24)
(0.0095269 0.024329 -2.45444e-24)
(0 -0.00501993 0)
(0 -0.0304595 0)
(0 -0.0524177 0)
(0 -0.0715482 0)
(0 -0.0885501 0)
(0 -0.104051 0)
(0 -0.118553 0)
(0 -0.132426 0)
(0 -0.145928 0)
(0 -0.159233 0)
(0 -0.172458 0)
(0 -0.203868 0)
(0 -0.257836 0)
(0 -0.311908 0)
(0 -0.368337 0)
(0 -0.431992 0)
(0 -0.509042 0)
(0 -0.607564 0)
(0 -0.727572 0)
(0 -0.841203 0)
(0 -0.906906 0)
)
;
}
cylinder
{
type fixedValue;
value uniform (0 0 0);
}
top
{
type symmetryPlane;
}
bottom
{
type symmetryPlane;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"henry.rossiter@utexas.edu"
] | henry.rossiter@utexas.edu | |
c1a62c8dd6b64b7c24137465b413c66c51c1ae68 | 13fd4fed91fa0d42c1ac59e6ba5273010f5f7f1c | /Конструктор копирования/Конструктор копирования/Конструктор копирования.cpp | 561fb597c961a8fe241302b904086ac5da38e9e8 | [] | no_license | Morzhling/My-Cpp-training | 9b1488b557dfafbcabcc4d675874b86dddc1ef79 | 8e372e105f8d05dd152cc1be1666dc36413b430b | refs/heads/master | 2020-04-27T11:04:28.002711 | 2019-07-29T19:51:10 | 2019-07-29T19:51:10 | 174,282,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | #include "pch.h"
#include <iostream>
using namespace std;
class MyClass
{
int Size;
public:
int *data;
MyClass()
{
cout << this << " Constructor " << endl;
}
MyClass(int size)
{
this->Size = size;
this->data = new int[size];
for (int i = 0; i < size; i++)
{
data[i] = i;
}
cout << this << " Constructor " << endl;
}
MyClass(const MyClass &other)
{
this->Size = other.Size;
this->data = new int[other.Size];
for (int i = 0; i < other.Size; i++)
{
this->data[i] = other.data[i];
}
cout << this << " Constructor copy " << endl;
}
~MyClass()
{
cout << this << " Destructor " << endl;
delete[] data;
}
/*void Print()
{
cout << "X = " << x << "\t" << "Y = " << y << endl;
}*/
};
void Func(MyClass val)
{
cout << " Func " << endl;
}
MyClass Func2()
{
cout << " Func2 " << endl;
MyClass temp(31);
return temp;
}
int main()
{
//Func2();
MyClass a(12);
MyClass b(a);
//Func(a);
return 0;
} | [
"basiluzumaki@gmail.com"
] | basiluzumaki@gmail.com |
46e0a4074dcadbd9515e333a49ab7112a54472f3 | 8bdd599364b621da20d2fea67b3499dcfc2b1661 | /Course(Array sorting)/Course/Course/stdafx.cpp | 7421a4ccdbef3100fc445a056fbf4b3e5c9c722d | [] | no_license | lin60102/Cpp_programs | fd5e3884f4bf666e704ac2f2aa48924867a4db58 | e3709a6648ff23c5aa01843e7e9bc6146408893d | refs/heads/master | 2020-04-18T04:50:07.725509 | 2019-01-27T08:31:16 | 2019-01-27T08:31:16 | null | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 178 | cpp | // stdafx.cpp : 僅包含標準 Include 檔的原始程式檔
// Course.pch 會成為先行編譯標頭檔
// stdafx.obj 會包含先行編譯型別資訊
#include "stdafx.h"
| [
"38403949+lin60102@users.noreply.github.com"
] | 38403949+lin60102@users.noreply.github.com |
685279bc070782065e1484fa6d5b323b9b2aef30 | 23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f | /Windows API函数参考手册/第05章位图和图标/5.2创建和撤销位图、图标/5_2_1_4/5_2_1_4.cpp | 380db3c005d5049c4c24172f0f3159b96b4da077 | [] | no_license | IgorYunusov/Mega-collection-cpp-1 | c7c09e3c76395bcbf95a304db6462a315db921ba | 42d07f16a379a8093b6ddc15675bf777eb10d480 | refs/heads/master | 2020-03-24T10:20:15.783034 | 2018-06-12T13:19:05 | 2018-06-12T13:19:05 | 142,653,486 | 3 | 1 | null | 2018-07-28T06:36:35 | 2018-07-28T06:36:35 | null | GB18030 | C++ | false | false | 6,228 | cpp | // 5_2_1_4.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "resource.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text
// Foward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_MY5_2_1_4, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow)) {
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_MY5_2_1_4);
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0)) {
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage is only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_MY5_2_1_4);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = (LPCSTR)IDC_MY5_2_1_4;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HANDLE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd) {
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
TCHAR szHello[MAX_LOADSTRING];
LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);
switch (message) {
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId) {
case IDM_ABOUT:
DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
break;
case WM_LBUTTONDOWN:
BITMAPINFO* pbi;
HDC hDC;
HBITMAP hBitmap;
BYTE* pMem, *pBits;
pMem = (BYTE*)malloc(sizeof(BITMAPINFOHEADER) + 32 * 32 * 4);
pbi = (BITMAPINFO*)pMem;
pBits = (BYTE*)malloc(32 * 32 * 4);
int i, j;
//初始化位图的位数据
for (i = 0; i < 32; i++)
for (j = 0; j < 32 * 4; j = j + 4) {
pBits[i * 32 * 4 + j] = 0;
pBits[i * 32 * 4 + j + 1] = i * 3 + j * 2;
pBits[i * 32 * 4 + j + 2] = i * 5 + j;
pBits[i * 32 * 4 + j + 3] = j * 2;
}
pbi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbi->bmiHeader.biHeight = 32;
pbi->bmiHeader.biWidth = 32;
pbi->bmiHeader.biPlanes = 1;
pbi->bmiHeader.biBitCount = 32;
pbi->bmiHeader.biCompression = BI_RGB;
hDC = GetDC(hWnd);
//由于位图的每个像素有32位,所以它忽略了pbi->bmiColors所指定的颜色,即位图的数据自身
//对于表示颜色来说已经足够,不用再用索引了。
hBitmap = CreateDIBitmap(hDC, &pbi->bmiHeader, CBM_INIT, pBits, pbi, DIB_RGB_COLORS);
//在窗口上绘制此位图
DrawState(hDC, NULL, NULL, (LPARAM)hBitmap, 0, 30, 20, 0, 0, DST_BITMAP);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Mesage handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) {
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {
EndDialog(hDlg, LOWORD(wParam));
return TRUE;
}
break;
}
return FALSE;
}
| [
"wyrover@gmail.com"
] | wyrover@gmail.com |
d9c12df049925b9195ab1041d3c8da53a6655b90 | 0f398c8beaebd61d43dd575ef2cfa34122775676 | /src/hos.cpp | d8dc25e0ce8dd46dbeda0722a6c6349ca5cd3b12 | [] | no_license | storrellas/hosSmartHome | 8eedecfa5ef43276ad8dc594718a041e9e977139 | 45fb9a9b441c4d175d54a2b2bb35b4e763c09c9c | refs/heads/master | 2021-01-10T22:06:13.658552 | 2015-11-06T14:46:50 | 2015-11-06T14:46:50 | 28,671,619 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,053 | cpp | /****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "hos.h"
#include <QtGui>
#include <cmath>
#define SELECTION_NUMBER 8
#define FULL_CIRCLE 360
/********************************************************************
Function: HoS
Overview: Public constructor
********************************************************************/
HoS::HoS(QWidget *parent) : QWidget(parent)
{
this->timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
// Initialise the angle to 0
this->currentAngle = 0;
}
/********************************************************************
Function: getHoSState
Overview: gets whether the HoS is enabled or disabled
********************************************************************/
bool HoS::getHoSState(){
return timer->isActive();
}
/********************************************************************
Function: enableTurn
Overview: Starts the Hex-O-Select
********************************************************************/
bool HoS::enableTurn(){
this->timer->start(200);
return true;
}
/********************************************************************
Function: disableTurn
Overview: Stops the Hex-O-Select
********************************************************************/
bool HoS::disableTurn(){
this->timer->stop();
return true;
}
/********************************************************************
Function: getCurrentAngle
Overview: returns the current angle
********************************************************************/
int HoS::getCurrentAngle(){
return this->currentAngle;
}
/********************************************************************
Function: getCurrentSelection
Overview: returns the current selected option
********************************************************************/
int HoS::getCurrentSelection(){
int anglePerSelection = FULL_CIRCLE/SELECTION_NUMBER;
int selection =(int) this->currentAngle/anglePerSelection;
return selection;
}
/********************************************************************
Function: paintEvent
Overview: Paints forms in the widget
********************************************************************/
void HoS::paintEvent(QPaintEvent *)
{
// Iterator
int i = 0;
// Configure canvas
int side = qMin(width(), height());
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() / 2);
painter.scale(side / 250.0, side / 250.0);
// // Draw Circle
// // -----------
// static const int radiusHOS = 80;
///*
// QPoint square[4];
// painter.save();
// painter.setBrush(Qt::transparent);
// painter.setPen(Qt::black);
// square[0] = QPoint(0,0);
// square[1] = QPoint(radiusHOS,0);
// square[2] = QPoint(radiusHOS,radiusHOS);
// square[3] = QPoint(0,radiusHOS);
// painter.drawConvexPolygon(square, 4);
// painter.restore();
///**/
// int nPoints = 82;
// QPoint circle[nPoints];
// painter.save();
// painter.setBrush(Qt::transparent);
// painter.setPen(Qt::black);
// circle[0] = QPoint(0,0);
// for ( i = 1; i < nPoints-1; i++){
// circle[i] = QPoint(i, sqrt( (radiusHOS*radiusHOS)-(i*i) ));
// qDebug() << "i:" << i << " y:" << sqrt( (radiusHOS*radiusHOS)-(i*i) );
// }
// painter.drawConvexPolygon(circle, nPoints);
// painter.restore();
// return;
// Arrow painting
// --------------
static const QColor arrowColor(0, 0, 0,197);
painter.setPen(arrowColor);
painter.setBrush(arrowColor);
static const QPoint arrow[] = {
QPoint(5, 8),
QPoint(5, -40),
QPoint(10, -40),
QPoint(0, -50),
QPoint(-10, -40),
QPoint(-5, -40),
QPoint(-5, 8)
};
painter.save();
this->currentAngle+=1;
if(this->currentAngle >= 360) this->currentAngle = 0;
painter.rotate(this->currentAngle);
painter.drawConvexPolygon(arrow, 7);
painter.restore();
}
| [
"storrellas@gmail.com"
] | storrellas@gmail.com |
12db8a0f9cde3f4dea88c9179d45b382140b6f6b | 6bc086d87ed9ecff2a9fd9f53b64a815c38f0263 | /SudokuC++/board.cpp | b6dc61070efe88676ae0fda5d6a904a73a7a3f87 | [] | no_license | dennist-tran/SudokuCpp | 81ba29302f0d9219e809e3c41bc330218ede7952 | 41dccff00102c50dcfacacc7477881f28840ddce | refs/heads/master | 2023-08-23T09:58:30.004190 | 2021-10-26T02:07:54 | 2021-10-26T02:07:54 | 416,596,947 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | #include <iostream>
using namespace std;
void printBoard(int board[9][9])
{
for(int row = 0; row < 9; row++)
{
for(int col = 0; col < 9; col++)
{
if (col == 3 || col == 6)
std::cout << "|" << " ";
std::cout << board[row][col] << " ";
}
std::cout << std::endl;
if (row == 2 || row == 5)
std::cout << "------+-------+-------" << std::endl;
}
}
bool checkValid(int board[9][9], int row, int col, int value)
{
int box_x = (col / 3) * 3;
int box_y = (row / 3) * 3;
for (int i = 0; i < 9; i++)
{
if (board[row][i] == value) return false;
if (board[i][col] == value) return false;
if (board[box_y + i / 3][box_x + i % 3] == value) return false;
}
return true;
}
bool addValue(int board[9][9], int row, int col, int value)
{
if (!checkValid(board, row, col, value)) return false;
board[row][col] = value;
return true;
}
void copyBoard(int board[9][9], int copy[9][9])
{
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
copy[i][j] = board[i][j];
}
bool validateBoard(int board[9][9])
{
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
if (board[i][j] != 0)
{
int value = board[i][j];
board[i][j] = 0;
if (!checkValid(board, i, j, value))
{
board[i][j] = value;
return false;
}
board[i][j] = value;
}
return true;
}
| [
"42656976+BoxOfPencils@users.noreply.github.com"
] | 42656976+BoxOfPencils@users.noreply.github.com |
04e10d43ebfe5f8d454d59c5cc703716e632311b | 844969bd953d7300f02172c867725e27b518c08e | /SDK/GHLetter_ExclusionEntitlement_Campaign027_functions.cpp | 0540b27d831b16881417f97183d340d8732677cc | [] | no_license | zanzo420/SoT-Python-Offset-Finder | 70037c37991a2df53fa671e3c8ce12c45fbf75a5 | d881877da08b5c5beaaca140f0ab768223b75d4d | refs/heads/main | 2023-07-18T17:25:01.596284 | 2021-09-09T12:31:51 | 2021-09-09T12:31:51 | 380,604,174 | 0 | 0 | null | 2021-06-26T22:07:04 | 2021-06-26T22:07:03 | null | UTF-8 | C++ | false | false | 600 | cpp | // Name: SoT, Version: 2.2.1.1
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
void UGHLetter_ExclusionEntitlement_Campaign027_C::AfterRead()
{
UEntitlementDesc::AfterRead();
}
void UGHLetter_ExclusionEntitlement_Campaign027_C::BeforeDelete()
{
UEntitlementDesc::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"51171051+DougTheDruid@users.noreply.github.com"
] | 51171051+DougTheDruid@users.noreply.github.com |
aa10db08cf980d5e2dea8e4821bc1f4f4047dbeb | ba4db75b9d1f08c6334bf7b621783759cd3209c7 | /src_main/game/client/dod/VGUI/dodcornercutpanel.h | 71146fb0ac843b660cab239515e53af6f449f44d | [] | no_license | equalent/source-2007 | a27326c6eb1e63899e3b77da57f23b79637060c0 | d07be8d02519ff5c902e1eb6430e028e1b302c8b | refs/heads/master | 2020-03-28T22:46:44.606988 | 2017-03-27T18:05:57 | 2017-03-27T18:05:57 | 149,257,460 | 2 | 0 | null | 2018-09-18T08:52:10 | 2018-09-18T08:52:09 | null | WINDOWS-1252 | C++ | false | false | 1,770 | h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef DOD_CORNERCUTPANEL_H
#define DOD_CORNERCUTPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "cbase.h"
#include <vgui_controls/EditablePanel.h>
#include <vgui/isurface.h>
#include "dod_shareddefs.h"
//-----------------------------------------------------------------------------
// Purpose: Draws the corner-cut background panels
//-----------------------------------------------------------------------------
class CDoDCutEditablePanel : public vgui::EditablePanel
{
public:
DECLARE_CLASS_SIMPLE( CDoDCutEditablePanel, vgui::EditablePanel );
CDoDCutEditablePanel( vgui::Panel *parent, const char *name );
virtual void PaintBackground();
virtual void SetBorder( vgui::IBorder *border );
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void SetVisible( bool state )
{
BaseClass::SetVisible( state );
}
virtual void ApplySettings( KeyValues *inResourceData );
virtual void GetSettings( KeyValues *outResourceData );
virtual void SetCornerToCut( int nCorner ){ m_nCornerToCut = nCorner; }
virtual void SetCornerCutSize( int nCutSize ){ m_nCornerCutSize = nCutSize; }
virtual void SetBackGroundColor( const char *pszNewColor );
virtual void SetBorderColor( const char *pszNewColor );
private:
int m_iBackgroundTexture;
int m_nCornerToCut;
int m_nCornerCutSize;
char m_szBackgroundTexture[128];
char m_szBackgroudColor[128];
char m_szBorderColor[128];
Color m_clrBackground;
Color m_clrBorder;
};
#endif // DOD_CORNERCUTPANEL_H
| [
"sean@csnxs.uk"
] | sean@csnxs.uk |
9beeadf40eb445807b7a43cf1886f049cca5bf43 | d5d94c992d0596080ba694c518dfdb58d3490847 | /1433/answer.cpp | 04d6019e9663dac02ba5555f858e625ce8d341a6 | [] | no_license | calgagi/leetcode | 1bf24b750e44c2c893935983e5d88e0f071d9f2d | 431aba979d92e331f2f92a07eb80167a823a49bd | refs/heads/master | 2022-11-17T11:26:01.596496 | 2020-07-19T06:56:04 | 2020-07-19T06:56:04 | 276,207,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | cpp | class Solution {
public:
bool checkIfCanBreak(string s1, string s2) {
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
int n = s1.length();
bool g1 = 1, g2 = 1;
for (int i = 0; i < n; i++) {
if (s1[i] > s2[i]) {
g1 = 0;
} else if (s1[i] < s2[i]) {
g2 = 0;
}
}
return g1 || g2;
}
};
| [
"calgagi@gmail.com"
] | calgagi@gmail.com |
55383b0ea9d62787edc569d51bb02cb86bd17ac6 | 0865e654df8684a4cb137e8a6de0007e1583629c | /vendor/grpc/grpc/include/grpc++/impl/codegen/time.h | 81ca7bb3dec6376dd9e9d803db7a023620b50648 | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bakins/grpc-fastcgi-example | f0e6cf3056c76d3991824e4ea7d9343ed926b65d | 83e89ff1b69d6e31de1ed24bfd35c33efaea7e2f | refs/heads/master | 2022-03-15T01:04:41.240887 | 2022-02-15T17:24:25 | 2022-02-15T17:24:25 | 101,287,872 | 1 | 1 | Apache-2.0 | 2022-02-15T17:24:26 | 2017-08-24T11:31:25 | PHP | UTF-8 | C++ | false | false | 3,515 | h | /*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPCXX_IMPL_CODEGEN_TIME_H
#define GRPCXX_IMPL_CODEGEN_TIME_H
#include <grpc++/impl/codegen/config.h>
#include <grpc/impl/codegen/grpc_types.h>
namespace grpc {
/** If you are trying to use CompletionQueue::AsyncNext with a time class that
isn't either gpr_timespec or std::chrono::system_clock::time_point, you
will most likely be looking at this comment as your compiler will have
fired an error below. In order to fix this issue, you have two potential
solutions:
1. Use gpr_timespec or std::chrono::system_clock::time_point instead
2. Specialize the TimePoint class with whichever time class that you
want to use here. See below for two examples of how to do this.
*/
template <typename T>
class TimePoint {
public:
TimePoint(const T& time) { you_need_a_specialization_of_TimePoint(); }
gpr_timespec raw_time() {
gpr_timespec t;
return t;
}
private:
void you_need_a_specialization_of_TimePoint();
};
template <>
class TimePoint<gpr_timespec> {
public:
TimePoint(const gpr_timespec& time) : time_(time) {}
gpr_timespec raw_time() { return time_; }
private:
gpr_timespec time_;
};
} // namespace grpc
#include <chrono>
#include <grpc/impl/codegen/grpc_types.h>
namespace grpc {
// from and to should be absolute time.
void Timepoint2Timespec(const std::chrono::system_clock::time_point& from,
gpr_timespec* to);
void TimepointHR2Timespec(
const std::chrono::high_resolution_clock::time_point& from,
gpr_timespec* to);
std::chrono::system_clock::time_point Timespec2Timepoint(gpr_timespec t);
template <>
class TimePoint<std::chrono::system_clock::time_point> {
public:
TimePoint(const std::chrono::system_clock::time_point& time) {
Timepoint2Timespec(time, &time_);
}
gpr_timespec raw_time() const { return time_; }
private:
gpr_timespec time_;
};
} // namespace grpc
#endif // GRPCXX_IMPL_CODEGEN_TIME_H
| [
"bakins@rsglab.com"
] | bakins@rsglab.com |
12bf85f257b28d99ad87c06c92c115b566ea45f6 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/LArCalorimeter/LArRawConditions/src/LArShapeMC.cxx | 858b8ed66948d1a3bfe2bc7469c1af07e519d573 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,157 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "LArRawConditions/LArShapeMC.h"
#include "AthenaKernel/getMessageSvc.h"
#include "GaudiKernel/IMessageSvc.h"
#include "GaudiKernel/Bootstrap.h"
#include "GaudiKernel/ISvcLocator.h"
#include "GaudiKernel/IToolSvc.h"
#include "AthenaKernel/getMessageSvc.h"
#include "GaudiKernel/MsgStream.h"
#include "LArElecCalib/ILArMCSymTool.h"
#include <iostream>
using namespace std ;
LArShapeMC::LArShapeMC() : ILArShape(),
LArConditionsContainer<LArShapeP1>(),
m_larmcsym("LArMCSymTool")
{}
StatusCode LArShapeMC::initialize()
{
if(m_larmcsym.retrieve().isFailure()){
MsgStream log(Athena::getMessageSvc(), "LArRampMC");
log << MSG::WARNING << "Could not retrieve LArMCSymTool " << endreq;
return (StatusCode::FAILURE);
}
return (CONTAINER::initialize());
}
LArShapeMC::~LArShapeMC() {}
namespace {
void do_get_shape (const std::vector<float>& shape,
const HWIdentifier& CellID,
int tbin,
int mode,
bool flag,
std::vector<float>& v)
{
v.clear();
if( shape.size() == 0 ){
MsgStream logstr(Athena::getMessageSvc(), "LArShapeComplete");
logstr << MSG::DEBUG << "Invalid ID 0x" << MSG::hex << CellID
<< MSG::dec << endreq;
return;
}
//int NOFCPhases = 25;
//int NOFCTimeBins = 25;
int NOFCPhases = 50; // not really used in current implementation
int NOFCTimeBins = 24; // fits to CTB/P3C data
if ( mode == 10 ) { /* 10 = H8 CTB 2004 RTM OFC */
// Keep this old implementation for mode==10 only.
NOFCPhases = 50 ;
NOFCTimeBins = 24 ;
unsigned int MaxSamples = NOFCTimeBins * 5 + ( NOFCPhases - NOFCTimeBins );
if ( tbin >= NOFCPhases) { /* invalid tbin: return empty vector */
MsgStream logstr(Athena::getMessageSvc(), "LArShapeComplete");
logstr << MSG::ERROR << " LArShapeComplete: Invalid tbin " << tbin
<< " for cell 0x " << MSG::hex << CellID << MSG::dec << endreq;
}
else if ( shape.size() < MaxSamples ) {
MsgStream logstr(Athena::getMessageSvc(), "LArShapeComplete");
logstr << MSG::WARNING
<< "stored vector is too small for TB mode" << endreq;
}
else {
int min = 0, max = 5;
// ??? Does the flag=true behavior make sense?
if (shape.size() > (flag ? MaxSamples : NOFCPhases)) {
min = 1;
max = 6;
}
for (int i=min;i<max;i++) {
v.push_back (shape[i*NOFCTimeBins+tbin]);
}
}
} else
{
// new implementation, as discussed in April 2006.
// return all possible samples spaced by 25ns (32 samples)
// tbin>0 gives earlier pulse.
// tbin is not restricted to be less 25ns.
unsigned int size = shape.size();
for (unsigned int i = 0; i< size ; i += NOFCTimeBins )
{
unsigned int j = i+tbin ;
if( j > size )
v.push_back(0);
else
v.push_back(shape[j]);
}
}
}
#if 0
bool setup_cabling_service (const Identifier& CellID,
HWIdentifier& OnId)
{
ISvcLocator* svcLoc = Gaudi::svcLocator( );
IToolSvc* toolSvc;
StatusCode sc = svcLoc->service( "ToolSvc",toolSvc );
if(sc.isFailure()) {
MsgStream logstr(Athena::getMessageSvc(), "LArShapeMC");
logstr << MSG::ERROR << "Could not retrieve ToolSvc " << endreq;
return false;
}
LArCablingService* cablingService;
sc = toolSvc->retrieveTool("LArCablingService",cablingService);
if(sc.isFailure()){
MsgStream logstr(Athena::getMessageSvc(), "LArShapeMC");
logstr << MSG::ERROR << "Could not retrieve LArCablingService Tool "
<< endreq;
return false;
}
OnId = cablingService->createSignalChannelID(CellID);
return true;
}
#endif
} // anonymous namespace
/*
* retrieve Shape
*/
LArShapeMC::ShapeRef_t
LArShapeMC::Shape(const HWIdentifier& CellID,
int gain,
int tbin=0,
int mode=0 ) const
{
static std::vector<float> v;
HWIdentifier SymCellID = m_larmcsym->symOnline(CellID);
do_get_shape (get(SymCellID, gain).m_vShape, CellID, tbin, mode, false, v);
return v;
}
LArShapeMC::ShapeRef_t
LArShapeMC::ShapeDer(const HWIdentifier& CellID,
int gain,
int tbin=0,
int mode=0 ) const
{
static std::vector<float> v;
HWIdentifier SymCellID = m_larmcsym->symOnline(CellID);
do_get_shape (get(SymCellID, gain).m_vShapeDer, CellID, tbin, mode, true, v);
return v;
}
LArShapeMC::ShapeRef_t
LArShapeMC::Shape(const Identifier& CellID,
int gain,
int tbin=0,
int mode=0 ) const
{
HWIdentifier SymCellID = m_larmcsym->symOnline(CellID);
return Shape(SymCellID, gain, tbin, mode);
}
LArShapeMC::ShapeRef_t
LArShapeMC::ShapeDer(const Identifier& CellID,
int gain,
int tbin=0,
int mode=0) const
{
HWIdentifier SymCellID = m_larmcsym->symOnline(CellID);
return ShapeDer(SymCellID, gain, tbin, mode);
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
d84d592ebbdb414e4202210864f07a2623004bac | 0788948772b14389f147b0d7c66d921978b14ff3 | /xyzeval/include/utils.hpp | 8bfb714e882dbdbf43e8f1ecb190ea7e5571be52 | [
"MIT"
] | permissive | elor/xyzutils | f796a87ca92097183971703f149e6ad8e3af08ed | 5888f5a27ca3ba91c2a483c9b44d1ce0dbdb5d88 | refs/heads/master | 2020-05-31T15:04:09.210430 | 2014-08-28T14:02:22 | 2014-08-28T14:02:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | hpp | /*
* utils.h
*
* Created on: Oct 9, 2013
* Author: elor
*/
#ifndef UTILS_H_
#define UTILS_H_
#include <string>
#include <vector>
std::vector<std::string> strsplit(std::string str);
std::vector<std::string> strsplit(const char *str);
#endif /* UTILS_H_ */
| [
"elor@hrz.tu-chemnitz.de"
] | elor@hrz.tu-chemnitz.de |
ba6c2deec9795557acd5f88e6dd570994da6413e | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-qt5/generated/client/OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties.h | 03d8b05cc1a49e4e87da17a0c45b907c6c612e8d | [
"Apache-2.0"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 1,687 | h | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties.h
*
*
*/
#ifndef OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties_H_
#define OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties_H_
#include <QJsonObject>
#include "OAIOAIConfigNodePropertyString.h"
#include "OAIObject.h"
namespace OpenAPI {
class OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties: public OAIObject {
public:
OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties();
OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties(QString json);
~OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties();
void init();
void cleanup();
QString asJson () override;
QJsonObject asJsonObject() override;
void fromJsonObject(QJsonObject json) override;
OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties* fromJson(QString jsonString) override;
OAIConfigNodePropertyString* getPipelineType();
void setPipelineType(OAIConfigNodePropertyString* pipeline_type);
virtual bool isSet() override;
private:
OAIConfigNodePropertyString* pipeline_type;
bool m_pipeline_type_isSet;
};
}
#endif /* OAIComAdobeCqDamCfmImplContentRewriterParRangeFilterProperties_H_ */
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
0f78b47b3508efc03907e8e595ad46e43218b470 | ac8e27210d8ae1c79e7d0d9db1bcf4e31c737718 | /tools/clang/lib/CodeGen/CodeGenModule.cpp | 1fd4e4cf8b8fe443dc64c055c44937e0dd7e4e2b | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | steleman/flang9 | d583d619bfb67d27a995274e30c8c1a642696ec1 | 4ad7c213b30422e1e0fcb3ac826640d576977d04 | refs/heads/master | 2020-11-27T09:50:18.644313 | 2020-03-07T14:37:32 | 2020-03-07T14:37:32 | 229,387,867 | 0 | 0 | Apache-2.0 | 2019-12-21T06:35:35 | 2019-12-21T06:35:34 | null | UTF-8 | C++ | false | false | 224,457 | cpp | //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This coordinates the per-module state used while generating code.
//
//===----------------------------------------------------------------------===//
#include "CodeGenModule.h"
#include "CGBlocks.h"
#include "CGCUDARuntime.h"
#include "CGCXXABI.h"
#include "CGCall.h"
#include "CGDebugInfo.h"
#include "CGObjCRuntime.h"
#include "CGOpenCLRuntime.h"
#include "CGOpenMPRuntime.h"
#include "CGOpenMPRuntimeNVPTX.h"
#include "CodeGenFunction.h"
#include "CodeGenPGO.h"
#include "ConstantEmitter.h"
#include "CoverageMappingGen.h"
#include "TargetInfo.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ProfileSummary.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/TimeProfiler.h"
using namespace clang;
using namespace CodeGen;
static llvm::cl::opt<bool> LimitedCoverage(
"limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
llvm::cl::init(false));
static const char AnnotationSection[] = "llvm.metadata";
static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
switch (CGM.getTarget().getCXXABI().getKind()) {
case TargetCXXABI::GenericAArch64:
case TargetCXXABI::GenericARM:
case TargetCXXABI::iOS:
case TargetCXXABI::iOS64:
case TargetCXXABI::WatchOS:
case TargetCXXABI::GenericMIPS:
case TargetCXXABI::GenericItanium:
case TargetCXXABI::WebAssembly:
return CreateItaniumCXXABI(CGM);
case TargetCXXABI::Microsoft:
return CreateMicrosoftCXXABI(CGM);
}
llvm_unreachable("invalid C++ ABI kind");
}
CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
const PreprocessorOptions &PPO,
const CodeGenOptions &CGO, llvm::Module &M,
DiagnosticsEngine &diags,
CoverageSourceInfo *CoverageInfo)
: Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
VMContext(M.getContext()), Types(*this), VTables(*this),
SanitizerMD(new SanitizerMetadata(*this)) {
// Initialize the type cache.
llvm::LLVMContext &LLVMContext = M.getContext();
VoidTy = llvm::Type::getVoidTy(LLVMContext);
Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
HalfTy = llvm::Type::getHalfTy(LLVMContext);
FloatTy = llvm::Type::getFloatTy(LLVMContext);
DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
PointerAlignInBytes =
C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
SizeSizeInBytes =
C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
IntAlignInBytes =
C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
IntPtrTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getMaxPointerWidth());
Int8PtrTy = Int8Ty->getPointerTo(0);
Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
AllocaInt8PtrTy = Int8Ty->getPointerTo(
M.getDataLayout().getAllocaAddrSpace());
ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
if (LangOpts.ObjC)
createObjCRuntime();
if (LangOpts.OpenCL)
createOpenCLRuntime();
if (LangOpts.OpenMP)
createOpenMPRuntime();
if (LangOpts.CUDA)
createCUDARuntime();
// Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
(!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
getCXXABI().getMangleContext()));
// If debug info or coverage generation is enabled, create the CGDebugInfo
// object.
if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
DebugInfo.reset(new CGDebugInfo(*this));
Block.GlobalUniqueCount = 0;
if (C.getLangOpts().ObjC)
ObjCData.reset(new ObjCEntrypoints());
if (CodeGenOpts.hasProfileClangUse()) {
auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
if (auto E = ReaderOrErr.takeError()) {
unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
"Could not read profile %0: %1");
llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
<< EI.message();
});
} else
PGOReader = std::move(ReaderOrErr.get());
}
// If coverage mapping generation is enabled, create the
// CoverageMappingModuleGen object.
if (CodeGenOpts.CoverageMapping)
CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
}
CodeGenModule::~CodeGenModule() {}
void CodeGenModule::createObjCRuntime() {
// This is just isGNUFamily(), but we want to force implementors of
// new ABIs to decide how best to do this.
switch (LangOpts.ObjCRuntime.getKind()) {
case ObjCRuntime::GNUstep:
case ObjCRuntime::GCC:
case ObjCRuntime::ObjFW:
ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
return;
case ObjCRuntime::FragileMacOSX:
case ObjCRuntime::MacOSX:
case ObjCRuntime::iOS:
case ObjCRuntime::WatchOS:
ObjCRuntime.reset(CreateMacObjCRuntime(*this));
return;
}
llvm_unreachable("bad runtime kind");
}
void CodeGenModule::createOpenCLRuntime() {
OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
}
void CodeGenModule::createOpenMPRuntime() {
// Select a specialized code generation class based on the target, if any.
// If it does not exist use the default implementation.
switch (getTriple().getArch()) {
case llvm::Triple::nvptx:
case llvm::Triple::nvptx64:
assert(getLangOpts().OpenMPIsDevice &&
"OpenMP NVPTX is only prepared to deal with device code.");
OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
break;
default:
if (LangOpts.OpenMPSimd)
OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
else
OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
break;
}
}
void CodeGenModule::createCUDARuntime() {
CUDARuntime.reset(CreateNVCUDARuntime(*this));
}
void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
Replacements[Name] = C;
}
void CodeGenModule::applyReplacements() {
for (auto &I : Replacements) {
StringRef MangledName = I.first();
llvm::Constant *Replacement = I.second;
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (!Entry)
continue;
auto *OldF = cast<llvm::Function>(Entry);
auto *NewF = dyn_cast<llvm::Function>(Replacement);
if (!NewF) {
if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
} else {
auto *CE = cast<llvm::ConstantExpr>(Replacement);
assert(CE->getOpcode() == llvm::Instruction::BitCast ||
CE->getOpcode() == llvm::Instruction::GetElementPtr);
NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
}
}
// Replace old with new, but keep the old order.
OldF->replaceAllUsesWith(Replacement);
if (NewF) {
NewF->removeFromParent();
OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
NewF);
}
OldF->eraseFromParent();
}
}
void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
GlobalValReplacements.push_back(std::make_pair(GV, C));
}
void CodeGenModule::applyGlobalValReplacements() {
for (auto &I : GlobalValReplacements) {
llvm::GlobalValue *GV = I.first;
llvm::Constant *C = I.second;
GV->replaceAllUsesWith(C);
GV->eraseFromParent();
}
}
// This is only used in aliases that we created and we know they have a
// linear structure.
static const llvm::GlobalObject *getAliasedGlobal(
const llvm::GlobalIndirectSymbol &GIS) {
llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
const llvm::Constant *C = &GIS;
for (;;) {
C = C->stripPointerCasts();
if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
return GO;
// stripPointerCasts will not walk over weak aliases.
auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
if (!GIS2)
return nullptr;
if (!Visited.insert(GIS2).second)
return nullptr;
C = GIS2->getIndirectSymbol();
}
}
void CodeGenModule::checkAliases() {
// Check if the constructed aliases are well formed. It is really unfortunate
// that we have to do this in CodeGen, but we only construct mangled names
// and aliases during codegen.
bool Error = false;
DiagnosticsEngine &Diags = getDiags();
for (const GlobalDecl &GD : Aliases) {
const auto *D = cast<ValueDecl>(GD.getDecl());
SourceLocation Location;
bool IsIFunc = D->hasAttr<IFuncAttr>();
if (const Attr *A = D->getDefiningAttr())
Location = A->getLocation();
else
llvm_unreachable("Not an alias or ifunc?");
StringRef MangledName = getMangledName(GD);
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
if (!GV) {
Error = true;
Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
} else if (GV->isDeclaration()) {
Error = true;
Diags.Report(Location, diag::err_alias_to_undefined)
<< IsIFunc << IsIFunc;
} else if (IsIFunc) {
// Check resolver function type.
llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
GV->getType()->getPointerElementType());
assert(FTy);
if (!FTy->getReturnType()->isPointerTy())
Diags.Report(Location, diag::err_ifunc_resolver_return);
}
llvm::Constant *Aliasee = Alias->getIndirectSymbol();
llvm::GlobalValue *AliaseeGV;
if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
else
AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
StringRef AliasSection = SA->getName();
if (AliasSection != AliaseeGV->getSection())
Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
<< AliasSection << IsIFunc << IsIFunc;
}
// We have to handle alias to weak aliases in here. LLVM itself disallows
// this since the object semantics would not match the IL one. For
// compatibility with gcc we implement it by just pointing the alias
// to its aliasee's aliasee. We also warn, since the user is probably
// expecting the link to be weak.
if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
if (GA->isInterposable()) {
Diags.Report(Location, diag::warn_alias_to_weak_alias)
<< GV->getName() << GA->getName() << IsIFunc;
Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
GA->getIndirectSymbol(), Alias->getType());
Alias->setIndirectSymbol(Aliasee);
}
}
}
if (!Error)
return;
for (const GlobalDecl &GD : Aliases) {
StringRef MangledName = getMangledName(GD);
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
Alias->eraseFromParent();
}
}
void CodeGenModule::clear() {
DeferredDeclsToEmit.clear();
if (OpenMPRuntime)
OpenMPRuntime->clear();
}
void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
StringRef MainFile) {
if (!hasDiagnostics())
return;
if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
if (MainFile.empty())
MainFile = "<stdin>";
Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
} else {
if (Mismatched > 0)
Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
if (Missing > 0)
Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
}
}
void CodeGenModule::Release() {
EmitDeferred();
EmitVTablesOpportunistically();
applyGlobalValReplacements();
applyReplacements();
checkAliases();
emitMultiVersionFunctions();
EmitCXXGlobalInitFunc();
EmitCXXGlobalDtorFunc();
registerGlobalDtorsWithAtExit();
EmitCXXThreadLocalInitFunc();
if (ObjCRuntime)
if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
AddGlobalCtor(ObjCInitFunction);
if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
CUDARuntime) {
if (llvm::Function *CudaCtorFunction =
CUDARuntime->makeModuleCtorFunction())
AddGlobalCtor(CudaCtorFunction);
}
if (OpenMPRuntime) {
if (llvm::Function *OpenMPRequiresDirectiveRegFun =
OpenMPRuntime->emitRequiresDirectiveRegFun()) {
AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
}
if (llvm::Function *OpenMPRegistrationFunction =
OpenMPRuntime->emitRegistrationFunction()) {
auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
OpenMPRegistrationFunction : nullptr;
AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
}
OpenMPRuntime->clear();
}
if (PGOReader) {
getModule().setProfileSummary(
PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
llvm::ProfileSummary::PSK_Instr);
if (PGOStats.hasDiagnostics())
PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
}
EmitCtorList(GlobalCtors, "llvm.global_ctors");
EmitCtorList(GlobalDtors, "llvm.global_dtors");
EmitGlobalAnnotations();
EmitStaticExternCAliases();
EmitDeferredUnusedCoverageMappings();
if (CoverageMapping)
CoverageMapping->emit();
if (CodeGenOpts.SanitizeCfiCrossDso) {
CodeGenFunction(*this).EmitCfiCheckFail();
CodeGenFunction(*this).EmitCfiCheckStub();
}
emitAtAvailableLinkGuard();
emitLLVMUsed();
if (SanStats)
SanStats->finish();
if (CodeGenOpts.Autolink &&
(Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
EmitModuleLinkOptions();
}
// On ELF we pass the dependent library specifiers directly to the linker
// without manipulating them. This is in contrast to other platforms where
// they are mapped to a specific linker option by the compiler. This
// difference is a result of the greater variety of ELF linkers and the fact
// that ELF linkers tend to handle libraries in a more complicated fashion
// than on other platforms. This forces us to defer handling the dependent
// libs to the linker.
//
// CUDA/HIP device and host libraries are different. Currently there is no
// way to differentiate dependent libraries for host or device. Existing
// usage of #pragma comment(lib, *) is intended for host libraries on
// Windows. Therefore emit llvm.dependent-libraries only for host.
if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
for (auto *MD : ELFDependentLibraries)
NMD->addOperand(MD);
}
// Record mregparm value now so it is visible through rest of codegen.
if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
CodeGenOpts.NumRegisterParameters);
if (CodeGenOpts.DwarfVersion) {
// We actually want the latest version when there are conflicts.
// We can change from Warning to Latest if such mode is supported.
getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
CodeGenOpts.DwarfVersion);
}
if (CodeGenOpts.EmitCodeView) {
// Indicate that we want CodeView in the metadata.
getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
}
if (CodeGenOpts.CodeViewGHash) {
getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
}
if (CodeGenOpts.ControlFlowGuard) {
// We want function ID tables for Control Flow Guard.
getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
}
if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
// We don't support LTO with 2 with different StrictVTablePointers
// FIXME: we could support it by stripping all the information introduced
// by StrictVTablePointers.
getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
llvm::Metadata *Ops[2] = {
llvm::MDString::get(VMContext, "StrictVTablePointers"),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt32Ty(VMContext), 1))};
getModule().addModuleFlag(llvm::Module::Require,
"StrictVTablePointersRequirement",
llvm::MDNode::get(VMContext, Ops));
}
if (DebugInfo)
// We support a single version in the linked module. The LLVM
// parser will drop debug info with a different version number
// (and warn about it, too).
getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
llvm::DEBUG_METADATA_VERSION);
// We need to record the widths of enums and wchar_t, so that we can generate
// the correct build attributes in the ARM backend. wchar_size is also used by
// TargetLibraryInfo.
uint64_t WCharWidth =
Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
if ( Arch == llvm::Triple::arm
|| Arch == llvm::Triple::armeb
|| Arch == llvm::Triple::thumb
|| Arch == llvm::Triple::thumbeb) {
// The minimum width of an enum in bytes
uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
}
if (CodeGenOpts.SanitizeCfiCrossDso) {
// Indicate that we want cross-DSO control flow integrity checks.
getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
}
if (CodeGenOpts.CFProtectionReturn &&
Target.checkCFProtectionReturnSupported(getDiags())) {
// Indicate that we want to instrument return control flow protection.
getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
1);
}
if (CodeGenOpts.CFProtectionBranch &&
Target.checkCFProtectionBranchSupported(getDiags())) {
// Indicate that we want to instrument branch control flow protection.
getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
1);
}
if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
// Indicate whether __nvvm_reflect should be configured to flush denormal
// floating point values to 0. (This corresponds to its "__CUDA_FTZ"
// property.)
getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
CodeGenOpts.FlushDenorm ? 1 : 0);
}
// Emit OpenCL specific module metadata: OpenCL/SPIR version.
if (LangOpts.OpenCL) {
EmitOpenCLMetadata();
// Emit SPIR version.
if (getTriple().isSPIR()) {
// SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
// opencl.spir.version named metadata.
// C++ is backwards compatible with OpenCL v2.0.
auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
llvm::Metadata *SPIRVerElts[] = {
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, Version / 100)),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, (Version / 100 > 1) ? 0 : 2))};
llvm::NamedMDNode *SPIRVerMD =
TheModule.getOrInsertNamedMetadata("opencl.spir.version");
llvm::LLVMContext &Ctx = TheModule.getContext();
SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
}
}
if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
assert(PLevel < 3 && "Invalid PIC Level");
getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
if (Context.getLangOpts().PIE)
getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
}
if (getCodeGenOpts().CodeModel.size() > 0) {
unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
.Case("tiny", llvm::CodeModel::Tiny)
.Case("small", llvm::CodeModel::Small)
.Case("kernel", llvm::CodeModel::Kernel)
.Case("medium", llvm::CodeModel::Medium)
.Case("large", llvm::CodeModel::Large)
.Default(~0u);
if (CM != ~0u) {
llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
getModule().setCodeModel(codeModel);
}
}
if (CodeGenOpts.NoPLT)
getModule().setRtLibUseGOT();
SimplifyPersonality();
if (getCodeGenOpts().EmitDeclMetadata)
EmitDeclMetadata();
if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
EmitCoverageFile();
if (DebugInfo)
DebugInfo->finalize();
if (getCodeGenOpts().EmitVersionIdentMetadata)
EmitVersionIdentMetadata();
if (!getCodeGenOpts().RecordCommandLine.empty())
EmitCommandLineMetadata();
EmitTargetMetadata();
}
void CodeGenModule::EmitOpenCLMetadata() {
// SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
// opencl.ocl.version named metadata node.
// C++ is backwards compatible with OpenCL v2.0.
// FIXME: We might need to add CXX version at some point too?
auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
llvm::Metadata *OCLVerElts[] = {
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, Version / 100)),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
llvm::NamedMDNode *OCLVerMD =
TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
llvm::LLVMContext &Ctx = TheModule.getContext();
OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
}
void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
// Make sure that this type is translated.
Types.UpdateCompletedType(TD);
}
void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
// Make sure that this type is translated.
Types.RefreshTypeCacheForClass(RD);
}
llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
if (!TBAA)
return nullptr;
return TBAA->getTypeInfo(QTy);
}
TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->getAccessInfo(AccessType);
}
TBAAAccessInfo
CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->getVTablePtrAccessInfo(VTablePtrType);
}
llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
if (!TBAA)
return nullptr;
return TBAA->getTBAAStructInfo(QTy);
}
llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
if (!TBAA)
return nullptr;
return TBAA->getBaseTypeInfo(QTy);
}
llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
if (!TBAA)
return nullptr;
return TBAA->getAccessTagInfo(Info);
}
TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
TBAAAccessInfo TargetInfo) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
}
TBAAAccessInfo
CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
TBAAAccessInfo InfoB) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
}
TBAAAccessInfo
CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
TBAAAccessInfo SrcInfo) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
}
void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
TBAAAccessInfo TBAAInfo) {
if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
}
void CodeGenModule::DecorateInstructionWithInvariantGroup(
llvm::Instruction *I, const CXXRecordDecl *RD) {
I->setMetadata(llvm::LLVMContext::MD_invariant_group,
llvm::MDNode::get(getLLVMContext(), {}));
}
void CodeGenModule::Error(SourceLocation loc, StringRef message) {
unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
getDiags().Report(Context.getFullLoc(loc), diagID) << message;
}
/// ErrorUnsupported - Print out an error that codegen doesn't support the
/// specified stmt yet.
void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
"cannot compile this %0 yet");
std::string Msg = Type;
getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
<< Msg << S->getSourceRange();
}
/// ErrorUnsupported - Print out an error that codegen doesn't support the
/// specified decl yet.
void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
"cannot compile this %0 yet");
std::string Msg = Type;
getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
}
llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
return llvm::ConstantInt::get(SizeTy, size.getQuantity());
}
void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
const NamedDecl *D) const {
if (GV->hasDLLImportStorageClass())
return;
// Internal definitions always have default visibility.
if (GV->hasLocalLinkage()) {
GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
return;
}
if (!D)
return;
// Set visibility for definitions, and for declarations if requested globally
// or set explicitly.
LinkageInfo LV = D->getLinkageAndVisibility();
if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
!GV->isDeclarationForLinker())
GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
}
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
llvm::GlobalValue *GV) {
if (GV->hasLocalLinkage())
return true;
if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
return true;
// DLLImport explicitly marks the GV as external.
if (GV->hasDLLImportStorageClass())
return false;
const llvm::Triple &TT = CGM.getTriple();
if (TT.isWindowsGNUEnvironment()) {
// In MinGW, variables without DLLImport can still be automatically
// imported from a DLL by the linker; don't mark variables that
// potentially could come from another DLL as DSO local.
if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
!GV->isThreadLocal())
return false;
}
// On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
// remain unresolved in the link, they can be resolved to zero, which is
// outside the current DSO.
if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
return false;
// Every other GV is local on COFF.
// Make an exception for windows OS in the triple: Some firmware builds use
// *-win32-macho triples. This (accidentally?) produced windows relocations
// without GOT tables in older clang versions; Keep this behaviour.
// FIXME: even thread local variables?
if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
return true;
// Only handle COFF and ELF for now.
if (!TT.isOSBinFormatELF())
return false;
// If this is not an executable, don't assume anything is local.
const auto &CGOpts = CGM.getCodeGenOpts();
llvm::Reloc::Model RM = CGOpts.RelocationModel;
const auto &LOpts = CGM.getLangOpts();
if (RM != llvm::Reloc::Static && !LOpts.PIE && !LOpts.OpenMPIsDevice)
return false;
// A definition cannot be preempted from an executable.
if (!GV->isDeclarationForLinker())
return true;
// Most PIC code sequences that assume that a symbol is local cannot produce a
// 0 if it turns out the symbol is undefined. While this is ABI and relocation
// depended, it seems worth it to handle it here.
if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
return false;
// PPC has no copy relocations and cannot use a plt entry as a symbol address.
llvm::Triple::ArchType Arch = TT.getArch();
if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
Arch == llvm::Triple::ppc64le)
return false;
// If we can use copy relocations we can assume it is local.
if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
if (!Var->isThreadLocal() &&
(RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
return true;
// If we can use a plt entry as the symbol address we can assume it
// is local.
// FIXME: This should work for PIE, but the gold linker doesn't support it.
if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
return true;
// Otherwise don't assue it is local.
return false;
}
void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
}
void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
GlobalDecl GD) const {
const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
// C++ destructors have a few C++ ABI specific special cases.
if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
return;
}
setDLLImportDLLExport(GV, D);
}
void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
const NamedDecl *D) const {
if (D && D->isExternallyVisible()) {
if (D->hasAttr<DLLImportAttr>())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
}
}
void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
GlobalDecl GD) const {
setDLLImportDLLExport(GV, GD);
setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
}
void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
const NamedDecl *D) const {
setDLLImportDLLExport(GV, D);
setGVPropertiesAux(GV, D);
}
void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
const NamedDecl *D) const {
setGlobalVisibility(GV, D);
setDSOLocal(GV);
GV->setPartition(CodeGenOpts.SymbolPartition);
}
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
.Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
.Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
.Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
.Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
}
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
CodeGenOptions::TLSModel M) {
switch (M) {
case CodeGenOptions::GeneralDynamicTLSModel:
return llvm::GlobalVariable::GeneralDynamicTLSModel;
case CodeGenOptions::LocalDynamicTLSModel:
return llvm::GlobalVariable::LocalDynamicTLSModel;
case CodeGenOptions::InitialExecTLSModel:
return llvm::GlobalVariable::InitialExecTLSModel;
case CodeGenOptions::LocalExecTLSModel:
return llvm::GlobalVariable::LocalExecTLSModel;
}
llvm_unreachable("Invalid TLS model!");
}
void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
llvm::GlobalValue::ThreadLocalMode TLM;
TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
// Override the TLS model if it is explicitly specified.
if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
TLM = GetLLVMTLSModel(Attr->getModel());
}
GV->setThreadLocalMode(TLM);
}
static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
StringRef Name) {
const TargetInfo &Target = CGM.getTarget();
return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
}
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
const CPUSpecificAttr *Attr,
unsigned CPUIndex,
raw_ostream &Out) {
// cpu_specific gets the current name, dispatch gets the resolver if IFunc is
// supported.
if (Attr)
Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
else if (CGM.getTarget().supportsIFunc())
Out << ".resolver";
}
static void AppendTargetMangling(const CodeGenModule &CGM,
const TargetAttr *Attr, raw_ostream &Out) {
if (Attr->isDefaultVersion())
return;
Out << '.';
const TargetInfo &Target = CGM.getTarget();
TargetAttr::ParsedTargetAttr Info =
Attr->parse([&Target](StringRef LHS, StringRef RHS) {
// Multiversioning doesn't allow "no-${feature}", so we can
// only have "+" prefixes here.
assert(LHS.startswith("+") && RHS.startswith("+") &&
"Features should always have a prefix.");
return Target.multiVersionSortPriority(LHS.substr(1)) >
Target.multiVersionSortPriority(RHS.substr(1));
});
bool IsFirst = true;
if (!Info.Architecture.empty()) {
IsFirst = false;
Out << "arch_" << Info.Architecture;
}
for (StringRef Feat : Info.Features) {
if (!IsFirst)
Out << '_';
IsFirst = false;
Out << Feat.substr(1);
}
}
static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
const NamedDecl *ND,
bool OmitMultiVersionMangling = false) {
SmallString<256> Buffer;
llvm::raw_svector_ostream Out(Buffer);
MangleContext &MC = CGM.getCXXABI().getMangleContext();
if (MC.shouldMangleDeclName(ND)) {
llvm::raw_svector_ostream Out(Buffer);
if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
MC.mangleCXXCtor(D, GD.getCtorType(), Out);
else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
MC.mangleCXXDtor(D, GD.getDtorType(), Out);
else
MC.mangleName(ND, Out);
} else {
IdentifierInfo *II = ND->getIdentifier();
assert(II && "Attempt to mangle unnamed decl.");
const auto *FD = dyn_cast<FunctionDecl>(ND);
if (FD &&
FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
llvm::raw_svector_ostream Out(Buffer);
Out << "__regcall3__" << II->getName();
} else {
Out << II->getName();
}
}
if (const auto *FD = dyn_cast<FunctionDecl>(ND))
if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
switch (FD->getMultiVersionKind()) {
case MultiVersionKind::CPUDispatch:
case MultiVersionKind::CPUSpecific:
AppendCPUSpecificCPUDispatchMangling(CGM,
FD->getAttr<CPUSpecificAttr>(),
GD.getMultiVersionIndex(), Out);
break;
case MultiVersionKind::Target:
AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
break;
case MultiVersionKind::None:
llvm_unreachable("None multiversion type isn't valid here");
}
}
return Out.str();
}
void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
const FunctionDecl *FD) {
if (!FD->isMultiVersion())
return;
// Get the name of what this would be without the 'target' attribute. This
// allows us to lookup the version that was emitted when this wasn't a
// multiversion function.
std::string NonTargetName =
getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
GlobalDecl OtherGD;
if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
assert(OtherGD.getCanonicalDecl()
.getDecl()
->getAsFunction()
->isMultiVersion() &&
"Other GD should now be a multiversioned function");
// OtherFD is the version of this function that was mangled BEFORE
// becoming a MultiVersion function. It potentially needs to be updated.
const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
.getDecl()
->getAsFunction()
->getMostRecentDecl();
std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
// This is so that if the initial version was already the 'default'
// version, we don't try to update it.
if (OtherName != NonTargetName) {
// Remove instead of erase, since others may have stored the StringRef
// to this.
const auto ExistingRecord = Manglings.find(NonTargetName);
if (ExistingRecord != std::end(Manglings))
Manglings.remove(&(*ExistingRecord));
auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
Entry->setName(OtherName);
}
}
}
StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
GlobalDecl CanonicalGD = GD.getCanonicalDecl();
// Some ABIs don't have constructor variants. Make sure that base and
// complete constructors get mangled the same.
if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
if (!getTarget().getCXXABI().hasConstructorVariants()) {
CXXCtorType OrigCtorType = GD.getCtorType();
assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
if (OrigCtorType == Ctor_Base)
CanonicalGD = GlobalDecl(CD, Ctor_Complete);
}
}
auto FoundName = MangledDeclNames.find(CanonicalGD);
if (FoundName != MangledDeclNames.end())
return FoundName->second;
// Keep the first result in the case of a mangling collision.
const auto *ND = cast<NamedDecl>(GD.getDecl());
std::string MangledName = getMangledNameImpl(*this, GD, ND);
// Adjust kernel stub mangling as we may need to be able to differentiate
// them from the kernel itself (e.g., for HIP).
if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
if (!getLangOpts().CUDAIsDevice && FD->hasAttr<CUDAGlobalAttr>())
MangledName = getCUDARuntime().getDeviceStubName(MangledName);
auto Result = Manglings.insert(std::make_pair(MangledName, GD));
return MangledDeclNames[CanonicalGD] = Result.first->first();
}
StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
const BlockDecl *BD) {
MangleContext &MangleCtx = getCXXABI().getMangleContext();
const Decl *D = GD.getDecl();
SmallString<256> Buffer;
llvm::raw_svector_ostream Out(Buffer);
if (!D)
MangleCtx.mangleGlobalBlock(BD,
dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
else
MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
return Result.first->first();
}
llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
return getModule().getNamedValue(Name);
}
/// AddGlobalCtor - Add a function to the list that will be called before
/// main() runs.
void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
llvm::Constant *AssociatedData) {
// FIXME: Type coercion of void()* types.
GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
}
/// AddGlobalDtor - Add a function to the list that will be called
/// when the module is unloaded.
void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
DtorsUsingAtExit[Priority].push_back(Dtor);
return;
}
// FIXME: Type coercion of void()* types.
GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
}
void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
if (Fns.empty()) return;
// Ctor function type is void()*.
llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
TheModule.getDataLayout().getProgramAddressSpace());
// Get the type of a ctor entry, { i32, void ()*, i8* }.
llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, CtorPFTy, VoidPtrTy);
// Construct the constructor and destructor arrays.
ConstantInitBuilder builder(*this);
auto ctors = builder.beginArray(CtorStructTy);
for (const auto &I : Fns) {
auto ctor = ctors.beginStruct(CtorStructTy);
ctor.addInt(Int32Ty, I.Priority);
ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
if (I.AssociatedData)
ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
else
ctor.addNullPointer(VoidPtrTy);
ctor.finishAndAddTo(ctors);
}
auto list =
ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
/*constant*/ false,
llvm::GlobalValue::AppendingLinkage);
// The LTO linker doesn't seem to like it when we set an alignment
// on appending variables. Take it off as a workaround.
list->setAlignment(0);
Fns.clear();
}
llvm::GlobalValue::LinkageTypes
CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
const auto *D = cast<FunctionDecl>(GD.getDecl());
GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
if (isa<CXXConstructorDecl>(D) &&
cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
Context.getTargetInfo().getCXXABI().isMicrosoft()) {
// Our approach to inheriting constructors is fundamentally different from
// that used by the MS ABI, so keep our inheriting constructor thunks
// internal rather than trying to pick an unambiguous mangling for them.
return llvm::GlobalValue::InternalLinkage;
}
return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
}
llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
if (!MDS) return nullptr;
return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
}
void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
const CGFunctionInfo &Info,
llvm::Function *F) {
unsigned CallingConv;
llvm::AttributeList PAL;
ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
F->setAttributes(PAL);
F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
}
static void removeImageAccessQualifier(std::string& TyName) {
std::string ReadOnlyQual("__read_only");
std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
if (ReadOnlyPos != std::string::npos)
// "+ 1" for the space after access qualifier.
TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
else {
std::string WriteOnlyQual("__write_only");
std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
if (WriteOnlyPos != std::string::npos)
TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
else {
std::string ReadWriteQual("__read_write");
std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
if (ReadWritePos != std::string::npos)
TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
}
}
}
// Returns the address space id that should be produced to the
// kernel_arg_addr_space metadata. This is always fixed to the ids
// as specified in the SPIR 2.0 specification in order to differentiate
// for example in clGetKernelArgInfo() implementation between the address
// spaces with targets without unique mapping to the OpenCL address spaces
// (basically all single AS CPUs).
static unsigned ArgInfoAddressSpace(LangAS AS) {
switch (AS) {
case LangAS::opencl_global: return 1;
case LangAS::opencl_constant: return 2;
case LangAS::opencl_local: return 3;
case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
default:
return 0; // Assume private.
}
}
void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
const FunctionDecl *FD,
CodeGenFunction *CGF) {
assert(((FD && CGF) || (!FD && !CGF)) &&
"Incorrect use - FD and CGF should either be both null or not!");
// Create MDNodes that represent the kernel arg metadata.
// Each MDNode is a list in the form of "key", N number of values which is
// the same number of values as their are kernel arguments.
const PrintingPolicy &Policy = Context.getPrintingPolicy();
// MDNode for the kernel argument address space qualifiers.
SmallVector<llvm::Metadata *, 8> addressQuals;
// MDNode for the kernel argument access qualifiers (images only).
SmallVector<llvm::Metadata *, 8> accessQuals;
// MDNode for the kernel argument type names.
SmallVector<llvm::Metadata *, 8> argTypeNames;
// MDNode for the kernel argument base type names.
SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
// MDNode for the kernel argument type qualifiers.
SmallVector<llvm::Metadata *, 8> argTypeQuals;
// MDNode for the kernel argument names.
SmallVector<llvm::Metadata *, 8> argNames;
if (FD && CGF)
for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
const ParmVarDecl *parm = FD->getParamDecl(i);
QualType ty = parm->getType();
std::string typeQuals;
if (ty->isPointerType()) {
QualType pointeeTy = ty->getPointeeType();
// Get address qualifier.
addressQuals.push_back(
llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
// Get argument type name.
std::string typeName =
pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
// Turn "unsigned type" to "utype"
std::string::size_type pos = typeName.find("unsigned");
if (pointeeTy.isCanonical() && pos != std::string::npos)
typeName.erase(pos + 1, 8);
argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
std::string baseTypeName =
pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
Policy) +
"*";
// Turn "unsigned type" to "utype"
pos = baseTypeName.find("unsigned");
if (pos != std::string::npos)
baseTypeName.erase(pos + 1, 8);
argBaseTypeNames.push_back(
llvm::MDString::get(VMContext, baseTypeName));
// Get argument type qualifiers:
if (ty.isRestrictQualified())
typeQuals = "restrict";
if (pointeeTy.isConstQualified() ||
(pointeeTy.getAddressSpace() == LangAS::opencl_constant))
typeQuals += typeQuals.empty() ? "const" : " const";
if (pointeeTy.isVolatileQualified())
typeQuals += typeQuals.empty() ? "volatile" : " volatile";
} else {
uint32_t AddrSpc = 0;
bool isPipe = ty->isPipeType();
if (ty->isImageType() || isPipe)
AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
addressQuals.push_back(
llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
// Get argument type name.
std::string typeName;
if (isPipe)
typeName = ty.getCanonicalType()
->getAs<PipeType>()
->getElementType()
.getAsString(Policy);
else
typeName = ty.getUnqualifiedType().getAsString(Policy);
// Turn "unsigned type" to "utype"
std::string::size_type pos = typeName.find("unsigned");
if (ty.isCanonical() && pos != std::string::npos)
typeName.erase(pos + 1, 8);
std::string baseTypeName;
if (isPipe)
baseTypeName = ty.getCanonicalType()
->getAs<PipeType>()
->getElementType()
.getCanonicalType()
.getAsString(Policy);
else
baseTypeName =
ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
// Remove access qualifiers on images
// (as they are inseparable from type in clang implementation,
// but OpenCL spec provides a special query to get access qualifier
// via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
if (ty->isImageType()) {
removeImageAccessQualifier(typeName);
removeImageAccessQualifier(baseTypeName);
}
argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
// Turn "unsigned type" to "utype"
pos = baseTypeName.find("unsigned");
if (pos != std::string::npos)
baseTypeName.erase(pos + 1, 8);
argBaseTypeNames.push_back(
llvm::MDString::get(VMContext, baseTypeName));
if (isPipe)
typeQuals = "pipe";
}
argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
// Get image and pipe access qualifier:
if (ty->isImageType() || ty->isPipeType()) {
const Decl *PDecl = parm;
if (auto *TD = dyn_cast<TypedefType>(ty))
PDecl = TD->getDecl();
const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
if (A && A->isWriteOnly())
accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
else if (A && A->isReadWrite())
accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
else
accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
} else
accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
// Get argument name.
argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
}
Fn->setMetadata("kernel_arg_addr_space",
llvm::MDNode::get(VMContext, addressQuals));
Fn->setMetadata("kernel_arg_access_qual",
llvm::MDNode::get(VMContext, accessQuals));
Fn->setMetadata("kernel_arg_type",
llvm::MDNode::get(VMContext, argTypeNames));
Fn->setMetadata("kernel_arg_base_type",
llvm::MDNode::get(VMContext, argBaseTypeNames));
Fn->setMetadata("kernel_arg_type_qual",
llvm::MDNode::get(VMContext, argTypeQuals));
if (getCodeGenOpts().EmitOpenCLArgMetadata)
Fn->setMetadata("kernel_arg_name",
llvm::MDNode::get(VMContext, argNames));
}
/// Determines whether the language options require us to model
/// unwind exceptions. We treat -fexceptions as mandating this
/// except under the fragile ObjC ABI with only ObjC exceptions
/// enabled. This means, for example, that C with -fexceptions
/// enables this.
static bool hasUnwindExceptions(const LangOptions &LangOpts) {
// If exceptions are completely disabled, obviously this is false.
if (!LangOpts.Exceptions) return false;
// If C++ exceptions are enabled, this is true.
if (LangOpts.CXXExceptions) return true;
// If ObjC exceptions are enabled, this depends on the ABI.
if (LangOpts.ObjCExceptions) {
return LangOpts.ObjCRuntime.hasUnwindExceptions();
}
return true;
}
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
const CXXMethodDecl *MD) {
// Check that the type metadata can ever actually be used by a call.
if (!CGM.getCodeGenOpts().LTOUnit ||
!CGM.HasHiddenLTOVisibility(MD->getParent()))
return false;
// Only functions whose address can be taken with a member function pointer
// need this sort of type metadata.
return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
!isa<CXXDestructorDecl>(MD);
}
std::vector<const CXXRecordDecl *>
CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
llvm::SetVector<const CXXRecordDecl *> MostBases;
std::function<void (const CXXRecordDecl *)> CollectMostBases;
CollectMostBases = [&](const CXXRecordDecl *RD) {
if (RD->getNumBases() == 0)
MostBases.insert(RD);
for (const CXXBaseSpecifier &B : RD->bases())
CollectMostBases(B.getType()->getAsCXXRecordDecl());
};
CollectMostBases(RD);
return MostBases.takeVector();
}
void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
llvm::Function *F) {
llvm::AttrBuilder B;
if (CodeGenOpts.UnwindTables)
B.addAttribute(llvm::Attribute::UWTable);
if (!hasUnwindExceptions(LangOpts))
B.addAttribute(llvm::Attribute::NoUnwind);
if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
if (LangOpts.getStackProtector() == LangOptions::SSPOn)
B.addAttribute(llvm::Attribute::StackProtect);
else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
B.addAttribute(llvm::Attribute::StackProtectStrong);
else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
B.addAttribute(llvm::Attribute::StackProtectReq);
}
if (!D) {
// If we don't have a declaration to control inlining, the function isn't
// explicitly marked as alwaysinline for semantic reasons, and inlining is
// disabled, mark the function as noinline.
if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
B.addAttribute(llvm::Attribute::NoInline);
F->addAttributes(llvm::AttributeList::FunctionIndex, B);
return;
}
// Track whether we need to add the optnone LLVM attribute,
// starting with the default for this optimization level.
bool ShouldAddOptNone =
!CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
// We can't add optnone in the following cases, it won't pass the verifier.
ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
B.addAttribute(llvm::Attribute::OptimizeNone);
// OptimizeNone implies noinline; we should not be inlining such functions.
B.addAttribute(llvm::Attribute::NoInline);
assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
"OptimizeNone and AlwaysInline on same function!");
// We still need to handle naked functions even though optnone subsumes
// much of their semantics.
if (D->hasAttr<NakedAttr>())
B.addAttribute(llvm::Attribute::Naked);
// OptimizeNone wins over OptimizeForSize and MinSize.
F->removeFnAttr(llvm::Attribute::OptimizeForSize);
F->removeFnAttr(llvm::Attribute::MinSize);
} else if (D->hasAttr<NakedAttr>()) {
// Naked implies noinline: we should not be inlining such functions.
B.addAttribute(llvm::Attribute::Naked);
B.addAttribute(llvm::Attribute::NoInline);
} else if (D->hasAttr<NoDuplicateAttr>()) {
B.addAttribute(llvm::Attribute::NoDuplicate);
} else if (D->hasAttr<NoInlineAttr>()) {
B.addAttribute(llvm::Attribute::NoInline);
} else if (D->hasAttr<AlwaysInlineAttr>() &&
!F->hasFnAttribute(llvm::Attribute::NoInline)) {
// (noinline wins over always_inline, and we can't specify both in IR)
B.addAttribute(llvm::Attribute::AlwaysInline);
} else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
// If we're not inlining, then force everything that isn't always_inline to
// carry an explicit noinline attribute.
if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
B.addAttribute(llvm::Attribute::NoInline);
} else {
// Otherwise, propagate the inline hint attribute and potentially use its
// absence to mark things as noinline.
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
// Search function and template pattern redeclarations for inline.
auto CheckForInline = [](const FunctionDecl *FD) {
auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
return Redecl->isInlineSpecified();
};
if (any_of(FD->redecls(), CheckRedeclForInline))
return true;
const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
if (!Pattern)
return false;
return any_of(Pattern->redecls(), CheckRedeclForInline);
};
if (CheckForInline(FD)) {
B.addAttribute(llvm::Attribute::InlineHint);
} else if (CodeGenOpts.getInlining() ==
CodeGenOptions::OnlyHintInlining &&
!FD->isInlined() &&
!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
B.addAttribute(llvm::Attribute::NoInline);
}
}
}
// Add other optimization related attributes if we are optimizing this
// function.
if (!D->hasAttr<OptimizeNoneAttr>()) {
if (D->hasAttr<ColdAttr>()) {
if (!ShouldAddOptNone)
B.addAttribute(llvm::Attribute::OptimizeForSize);
B.addAttribute(llvm::Attribute::Cold);
}
if (D->hasAttr<MinSizeAttr>())
B.addAttribute(llvm::Attribute::MinSize);
}
F->addAttributes(llvm::AttributeList::FunctionIndex, B);
unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
if (alignment)
F->setAlignment(alignment);
if (!D->hasAttr<AlignedAttr>())
if (LangOpts.FunctionAlignment)
F->setAlignment(1 << LangOpts.FunctionAlignment);
// Some C++ ABIs require 2-byte alignment for member functions, in order to
// reserve a bit for differentiating between virtual and non-virtual member
// functions. If the current target's C++ ABI requires this and this is a
// member function, set its alignment accordingly.
if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
F->setAlignment(2);
}
// In the cross-dso CFI mode, we want !type attributes on definitions only.
if (CodeGenOpts.SanitizeCfiCrossDso)
if (auto *FD = dyn_cast<FunctionDecl>(D))
CreateFunctionTypeMetadataForIcall(FD, F);
// Emit type metadata on member functions for member function pointer checks.
// These are only ever necessary on definitions; we're guaranteed that the
// definition will be present in the LTO unit as a result of LTO visibility.
auto *MD = dyn_cast<CXXMethodDecl>(D);
if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
llvm::Metadata *Id =
CreateMetadataIdentifierForType(Context.getMemberPointerType(
MD->getType(), Context.getRecordType(Base).getTypePtr()));
F->addTypeMetadata(0, Id);
}
}
}
void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
const Decl *D = GD.getDecl();
if (dyn_cast_or_null<NamedDecl>(D))
setGVProperties(GV, GD);
else
GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
if (D && D->hasAttr<UsedAttr>())
addUsedGlobal(GV);
if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
const auto *VD = cast<VarDecl>(D);
if (VD->getType().isConstQualified() &&
VD->getStorageDuration() == SD_Static)
addUsedGlobal(GV);
}
}
bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
llvm::AttrBuilder &Attrs) {
// Add target-cpu and target-features attributes to functions. If
// we have a decl for the function and it has a target attribute then
// parse that and add it to the feature set.
StringRef TargetCPU = getTarget().getTargetOpts().CPU;
std::vector<std::string> Features;
const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
FD = FD ? FD->getMostRecentDecl() : FD;
const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
bool AddedAttr = false;
if (TD || SD) {
llvm::StringMap<bool> FeatureMap;
getFunctionFeatureMap(FeatureMap, GD);
// Produce the canonical string for this set of features.
for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
// Now add the target-cpu and target-features to the function.
// While we populated the feature map above, we still need to
// get and parse the target attribute so we can get the cpu for
// the function.
if (TD) {
TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
if (ParsedAttr.Architecture != "" &&
getTarget().isValidCPUName(ParsedAttr.Architecture))
TargetCPU = ParsedAttr.Architecture;
}
} else {
// Otherwise just add the existing target cpu and target features to the
// function.
Features = getTarget().getTargetOpts().Features;
}
if (TargetCPU != "") {
Attrs.addAttribute("target-cpu", TargetCPU);
AddedAttr = true;
}
if (!Features.empty()) {
llvm::sort(Features);
Attrs.addAttribute("target-features", llvm::join(Features, ","));
AddedAttr = true;
}
return AddedAttr;
}
void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
llvm::GlobalObject *GO) {
const Decl *D = GD.getDecl();
SetCommonAttributes(GD, GO);
if (D) {
if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
GV->addAttribute("bss-section", SA->getName());
if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
GV->addAttribute("data-section", SA->getName());
if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
GV->addAttribute("rodata-section", SA->getName());
}
if (auto *F = dyn_cast<llvm::Function>(GO)) {
if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
if (!D->getAttr<SectionAttr>())
F->addFnAttr("implicit-section-name", SA->getName());
llvm::AttrBuilder Attrs;
if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
// We know that GetCPUAndFeaturesAttributes will always have the
// newest set, since it has the newest possible FunctionDecl, so the
// new ones should replace the old.
F->removeFnAttr("target-cpu");
F->removeFnAttr("target-features");
F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
}
}
if (const auto *CSA = D->getAttr<CodeSegAttr>())
GO->setSection(CSA->getName());
else if (const auto *SA = D->getAttr<SectionAttr>())
GO->setSection(SA->getName());
}
getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
}
void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
llvm::Function *F,
const CGFunctionInfo &FI) {
const Decl *D = GD.getDecl();
SetLLVMFunctionAttributes(GD, FI, F);
SetLLVMFunctionAttributesForDefinition(D, F);
F->setLinkage(llvm::Function::InternalLinkage);
setNonAliasAttributes(GD, F);
}
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
// Set linkage and visibility in case we never see a definition.
LinkageInfo LV = ND->getLinkageAndVisibility();
// Don't set internal linkage on declarations.
// "extern_weak" is overloaded in LLVM; we probably should have
// separate linkage types for this.
if (isExternallyVisible(LV.getLinkage()) &&
(ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
}
void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
llvm::Function *F) {
// Only if we are checking indirect calls.
if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
return;
// Non-static class methods are handled via vtable or member function pointer
// checks elsewhere.
if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
return;
// Additionally, if building with cross-DSO support...
if (CodeGenOpts.SanitizeCfiCrossDso) {
// Skip available_externally functions. They won't be codegen'ed in the
// current module anyway.
if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
return;
}
llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
F->addTypeMetadata(0, MD);
F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
// Emit a hash-based bit set entry for cross-DSO calls.
if (CodeGenOpts.SanitizeCfiCrossDso)
if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
}
void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
bool IsIncompleteFunction,
bool IsThunk) {
if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
// If this is an intrinsic function, set the function's attributes
// to the intrinsic's attributes.
F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
return;
}
const auto *FD = cast<FunctionDecl>(GD.getDecl());
if (!IsIncompleteFunction)
SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
// Add the Returned attribute for "this", except for iOS 5 and earlier
// where substantial code, including the libstdc++ dylib, was compiled with
// GCC and does not actually return "this".
if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
!(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
assert(!F->arg_empty() &&
F->arg_begin()->getType()
->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return");
F->addAttribute(1, llvm::Attribute::Returned);
}
// Only a few attributes are set on declarations; these may later be
// overridden by a definition.
setLinkageForGV(F, FD);
setGVProperties(F, FD);
// Setup target-specific attributes.
if (!IsIncompleteFunction && F->isDeclaration())
getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
if (const auto *CSA = FD->getAttr<CodeSegAttr>())
F->setSection(CSA->getName());
else if (const auto *SA = FD->getAttr<SectionAttr>())
F->setSection(SA->getName());
if (FD->isReplaceableGlobalAllocationFunction()) {
// A replaceable global allocation function does not act like a builtin by
// default, only if it is invoked by a new-expression or delete-expression.
F->addAttribute(llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoBuiltin);
// A sane operator new returns a non-aliasing pointer.
// FIXME: Also add NonNull attribute to the return value
// for the non-nothrow forms?
auto Kind = FD->getDeclName().getCXXOverloadedOperator();
if (getCodeGenOpts().AssumeSaneOperatorNew &&
(Kind == OO_New || Kind == OO_Array_New))
F->addAttribute(llvm::AttributeList::ReturnIndex,
llvm::Attribute::NoAlias);
}
if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
if (MD->isVirtual())
F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
// Don't emit entries for function declarations in the cross-DSO mode. This
// is handled with better precision by the receiving DSO.
if (!CodeGenOpts.SanitizeCfiCrossDso)
CreateFunctionTypeMetadataForIcall(FD, F);
if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
if (const auto *CB = FD->getAttr<CallbackAttr>()) {
// Annotate the callback behavior as metadata:
// - The callback callee (as argument number).
// - The callback payloads (as argument numbers).
llvm::LLVMContext &Ctx = F->getContext();
llvm::MDBuilder MDB(Ctx);
// The payload indices are all but the first one in the encoding. The first
// identifies the callback callee.
int CalleeIdx = *CB->encoding_begin();
ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
F->addMetadata(llvm::LLVMContext::MD_callback,
*llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
CalleeIdx, PayloadIndices,
/* VarArgsArePassed */ false)}));
}
}
void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
assert(!GV->isDeclaration() &&
"Only globals with definition can force usage.");
LLVMUsed.emplace_back(GV);
}
void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
assert(!GV->isDeclaration() &&
"Only globals with definition can force usage.");
LLVMCompilerUsed.emplace_back(GV);
}
static void emitUsed(CodeGenModule &CGM, StringRef Name,
std::vector<llvm::WeakTrackingVH> &List) {
// Don't create llvm.used if there is no need.
if (List.empty())
return;
// Convert List to what ConstantArray needs.
SmallVector<llvm::Constant*, 8> UsedArray;
UsedArray.resize(List.size());
for (unsigned i = 0, e = List.size(); i != e; ++i) {
UsedArray[i] =
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
}
if (UsedArray.empty())
return;
llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
auto *GV = new llvm::GlobalVariable(
CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, UsedArray), Name);
GV->setSection("llvm.metadata");
}
void CodeGenModule::emitLLVMUsed() {
emitUsed(*this, "llvm.used", LLVMUsed);
emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
}
void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
}
void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
llvm::SmallString<32> Opt;
getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
}
void CodeGenModule::AddDependentLib(StringRef Lib) {
auto &C = getLLVMContext();
if (getTarget().getTriple().isOSBinFormatELF()) {
ELFDependentLibraries.push_back(
llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
return;
}
llvm::SmallString<24> Opt;
getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
}
/// Add link options implied by the given module, including modules
/// it depends on, using a postorder walk.
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
SmallVectorImpl<llvm::MDNode *> &Metadata,
llvm::SmallPtrSet<Module *, 16> &Visited) {
// Import this module's parent.
if (Mod->Parent && Visited.insert(Mod->Parent).second) {
addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
}
// Import this module's dependencies.
for (unsigned I = Mod->Imports.size(); I > 0; --I) {
if (Visited.insert(Mod->Imports[I - 1]).second)
addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
}
// Add linker options to link against the libraries/frameworks
// described by this module.
llvm::LLVMContext &Context = CGM.getLLVMContext();
bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
// For modules that use export_as for linking, use that module
// name instead.
if (Mod->UseExportAsModuleLinkName)
return;
for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
// Link against a framework. Frameworks are currently Darwin only, so we
// don't to ask TargetCodeGenInfo for the spelling of the linker option.
if (Mod->LinkLibraries[I-1].IsFramework) {
llvm::Metadata *Args[2] = {
llvm::MDString::get(Context, "-framework"),
llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Metadata.push_back(llvm::MDNode::get(Context, Args));
continue;
}
// Link against a library.
if (IsELF) {
llvm::Metadata *Args[2] = {
llvm::MDString::get(Context, "lib"),
llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
};
Metadata.push_back(llvm::MDNode::get(Context, Args));
} else {
llvm::SmallString<24> Opt;
CGM.getTargetCodeGenInfo().getDependentLibraryOption(
Mod->LinkLibraries[I - 1].Library, Opt);
auto *OptString = llvm::MDString::get(Context, Opt);
Metadata.push_back(llvm::MDNode::get(Context, OptString));
}
}
}
void CodeGenModule::EmitModuleLinkOptions() {
// Collect the set of all of the modules we want to visit to emit link
// options, which is essentially the imported modules and all of their
// non-explicit child modules.
llvm::SetVector<clang::Module *> LinkModules;
llvm::SmallPtrSet<clang::Module *, 16> Visited;
SmallVector<clang::Module *, 16> Stack;
// Seed the stack with imported modules.
for (Module *M : ImportedModules) {
// Do not add any link flags when an implementation TU of a module imports
// a header of that same module.
if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
!getLangOpts().isCompilingModule())
continue;
if (Visited.insert(M).second)
Stack.push_back(M);
}
// Find all of the modules to import, making a little effort to prune
// non-leaf modules.
while (!Stack.empty()) {
clang::Module *Mod = Stack.pop_back_val();
bool AnyChildren = false;
// Visit the submodules of this module.
for (const auto &SM : Mod->submodules()) {
// Skip explicit children; they need to be explicitly imported to be
// linked against.
if (SM->IsExplicit)
continue;
if (Visited.insert(SM).second) {
Stack.push_back(SM);
AnyChildren = true;
}
}
// We didn't find any children, so add this module to the list of
// modules to link against.
if (!AnyChildren) {
LinkModules.insert(Mod);
}
}
// Add link options for all of the imported modules in reverse topological
// order. We don't do anything to try to order import link flags with respect
// to linker options inserted by things like #pragma comment().
SmallVector<llvm::MDNode *, 16> MetadataArgs;
Visited.clear();
for (Module *M : LinkModules)
if (Visited.insert(M).second)
addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
std::reverse(MetadataArgs.begin(), MetadataArgs.end());
LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
// Add the linker options metadata flag.
auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
for (auto *MD : LinkerOptionsMetadata)
NMD->addOperand(MD);
}
void CodeGenModule::EmitDeferred() {
// Emit deferred declare target declarations.
if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
getOpenMPRuntime().emitDeferredTargetDecls();
// Emit code for any potentially referenced deferred decls. Since a
// previously unused static decl may become used during the generation of code
// for a static function, iterate until no changes are made.
if (!DeferredVTables.empty()) {
EmitDeferredVTables();
// Emitting a vtable doesn't directly cause more vtables to
// become deferred, although it can cause functions to be
// emitted that then need those vtables.
assert(DeferredVTables.empty());
}
// Stop if we're out of both deferred vtables and deferred declarations.
if (DeferredDeclsToEmit.empty())
return;
// Grab the list of decls to emit. If EmitGlobalDefinition schedules more
// work, it will not interfere with this.
std::vector<GlobalDecl> CurDeclsToEmit;
CurDeclsToEmit.swap(DeferredDeclsToEmit);
for (GlobalDecl &D : CurDeclsToEmit) {
// We should call GetAddrOfGlobal with IsForDefinition set to true in order
// to get GlobalValue with exactly the type we need, not something that
// might had been created for another decl with the same mangled name but
// different type.
llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
GetAddrOfGlobal(D, ForDefinition));
// In case of different address spaces, we may still get a cast, even with
// IsForDefinition equal to true. Query mangled names table to get
// GlobalValue.
if (!GV)
GV = GetGlobalValue(getMangledName(D));
// Make sure GetGlobalValue returned non-null.
assert(GV);
// Check to see if we've already emitted this. This is necessary
// for a couple of reasons: first, decls can end up in the
// deferred-decls queue multiple times, and second, decls can end
// up with definitions in unusual ways (e.g. by an extern inline
// function acquiring a strong function redefinition). Just
// ignore these cases.
if (!GV->isDeclaration())
continue;
// Otherwise, emit the definition and move on to the next one.
EmitGlobalDefinition(D, GV);
// If we found out that we need to emit more decls, do that recursively.
// This has the advantage that the decls are emitted in a DFS and related
// ones are close together, which is convenient for testing.
if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
EmitDeferred();
assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
}
}
}
void CodeGenModule::EmitVTablesOpportunistically() {
// Try to emit external vtables as available_externally if they have emitted
// all inlined virtual functions. It runs after EmitDeferred() and therefore
// is not allowed to create new references to things that need to be emitted
// lazily. Note that it also uses fact that we eagerly emitting RTTI.
assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
&& "Only emit opportunistic vtables with optimizations");
for (const CXXRecordDecl *RD : OpportunisticVTables) {
assert(getVTables().isVTableExternal(RD) &&
"This queue should only contain external vtables");
if (getCXXABI().canSpeculativelyEmitVTable(RD))
VTables.GenerateClassData(RD);
}
OpportunisticVTables.clear();
}
void CodeGenModule::EmitGlobalAnnotations() {
if (Annotations.empty())
return;
// Create a new global variable for the ConstantStruct in the Module.
llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
Annotations[0]->getType(), Annotations.size()), Annotations);
auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
llvm::GlobalValue::AppendingLinkage,
Array, "llvm.global.annotations");
gv->setSection(AnnotationSection);
}
llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
llvm::Constant *&AStr = AnnotationStrings[Str];
if (AStr)
return AStr;
// Not found yet, create a new global.
llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
auto *gv =
new llvm::GlobalVariable(getModule(), s->getType(), true,
llvm::GlobalValue::PrivateLinkage, s, ".str");
gv->setSection(AnnotationSection);
gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
AStr = gv;
return gv;
}
llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
SourceManager &SM = getContext().getSourceManager();
PresumedLoc PLoc = SM.getPresumedLoc(Loc);
if (PLoc.isValid())
return EmitAnnotationString(PLoc.getFilename());
return EmitAnnotationString(SM.getBufferName(Loc));
}
llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
SourceManager &SM = getContext().getSourceManager();
PresumedLoc PLoc = SM.getPresumedLoc(L);
unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
SM.getExpansionLineNumber(L);
return llvm::ConstantInt::get(Int32Ty, LineNo);
}
llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
const AnnotateAttr *AA,
SourceLocation L) {
// Get the globals for file name, annotation, and the line number.
llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
*UnitGV = EmitAnnotationUnit(L),
*LineNoCst = EmitAnnotationLineNo(L);
// Create the ConstantStruct for the global annotation.
llvm::Constant *Fields[4] = {
llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
LineNoCst
};
return llvm::ConstantStruct::getAnon(Fields);
}
void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
llvm::GlobalValue *GV) {
assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
// Get the struct elements for these annotations.
for (const auto *I : D->specific_attrs<AnnotateAttr>())
Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
}
bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
llvm::Function *Fn,
SourceLocation Loc) const {
const auto &SanitizerBL = getContext().getSanitizerBlacklist();
// Blacklist by function name.
if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
return true;
// Blacklist by location.
if (Loc.isValid())
return SanitizerBL.isBlacklistedLocation(Kind, Loc);
// If location is unknown, this may be a compiler-generated function. Assume
// it's located in the main file.
auto &SM = Context.getSourceManager();
if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
}
return false;
}
bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
SourceLocation Loc, QualType Ty,
StringRef Category) const {
// For now globals can be blacklisted only in ASan and KASan.
const SanitizerMask EnabledAsanMask =
LangOpts.Sanitize.Mask &
(SanitizerKind::Address | SanitizerKind::KernelAddress |
SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
SanitizerKind::MemTag);
if (!EnabledAsanMask)
return false;
const auto &SanitizerBL = getContext().getSanitizerBlacklist();
if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
return true;
if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
return true;
// Check global type.
if (!Ty.isNull()) {
// Drill down the array types: if global variable of a fixed type is
// blacklisted, we also don't instrument arrays of them.
while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
Ty = AT->getElementType();
Ty = Ty.getCanonicalType().getUnqualifiedType();
// We allow to blacklist only record types (classes, structs etc.)
if (Ty->isRecordType()) {
std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
return true;
}
}
return false;
}
bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
StringRef Category) const {
const auto &XRayFilter = getContext().getXRayFilter();
using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
auto Attr = ImbueAttr::NONE;
if (Loc.isValid())
Attr = XRayFilter.shouldImbueLocation(Loc, Category);
if (Attr == ImbueAttr::NONE)
Attr = XRayFilter.shouldImbueFunction(Fn->getName());
switch (Attr) {
case ImbueAttr::NONE:
return false;
case ImbueAttr::ALWAYS:
Fn->addFnAttr("function-instrument", "xray-always");
break;
case ImbueAttr::ALWAYS_ARG1:
Fn->addFnAttr("function-instrument", "xray-always");
Fn->addFnAttr("xray-log-args", "1");
break;
case ImbueAttr::NEVER:
Fn->addFnAttr("function-instrument", "xray-never");
break;
}
return true;
}
bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
// Never defer when EmitAllDecls is specified.
if (LangOpts.EmitAllDecls)
return true;
if (CodeGenOpts.KeepStaticConsts) {
const auto *VD = dyn_cast<VarDecl>(Global);
if (VD && VD->getType().isConstQualified() &&
VD->getStorageDuration() == SD_Static)
return true;
}
return getContext().DeclMustBeEmitted(Global);
}
bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
if (const auto *FD = dyn_cast<FunctionDecl>(Global))
if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
// Implicit template instantiations may change linkage if they are later
// explicitly instantiated, so they should not be emitted eagerly.
return false;
if (const auto *VD = dyn_cast<VarDecl>(Global))
if (Context.getInlineVariableDefinitionKind(VD) ==
ASTContext::InlineVariableDefinitionKind::WeakUnknown)
// A definition of an inline constexpr static data member may change
// linkage later if it's redeclared outside the class.
return false;
// If OpenMP is enabled and threadprivates must be generated like TLS, delay
// codegen for global variables, because they may be marked as threadprivate.
if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
!isTypeConstant(Global->getType(), false) &&
!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
return false;
return true;
}
ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
const CXXUuidofExpr* E) {
// Sema has verified that IIDSource has a __declspec(uuid()), and that its
// well-formed.
StringRef Uuid = E->getUuidStr();
std::string Name = "_GUID_" + Uuid.lower();
std::replace(Name.begin(), Name.end(), '-', '_');
// The UUID descriptor should be pointer aligned.
CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
// Look for an existing global.
if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
return ConstantAddress(GV, Alignment);
llvm::Constant *Init = EmitUuidofInitializer(Uuid);
assert(Init && "failed to initialize as constant");
auto *GV = new llvm::GlobalVariable(
getModule(), Init->getType(),
/*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
if (supportsCOMDAT())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
setDSOLocal(GV);
return ConstantAddress(GV, Alignment);
}
ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
const AliasAttr *AA = VD->getAttr<AliasAttr>();
assert(AA && "No alias?");
CharUnits Alignment = getContext().getDeclAlign(VD);
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
// See if there is already something with the target's name in the module.
llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
if (Entry) {
unsigned AS = getContext().getTargetAddressSpace(VD->getType());
auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
return ConstantAddress(Ptr, Alignment);
}
llvm::Constant *Aliasee;
if (isa<llvm::FunctionType>(DeclTy))
Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
GlobalDecl(cast<FunctionDecl>(VD)),
/*ForVTable=*/false);
else
Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
llvm::PointerType::getUnqual(DeclTy),
nullptr);
auto *F = cast<llvm::GlobalValue>(Aliasee);
F->setLinkage(llvm::Function::ExternalWeakLinkage);
WeakRefReferences.insert(F);
return ConstantAddress(Aliasee, Alignment);
}
void CodeGenModule::EmitGlobal(GlobalDecl GD) {
const auto *Global = cast<ValueDecl>(GD.getDecl());
// Weak references don't produce any output by themselves.
if (Global->hasAttr<WeakRefAttr>())
return;
// If this is an alias definition (which otherwise looks like a declaration)
// emit it now.
if (Global->hasAttr<AliasAttr>())
return EmitAliasDefinition(GD);
// IFunc like an alias whose value is resolved at runtime by calling resolver.
if (Global->hasAttr<IFuncAttr>())
return emitIFuncDefinition(GD);
// If this is a cpu_dispatch multiversion function, emit the resolver.
if (Global->hasAttr<CPUDispatchAttr>())
return emitCPUDispatchDefinition(GD);
// If this is CUDA, be selective about which declarations we emit.
if (LangOpts.CUDA) {
if (LangOpts.CUDAIsDevice) {
if (!Global->hasAttr<CUDADeviceAttr>() &&
!Global->hasAttr<CUDAGlobalAttr>() &&
!Global->hasAttr<CUDAConstantAttr>() &&
!Global->hasAttr<CUDASharedAttr>() &&
!(LangOpts.HIP && Global->hasAttr<HIPPinnedShadowAttr>()))
return;
} else {
// We need to emit host-side 'shadows' for all global
// device-side variables because the CUDA runtime needs their
// size and host-side address in order to provide access to
// their device-side incarnations.
// So device-only functions are the only things we skip.
if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
Global->hasAttr<CUDADeviceAttr>())
return;
assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
"Expected Variable or Function");
}
}
if (LangOpts.OpenMP) {
// If this is OpenMP device, check if it is legal to emit this global
// normally.
if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
return;
if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
if (MustBeEmitted(Global))
EmitOMPDeclareReduction(DRD);
return;
} else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
if (MustBeEmitted(Global))
EmitOMPDeclareMapper(DMD);
return;
}
}
// Ignore declarations, they will be emitted on their first use.
if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
// Forward declarations are emitted lazily on first use.
if (!FD->doesThisDeclarationHaveABody()) {
if (!FD->doesDeclarationForceExternallyVisibleDefinition())
return;
StringRef MangledName = getMangledName(GD);
// Compute the function info and LLVM type.
const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
llvm::Type *Ty = getTypes().GetFunctionType(FI);
GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
/*DontDefer=*/false);
return;
}
} else {
const auto *VD = cast<VarDecl>(Global);
assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
!Context.isMSStaticDataMemberInlineDefinition(VD)) {
if (LangOpts.OpenMP) {
// Emit declaration of the must-be-emitted declare target variable.
if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
bool UnifiedMemoryEnabled =
getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
!UnifiedMemoryEnabled) {
(void)GetAddrOfGlobalVar(VD);
} else {
assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
(*Res == OMPDeclareTargetDeclAttr::MT_To &&
UnifiedMemoryEnabled)) &&
"Link clause or to clause with unified memory expected.");
(void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
}
return;
}
}
// If this declaration may have caused an inline variable definition to
// change linkage, make sure that it's emitted.
if (Context.getInlineVariableDefinitionKind(VD) ==
ASTContext::InlineVariableDefinitionKind::Strong)
GetAddrOfGlobalVar(VD);
return;
}
}
// Defer code generation to first use when possible, e.g. if this is an inline
// function. If the global must always be emitted, do it eagerly if possible
// to benefit from cache locality.
if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
// Emit the definition if it can't be deferred.
EmitGlobalDefinition(GD);
return;
}
// If we're deferring emission of a C++ variable with an
// initializer, remember the order in which it appeared in the file.
if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
cast<VarDecl>(Global)->hasInit()) {
DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
CXXGlobalInits.push_back(nullptr);
}
StringRef MangledName = getMangledName(GD);
if (GetGlobalValue(MangledName) != nullptr) {
// The value has already been used and should therefore be emitted.
addDeferredDeclToEmit(GD);
} else if (MustBeEmitted(Global)) {
// The value must be emitted, but cannot be emitted eagerly.
assert(!MayBeEmittedEagerly(Global));
addDeferredDeclToEmit(GD);
} else {
// Otherwise, remember that we saw a deferred decl with this name. The
// first use of the mangled name will cause it to move into
// DeferredDeclsToEmit.
DeferredDecls[MangledName] = GD;
}
}
// Check if T is a class type with a destructor that's not dllimport.
static bool HasNonDllImportDtor(QualType T) {
if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
return true;
return false;
}
namespace {
struct FunctionIsDirectlyRecursive
: public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
const StringRef Name;
const Builtin::Context &BI;
FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
: Name(N), BI(C) {}
bool VisitCallExpr(const CallExpr *E) {
const FunctionDecl *FD = E->getDirectCallee();
if (!FD)
return false;
AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
if (Attr && Name == Attr->getLabel())
return true;
unsigned BuiltinID = FD->getBuiltinID();
if (!BuiltinID || !BI.isLibFunction(BuiltinID))
return false;
StringRef BuiltinName = BI.getName(BuiltinID);
if (BuiltinName.startswith("__builtin_") &&
Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
return true;
}
return false;
}
bool VisitStmt(const Stmt *S) {
for (const Stmt *Child : S->children())
if (Child && this->Visit(Child))
return true;
return false;
}
};
// Make sure we're not referencing non-imported vars or functions.
struct DLLImportFunctionVisitor
: public RecursiveASTVisitor<DLLImportFunctionVisitor> {
bool SafeToInline = true;
bool shouldVisitImplicitCode() const { return true; }
bool VisitVarDecl(VarDecl *VD) {
if (VD->getTLSKind()) {
// A thread-local variable cannot be imported.
SafeToInline = false;
return SafeToInline;
}
// A variable definition might imply a destructor call.
if (VD->isThisDeclarationADefinition())
SafeToInline = !HasNonDllImportDtor(VD->getType());
return SafeToInline;
}
bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
if (const auto *D = E->getTemporary()->getDestructor())
SafeToInline = D->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitDeclRefExpr(DeclRefExpr *E) {
ValueDecl *VD = E->getDecl();
if (isa<FunctionDecl>(VD))
SafeToInline = VD->hasAttr<DLLImportAttr>();
else if (VarDecl *V = dyn_cast<VarDecl>(VD))
SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitCXXConstructExpr(CXXConstructExpr *E) {
SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
CXXMethodDecl *M = E->getMethodDecl();
if (!M) {
// Call through a pointer to member function. This is safe to inline.
SafeToInline = true;
} else {
SafeToInline = M->hasAttr<DLLImportAttr>();
}
return SafeToInline;
}
bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitCXXNewExpr(CXXNewExpr *E) {
SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
return SafeToInline;
}
};
}
// isTriviallyRecursive - Check if this function calls another
// decl that, because of the asm attribute or the other decl being a builtin,
// ends up pointing to itself.
bool
CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
StringRef Name;
if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
// asm labels are a special kind of mangling we have to support.
AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
if (!Attr)
return false;
Name = Attr->getLabel();
} else {
Name = FD->getName();
}
FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
const Stmt *Body = FD->getBody();
return Body ? Walker.Visit(Body) : false;
}
bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
return true;
const auto *F = cast<FunctionDecl>(GD.getDecl());
if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
return false;
if (F->hasAttr<DLLImportAttr>()) {
// Check whether it would be safe to inline this dllimport function.
DLLImportFunctionVisitor Visitor;
Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
if (!Visitor.SafeToInline)
return false;
if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
// Implicit destructor invocations aren't captured in the AST, so the
// check above can't see them. Check for them manually here.
for (const Decl *Member : Dtor->getParent()->decls())
if (isa<FieldDecl>(Member))
if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
return false;
for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
if (HasNonDllImportDtor(B.getType()))
return false;
}
}
// PR9614. Avoid cases where the source code is lying to us. An available
// externally function should have an equivalent function somewhere else,
// but a function that calls itself is clearly not equivalent to the real
// implementation.
// This happens in glibc's btowc and in some configure checks.
return !isTriviallyRecursive(F);
}
bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
return CodeGenOpts.OptimizationLevel > 0;
}
void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
llvm::GlobalValue *GV) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
if (FD->isCPUSpecificMultiVersion()) {
auto *Spec = FD->getAttr<CPUSpecificAttr>();
for (unsigned I = 0; I < Spec->cpus_size(); ++I)
EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
// Requires multiple emits.
} else
EmitGlobalFunctionDefinition(GD, GV);
}
void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
const auto *D = cast<ValueDecl>(GD.getDecl());
PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Context.getSourceManager(),
"Generating code for declaration");
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
// At -O0, don't generate IR for functions with available_externally
// linkage.
if (!shouldEmitFunction(GD))
return;
llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
std::string Name;
llvm::raw_string_ostream OS(Name);
FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
/*Qualified=*/true);
return Name;
});
if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
// Make sure to emit the definition(s) before we emit the thunks.
// This is necessary for the generation of certain thunks.
if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
ABI->emitCXXStructor(GD);
else if (FD->isMultiVersion())
EmitMultiVersionFunctionDefinition(GD, GV);
else
EmitGlobalFunctionDefinition(GD, GV);
if (Method->isVirtual())
getVTables().EmitThunks(GD);
return;
}
if (FD->isMultiVersion())
return EmitMultiVersionFunctionDefinition(GD, GV);
return EmitGlobalFunctionDefinition(GD, GV);
}
if (const auto *VD = dyn_cast<VarDecl>(D))
return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
}
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
llvm::Function *NewFn);
static unsigned
TargetMVPriority(const TargetInfo &TI,
const CodeGenFunction::MultiVersionResolverOption &RO) {
unsigned Priority = 0;
for (StringRef Feat : RO.Conditions.Features)
Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
if (!RO.Conditions.Architecture.empty())
Priority = std::max(
Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
return Priority;
}
void CodeGenModule::emitMultiVersionFunctions() {
for (GlobalDecl GD : MultiVersionFuncs) {
SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
getContext().forEachMultiversionedFunctionVersion(
FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
GlobalDecl CurGD{
(CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
StringRef MangledName = getMangledName(CurGD);
llvm::Constant *Func = GetGlobalValue(MangledName);
if (!Func) {
if (CurFD->isDefined()) {
EmitGlobalFunctionDefinition(CurGD, nullptr);
Func = GetGlobalValue(MangledName);
} else {
const CGFunctionInfo &FI =
getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
/*DontDefer=*/false, ForDefinition);
}
assert(Func && "This should have just been created");
}
const auto *TA = CurFD->getAttr<TargetAttr>();
llvm::SmallVector<StringRef, 8> Feats;
TA->getAddedFeatures(Feats);
Options.emplace_back(cast<llvm::Function>(Func),
TA->getArchitecture(), Feats);
});
llvm::Function *ResolverFunc;
const TargetInfo &TI = getTarget();
if (TI.supportsIFunc() || FD->isTargetMultiVersion())
ResolverFunc = cast<llvm::Function>(
GetGlobalValue((getMangledName(GD) + ".resolver").str()));
else
ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
if (supportsCOMDAT())
ResolverFunc->setComdat(
getModule().getOrInsertComdat(ResolverFunc->getName()));
llvm::stable_sort(
Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
const CodeGenFunction::MultiVersionResolverOption &RHS) {
return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
});
CodeGenFunction CGF(*this);
CGF.EmitMultiVersionResolver(ResolverFunc, Options);
}
}
void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
assert(FD && "Not a FunctionDecl?");
const auto *DD = FD->getAttr<CPUDispatchAttr>();
assert(DD && "Not a cpu_dispatch Function?");
llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
DeclTy = getTypes().GetFunctionType(FInfo);
}
StringRef ResolverName = getMangledName(GD);
llvm::Type *ResolverType;
GlobalDecl ResolverGD;
if (getTarget().supportsIFunc())
ResolverType = llvm::FunctionType::get(
llvm::PointerType::get(DeclTy,
Context.getTargetAddressSpace(FD->getType())),
false);
else {
ResolverType = DeclTy;
ResolverGD = GD;
}
auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
const TargetInfo &Target = getTarget();
unsigned Index = 0;
for (const IdentifierInfo *II : DD->cpus()) {
// Get the name of the target function so we can look it up/create it.
std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
getCPUSpecificMangling(*this, II->getName());
llvm::Constant *Func = GetGlobalValue(MangledName);
if (!Func) {
GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
if (ExistingDecl.getDecl() &&
ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
Func = GetGlobalValue(MangledName);
} else {
if (!ExistingDecl.getDecl())
ExistingDecl = GD.getWithMultiVersionIndex(Index);
Func = GetOrCreateLLVMFunction(
MangledName, DeclTy, ExistingDecl,
/*ForVTable=*/false, /*DontDefer=*/true,
/*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
}
}
llvm::SmallVector<StringRef, 32> Features;
Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
llvm::transform(Features, Features.begin(),
[](StringRef Str) { return Str.substr(1); });
Features.erase(std::remove_if(
Features.begin(), Features.end(), [&Target](StringRef Feat) {
return !Target.validateCpuSupports(Feat);
}), Features.end());
Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
++Index;
}
llvm::sort(
Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
const CodeGenFunction::MultiVersionResolverOption &RHS) {
return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
});
// If the list contains multiple 'default' versions, such as when it contains
// 'pentium' and 'generic', don't emit the call to the generic one (since we
// always run on at least a 'pentium'). We do this by deleting the 'least
// advanced' (read, lowest mangling letter).
while (Options.size() > 1 &&
CodeGenFunction::GetX86CpuSupportsMask(
(Options.end() - 2)->Conditions.Features) == 0) {
StringRef LHSName = (Options.end() - 2)->Function->getName();
StringRef RHSName = (Options.end() - 1)->Function->getName();
if (LHSName.compare(RHSName) < 0)
Options.erase(Options.end() - 2);
else
Options.erase(Options.end() - 1);
}
CodeGenFunction CGF(*this);
CGF.EmitMultiVersionResolver(ResolverFunc, Options);
}
/// If a dispatcher for the specified mangled name is not in the module, create
/// and return an llvm Function with the specified type.
llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
std::string MangledName =
getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
// Holds the name of the resolver, in ifunc mode this is the ifunc (which has
// a separate resolver).
std::string ResolverName = MangledName;
if (getTarget().supportsIFunc())
ResolverName += ".ifunc";
else if (FD->isTargetMultiVersion())
ResolverName += ".resolver";
// If this already exists, just return that one.
if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
return ResolverGV;
// Since this is the first time we've created this IFunc, make sure
// that we put this multiversioned function into the list to be
// replaced later if necessary (target multiversioning only).
if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
MultiVersionFuncs.push_back(GD);
if (getTarget().supportsIFunc()) {
llvm::Type *ResolverType = llvm::FunctionType::get(
llvm::PointerType::get(
DeclTy, getContext().getTargetAddressSpace(FD->getType())),
false);
llvm::Constant *Resolver = GetOrCreateLLVMFunction(
MangledName + ".resolver", ResolverType, GlobalDecl{},
/*ForVTable=*/false);
llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
GIF->setName(ResolverName);
SetCommonAttributes(FD, GIF);
return GIF;
}
llvm::Constant *Resolver = GetOrCreateLLVMFunction(
ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
assert(isa<llvm::GlobalValue>(Resolver) &&
"Resolver should be created for the first time");
SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
return Resolver;
}
/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
/// module, create and return an llvm Function with the specified type. If there
/// is something in the module with the specified name, return it potentially
/// bitcasted to the right type.
///
/// If D is non-null, it specifies a decl that correspond to this. This is used
/// to set the attributes on the function when it is first created.
llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
ForDefinition_t IsForDefinition) {
const Decl *D = GD.getDecl();
// Any attempts to use a MultiVersion function should result in retrieving
// the iFunc instead. Name Mangling will handle the rest of the changes.
if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
// For the device mark the function as one that should be emitted.
if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
!OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
!DontDefer && !IsForDefinition) {
if (const FunctionDecl *FDDef = FD->getDefinition()) {
GlobalDecl GDDef;
if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
GDDef = GlobalDecl(CD, GD.getCtorType());
else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
GDDef = GlobalDecl(DD, GD.getDtorType());
else
GDDef = GlobalDecl(FDDef);
EmitGlobal(GDDef);
}
}
if (FD->isMultiVersion()) {
const auto *TA = FD->getAttr<TargetAttr>();
if (TA && TA->isDefaultVersion())
UpdateMultiVersionNames(GD, FD);
if (!IsForDefinition)
return GetOrCreateMultiVersionResolver(GD, Ty, FD);
}
}
// Lookup the entry, lazily creating it if necessary.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry) {
if (WeakRefReferences.erase(Entry)) {
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
if (FD && !FD->hasAttr<WeakAttr>())
Entry->setLinkage(llvm::Function::ExternalLinkage);
}
// Handle dropped DLL attributes.
if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
setDSOLocal(Entry);
}
// If there are two attempts to define the same mangled name, issue an
// error.
if (IsForDefinition && !Entry->isDeclaration()) {
GlobalDecl OtherGD;
// Check that GD is not yet in DiagnosedConflictingDefinitions is required
// to make sure that we issue an error only once.
if (lookupRepresentativeDecl(MangledName, OtherGD) &&
(GD.getCanonicalDecl().getDecl() !=
OtherGD.getCanonicalDecl().getDecl()) &&
DiagnosedConflictingDefinitions.insert(GD).second) {
getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
<< MangledName;
getDiags().Report(OtherGD.getDecl()->getLocation(),
diag::note_previous_definition);
}
}
if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
(Entry->getType()->getElementType() == Ty)) {
return Entry;
}
// Make sure the result is of the correct type.
// (If function is requested for a definition, we always need to create a new
// function, not just return a bitcast.)
if (!IsForDefinition)
return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
}
// This function doesn't have a complete type (for example, the return
// type is an incomplete struct). Use a fake type instead, and make
// sure not to try to set attributes.
bool IsIncompleteFunction = false;
llvm::FunctionType *FTy;
if (isa<llvm::FunctionType>(Ty)) {
FTy = cast<llvm::FunctionType>(Ty);
} else {
FTy = llvm::FunctionType::get(VoidTy, false);
IsIncompleteFunction = true;
}
llvm::Function *F =
llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
Entry ? StringRef() : MangledName, &getModule());
// If we already created a function with the same mangled name (but different
// type) before, take its name and add it to the list of functions to be
// replaced with F at the end of CodeGen.
//
// This happens if there is a prototype for a function (e.g. "int f()") and
// then a definition of a different type (e.g. "int f(int x)").
if (Entry) {
F->takeName(Entry);
// This might be an implementation of a function without a prototype, in
// which case, try to do special replacement of calls which match the new
// prototype. The really key thing here is that we also potentially drop
// arguments from the call site so as to make a direct call, which makes the
// inliner happier and suppresses a number of optimizer warnings (!) about
// dropping arguments.
if (!Entry->use_empty()) {
ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
Entry->removeDeadConstantUsers();
}
llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
F, Entry->getType()->getElementType()->getPointerTo());
addGlobalValReplacement(Entry, BC);
}
assert(F->getName() == MangledName && "name was uniqued!");
if (D)
SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
F->addAttributes(llvm::AttributeList::FunctionIndex, B);
}
if (!DontDefer) {
// All MSVC dtors other than the base dtor are linkonce_odr and delegate to
// each other bottoming out with the base dtor. Therefore we emit non-base
// dtors on usage, even if there is no dtor definition in the TU.
if (D && isa<CXXDestructorDecl>(D) &&
getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
GD.getDtorType()))
addDeferredDeclToEmit(GD);
// This is the first use or definition of a mangled name. If there is a
// deferred decl with this name, remember that we need to emit it at the end
// of the file.
auto DDI = DeferredDecls.find(MangledName);
if (DDI != DeferredDecls.end()) {
// Move the potentially referenced deferred decl to the
// DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
// don't need it anymore).
addDeferredDeclToEmit(DDI->second);
DeferredDecls.erase(DDI);
// Otherwise, there are cases we have to worry about where we're
// using a declaration for which we must emit a definition but where
// we might not find a top-level definition:
// - member functions defined inline in their classes
// - friend functions defined inline in some class
// - special member functions with implicit definitions
// If we ever change our AST traversal to walk into class methods,
// this will be unnecessary.
//
// We also don't emit a definition for a function if it's going to be an
// entry in a vtable, unless it's already marked as used.
} else if (getLangOpts().CPlusPlus && D) {
// Look for a declaration that's lexically in a record.
for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
FD = FD->getPreviousDecl()) {
if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
if (FD->doesThisDeclarationHaveABody()) {
addDeferredDeclToEmit(GD.getWithDecl(FD));
break;
}
}
}
}
}
// Make sure the result is of the requested type.
if (!IsIncompleteFunction) {
assert(F->getType()->getElementType() == Ty);
return F;
}
llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
return llvm::ConstantExpr::getBitCast(F, PTy);
}
/// GetAddrOfFunction - Return the address of the given function. If Ty is
/// non-null, then this function will use the specified type if it has to
/// create it (this occurs when we see a definition of the function).
llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
llvm::Type *Ty,
bool ForVTable,
bool DontDefer,
ForDefinition_t IsForDefinition) {
// If there was no specific requested type, just convert it now.
if (!Ty) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
Ty = getTypes().ConvertType(FD->getType());
}
// Devirtualized destructor calls may come through here instead of via
// getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
// of the complete destructor when necessary.
if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
if (getTarget().getCXXABI().isMicrosoft() &&
GD.getDtorType() == Dtor_Complete &&
DD->getParent()->getNumVBases() == 0)
GD = GlobalDecl(DD, Dtor_Base);
}
StringRef MangledName = getMangledName(GD);
return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
/*IsThunk=*/false, llvm::AttributeList(),
IsForDefinition);
}
static const FunctionDecl *
GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
IdentifierInfo &CII = C.Idents.get(Name);
for (const auto &Result : DC->lookup(&CII))
if (const auto FD = dyn_cast<FunctionDecl>(Result))
return FD;
if (!C.getLangOpts().CPlusPlus)
return nullptr;
// Demangle the premangled name from getTerminateFn()
IdentifierInfo &CXXII =
(Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
? C.Idents.get("terminate")
: C.Idents.get(Name);
for (const auto &N : {"__cxxabiv1", "std"}) {
IdentifierInfo &NS = C.Idents.get(N);
for (const auto &Result : DC->lookup(&NS)) {
NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
for (const auto &Result : LSD->lookup(&NS))
if ((ND = dyn_cast<NamespaceDecl>(Result)))
break;
if (ND)
for (const auto &Result : ND->lookup(&CXXII))
if (const auto *FD = dyn_cast<FunctionDecl>(Result))
return FD;
}
}
return nullptr;
}
/// CreateRuntimeFunction - Create a new runtime function with the specified
/// type and name.
llvm::FunctionCallee
CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
llvm::AttributeList ExtraAttrs,
bool Local) {
llvm::Constant *C =
GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
/*DontDefer=*/false, /*IsThunk=*/false,
ExtraAttrs);
if (auto *F = dyn_cast<llvm::Function>(C)) {
if (F->empty()) {
F->setCallingConv(getRuntimeCC());
// In Windows Itanium environments, try to mark runtime functions
// dllimport. For Mingw and MSVC, don't. We don't really know if the user
// will link their standard library statically or dynamically. Marking
// functions imported when they are not imported can cause linker errors
// and warnings.
if (!Local && getTriple().isWindowsItaniumEnvironment() &&
!getCodeGenOpts().LTOVisibilityPublicStd) {
const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
if (!FD || FD->hasAttr<DLLImportAttr>()) {
F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
F->setLinkage(llvm::GlobalValue::ExternalLinkage);
}
}
setDSOLocal(F);
}
}
return {FTy, C};
}
/// isTypeConstant - Determine whether an object of this type can be emitted
/// as a constant.
///
/// If ExcludeCtor is true, the duration when the object's constructor runs
/// will not be considered. The caller will need to verify that the object is
/// not written to during its construction.
bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
if (!Ty.isConstant(Context) && !Ty->isReferenceType())
return false;
if (Context.getLangOpts().CPlusPlus) {
if (const CXXRecordDecl *Record
= Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
return ExcludeCtor && !Record->hasMutableFields() &&
Record->hasTrivialDestructor();
}
return true;
}
/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
/// create and return an llvm GlobalVariable with the specified type. If there
/// is something in the module with the specified name, return it potentially
/// bitcasted to the right type.
///
/// If D is non-null, it specifies a decl that correspond to this. This is used
/// to set the attributes on the global when it is first created.
///
/// If IsForDefinition is true, it is guaranteed that an actual global with
/// type Ty will be returned, not conversion of a variable with the same
/// mangled name but some other type.
llvm::Constant *
CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
llvm::PointerType *Ty,
const VarDecl *D,
ForDefinition_t IsForDefinition) {
// Lookup the entry, lazily creating it if necessary.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry) {
if (WeakRefReferences.erase(Entry)) {
if (D && !D->hasAttr<WeakAttr>())
Entry->setLinkage(llvm::Function::ExternalLinkage);
}
// Handle dropped DLL attributes.
if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
if (Entry->getType() == Ty)
return Entry;
// If there are two attempts to define the same mangled name, issue an
// error.
if (IsForDefinition && !Entry->isDeclaration()) {
GlobalDecl OtherGD;
const VarDecl *OtherD;
// Check that D is not yet in DiagnosedConflictingDefinitions is required
// to make sure that we issue an error only once.
if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
(D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
(OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
OtherD->hasInit() &&
DiagnosedConflictingDefinitions.insert(D).second) {
getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
<< MangledName;
getDiags().Report(OtherGD.getDecl()->getLocation(),
diag::note_previous_definition);
}
}
// Make sure the result is of the correct type.
if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
// (If global is requested for a definition, we always need to create a new
// global, not just return a bitcast.)
if (!IsForDefinition)
return llvm::ConstantExpr::getBitCast(Entry, Ty);
}
auto AddrSpace = GetGlobalVarAddressSpace(D);
auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
auto *GV = new llvm::GlobalVariable(
getModule(), Ty->getElementType(), false,
llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
// If we already created a global with the same mangled name (but different
// type) before, take its name and remove it from its parent.
if (Entry) {
GV->takeName(Entry);
if (!Entry->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Entry->replaceAllUsesWith(NewPtrForOldDecl);
}
Entry->eraseFromParent();
}
// This is the first use or definition of a mangled name. If there is a
// deferred decl with this name, remember that we need to emit it at the end
// of the file.
auto DDI = DeferredDecls.find(MangledName);
if (DDI != DeferredDecls.end()) {
// Move the potentially referenced deferred decl to the DeferredDeclsToEmit
// list, and remove it from DeferredDecls (since we don't need it anymore).
addDeferredDeclToEmit(DDI->second);
DeferredDecls.erase(DDI);
}
// Handle things which are present even on external declarations.
if (D) {
if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
// FIXME: This code is overly simple and should be merged with other global
// handling.
GV->setConstant(isTypeConstant(D->getType(), false));
GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
setLinkageForGV(GV, D);
if (D->getTLSKind()) {
if (D->getTLSKind() == VarDecl::TLS_Dynamic)
CXXThreadLocals.push_back(D);
setTLSMode(GV, *D);
}
setGVProperties(GV, D);
// If required by the ABI, treat declarations of static data members with
// inline initializers as definitions.
if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
EmitGlobalVarDefinition(D);
}
// Emit section information for extern variables.
if (D->hasExternalStorage()) {
if (const SectionAttr *SA = D->getAttr<SectionAttr>())
GV->setSection(SA->getName());
}
// Handle XCore specific ABI requirements.
if (getTriple().getArch() == llvm::Triple::xcore &&
D->getLanguageLinkage() == CLanguageLinkage &&
D->getType().isConstant(Context) &&
isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
GV->setSection(".cp.rodata");
// Check if we a have a const declaration with an initializer, we may be
// able to emit it as available_externally to expose it's value to the
// optimizer.
if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
D->getType().isConstQualified() && !GV->hasInitializer() &&
!D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
const auto *Record =
Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
bool HasMutableFields = Record && Record->hasMutableFields();
if (!HasMutableFields) {
const VarDecl *InitDecl;
const Expr *InitExpr = D->getAnyInitializer(InitDecl);
if (InitExpr) {
ConstantEmitter emitter(*this);
llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
if (Init) {
auto *InitType = Init->getType();
if (GV->getType()->getElementType() != InitType) {
// The type of the initializer does not match the definition.
// This happens when an initializer has a different type from
// the type of the global (because of padding at the end of a
// structure for instance).
GV->setName(StringRef());
// Make a new global with the correct type, this is now guaranteed
// to work.
auto *NewGV = cast<llvm::GlobalVariable>(
GetAddrOfGlobalVar(D, InitType, IsForDefinition));
// Erase the old global, since it is no longer used.
GV->eraseFromParent();
GV = NewGV;
} else {
GV->setInitializer(Init);
GV->setConstant(true);
GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
}
emitter.finalize(GV);
}
}
}
}
}
LangAS ExpectedAS =
D ? D->getType().getAddressSpace()
: (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
assert(getContext().getTargetAddressSpace(ExpectedAS) ==
Ty->getPointerAddressSpace());
if (AddrSpace != ExpectedAS)
return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
ExpectedAS, Ty);
if (GV->isDeclaration())
getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
return GV;
}
llvm::Constant *
CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
ForDefinition_t IsForDefinition) {
const Decl *D = GD.getDecl();
if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
/*DontDefer=*/false, IsForDefinition);
else if (isa<CXXMethodDecl>(D)) {
auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
cast<CXXMethodDecl>(D));
auto Ty = getTypes().GetFunctionType(*FInfo);
return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
IsForDefinition);
} else if (isa<FunctionDecl>(D)) {
const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
IsForDefinition);
} else
return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
IsForDefinition);
}
llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
unsigned Alignment) {
llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
llvm::GlobalVariable *OldGV = nullptr;
if (GV) {
// Check if the variable has the right type.
if (GV->getType()->getElementType() == Ty)
return GV;
// Because C++ name mangling, the only way we can end up with an already
// existing global with the same name is if it has been declared extern "C".
assert(GV->isDeclaration() && "Declaration has wrong type!");
OldGV = GV;
}
// Create a new variable.
GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Linkage, nullptr, Name);
if (OldGV) {
// Replace occurrences of the old variable if needed.
GV->takeName(OldGV);
if (!OldGV->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
OldGV->replaceAllUsesWith(NewPtrForOldDecl);
}
OldGV->eraseFromParent();
}
if (supportsCOMDAT() && GV->isWeakForLinker() &&
!GV->hasAvailableExternallyLinkage())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
GV->setAlignment(Alignment);
return GV;
}
/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
/// given global variable. If Ty is non-null and if the global doesn't exist,
/// then it will be created with the specified type instead of whatever the
/// normal requested type would be. If IsForDefinition is true, it is guaranteed
/// that an actual global with type Ty will be returned, not conversion of a
/// variable with the same mangled name but some other type.
llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
llvm::Type *Ty,
ForDefinition_t IsForDefinition) {
assert(D->hasGlobalStorage() && "Not a global variable");
QualType ASTTy = D->getType();
if (!Ty)
Ty = getTypes().ConvertTypeForMem(ASTTy);
llvm::PointerType *PTy =
llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
StringRef MangledName = getMangledName(D);
return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
}
/// CreateRuntimeVariable - Create a new runtime global variable with the
/// specified type and name.
llvm::Constant *
CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
StringRef Name) {
auto PtrTy =
getContext().getLangOpts().OpenCL
? llvm::PointerType::get(
Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
: llvm::PointerType::getUnqual(Ty);
auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
return Ret;
}
void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
assert(!D->getInit() && "Cannot emit definite definitions here!");
StringRef MangledName = getMangledName(D);
llvm::GlobalValue *GV = GetGlobalValue(MangledName);
// We already have a definition, not declaration, with the same mangled name.
// Emitting of declaration is not required (and actually overwrites emitted
// definition).
if (GV && !GV->isDeclaration())
return;
// If we have not seen a reference to this variable yet, place it into the
// deferred declarations table to be emitted if needed later.
if (!MustBeEmitted(D) && !GV) {
DeferredDecls[MangledName] = D;
return;
}
// The tentative definition is the only definition.
EmitGlobalVarDefinition(D);
}
CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
return Context.toCharUnitsFromBits(
getDataLayout().getTypeStoreSizeInBits(Ty));
}
LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
LangAS AddrSpace = LangAS::Default;
if (LangOpts.OpenCL) {
AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
assert(AddrSpace == LangAS::opencl_global ||
AddrSpace == LangAS::opencl_constant ||
AddrSpace == LangAS::opencl_local ||
AddrSpace >= LangAS::FirstTargetAddressSpace);
return AddrSpace;
}
if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
if (D && D->hasAttr<CUDAConstantAttr>())
return LangAS::cuda_constant;
else if (D && D->hasAttr<CUDASharedAttr>())
return LangAS::cuda_shared;
else if (D && D->hasAttr<CUDADeviceAttr>())
return LangAS::cuda_device;
else if (D && D->getType().isConstQualified())
return LangAS::cuda_constant;
else
return LangAS::cuda_device;
}
if (LangOpts.OpenMP) {
LangAS AS;
if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
return AS;
}
return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
}
LangAS CodeGenModule::getStringLiteralAddressSpace() const {
// OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
if (LangOpts.OpenCL)
return LangAS::opencl_constant;
if (auto AS = getTarget().getConstantAddressSpace())
return AS.getValue();
return LangAS::Default;
}
// In address space agnostic languages, string literals are in default address
// space in AST. However, certain targets (e.g. amdgcn) request them to be
// emitted in constant address space in LLVM IR. To be consistent with other
// parts of AST, string literal global variables in constant address space
// need to be casted to default address space before being put into address
// map and referenced by other part of CodeGen.
// In OpenCL, string literals are in constant address space in AST, therefore
// they should not be casted to default address space.
static llvm::Constant *
castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
llvm::GlobalVariable *GV) {
llvm::Constant *Cast = GV;
if (!CGM.getLangOpts().OpenCL) {
if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
if (AS != LangAS::Default)
Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
CGM, GV, AS.getValue(), LangAS::Default,
GV->getValueType()->getPointerTo(
CGM.getContext().getTargetAddressSpace(LangAS::Default)));
}
}
return Cast;
}
template<typename SomeDecl>
void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
llvm::GlobalValue *GV) {
if (!getLangOpts().CPlusPlus)
return;
// Must have 'used' attribute, or else inline assembly can't rely on
// the name existing.
if (!D->template hasAttr<UsedAttr>())
return;
// Must have internal linkage and an ordinary name.
if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
return;
// Must be in an extern "C" context. Entities declared directly within
// a record are not extern "C" even if the record is in such a context.
const SomeDecl *First = D->getFirstDecl();
if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
return;
// OK, this is an internal linkage entity inside an extern "C" linkage
// specification. Make a note of that so we can give it the "expected"
// mangled name if nothing else is using that name.
std::pair<StaticExternCMap::iterator, bool> R =
StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
// If we have multiple internal linkage entities with the same name
// in extern "C" regions, none of them gets that name.
if (!R.second)
R.first->second = nullptr;
}
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
if (!CGM.supportsCOMDAT())
return false;
// Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
// them being "merged" by the COMDAT Folding linker optimization.
if (D.hasAttr<CUDAGlobalAttr>())
return false;
if (D.hasAttr<SelectAnyAttr>())
return true;
GVALinkage Linkage;
if (auto *VD = dyn_cast<VarDecl>(&D))
Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
else
Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
switch (Linkage) {
case GVA_Internal:
case GVA_AvailableExternally:
case GVA_StrongExternal:
return false;
case GVA_DiscardableODR:
case GVA_StrongODR:
return true;
}
llvm_unreachable("No such linkage");
}
void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
llvm::GlobalObject &GO) {
if (!shouldBeInCOMDAT(*this, D))
return;
GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
}
/// Pass IsTentative as true if you want to create a tentative definition.
void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
bool IsTentative) {
// OpenCL global variables of sampler type are translated to function calls,
// therefore no need to be translated.
QualType ASTTy = D->getType();
if (getLangOpts().OpenCL && ASTTy->isSamplerT())
return;
// If this is OpenMP device, check if it is legal to emit this global
// normally.
if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
OpenMPRuntime->emitTargetGlobalVariable(D))
return;
llvm::Constant *Init = nullptr;
CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
bool NeedsGlobalCtor = false;
bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
const VarDecl *InitDecl;
const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Optional<ConstantEmitter> emitter;
// CUDA E.2.4.1 "__shared__ variables cannot have an initialization
// as part of their declaration." Sema has already checked for
// error cases, so we just need to set Init to UndefValue.
bool IsCUDASharedVar =
getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
// Shadows of initialized device-side global variables are also left
// undefined.
bool IsCUDAShadowVar =
!getLangOpts().CUDAIsDevice &&
(D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
D->hasAttr<CUDASharedAttr>());
// HIP pinned shadow of initialized host-side global variables are also
// left undefined.
bool IsHIPPinnedShadowVar =
getLangOpts().CUDAIsDevice && D->hasAttr<HIPPinnedShadowAttr>();
if (getLangOpts().CUDA &&
(IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar))
Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
else if (!InitExpr) {
// This is a tentative definition; tentative definitions are
// implicitly initialized with { 0 }.
//
// Note that tentative definitions are only emitted at the end of
// a translation unit, so they should never have incomplete
// type. In addition, EmitTentativeDefinition makes sure that we
// never attempt to emit a tentative definition if a real one
// exists. A use may still exists, however, so we still may need
// to do a RAUW.
assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Init = EmitNullConstant(D->getType());
} else {
initializedGlobalDecl = GlobalDecl(D);
emitter.emplace(*this);
Init = emitter->tryEmitForInitializer(*InitDecl);
if (!Init) {
QualType T = InitExpr->getType();
if (D->getType()->isReferenceType())
T = D->getType();
if (getLangOpts().CPlusPlus) {
Init = EmitNullConstant(T);
NeedsGlobalCtor = true;
} else {
ErrorUnsupported(D, "static initializer");
Init = llvm::UndefValue::get(getTypes().ConvertType(T));
}
} else {
// We don't need an initializer, so remove the entry for the delayed
// initializer position (just in case this entry was delayed) if we
// also don't need to register a destructor.
if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
DelayedCXXInitPosition.erase(D);
}
}
llvm::Type* InitType = Init->getType();
llvm::Constant *Entry =
GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
// Strip off a bitcast if we got one back.
if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
assert(CE->getOpcode() == llvm::Instruction::BitCast ||
CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
// All zero index gep.
CE->getOpcode() == llvm::Instruction::GetElementPtr);
Entry = CE->getOperand(0);
}
// Entry is now either a Function or GlobalVariable.
auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
// We have a definition after a declaration with the wrong type.
// We must make a new GlobalVariable* and update everything that used OldGV
// (a declaration or tentative definition) with the new GlobalVariable*
// (which will be a definition).
//
// This happens if there is a prototype for a global (e.g.
// "extern int x[];") and then a definition of a different type (e.g.
// "int x[10];"). This also happens when an initializer has a different type
// from the type of the global (this happens with unions).
if (!GV || GV->getType()->getElementType() != InitType ||
GV->getType()->getAddressSpace() !=
getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
// Move the old entry aside so that we'll create a new one.
Entry->setName(StringRef());
// Make a new global with the correct type, this is now guaranteed to work.
GV = cast<llvm::GlobalVariable>(
GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
// Replace all uses of the old global with the new global
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Entry->replaceAllUsesWith(NewPtrForOldDecl);
// Erase the old global, since it is no longer used.
cast<llvm::GlobalValue>(Entry)->eraseFromParent();
}
MaybeHandleStaticInExternC(D, GV);
if (D->hasAttr<AnnotateAttr>())
AddGlobalAnnotations(D, GV);
// Set the llvm linkage type as appropriate.
llvm::GlobalValue::LinkageTypes Linkage =
getLLVMLinkageVarDefinition(D, GV->isConstant());
// CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
// the device. [...]"
// CUDA B.2.2 "The __constant__ qualifier, optionally used together with
// __device__, declares a variable that: [...]
// Is accessible from all the threads within the grid and from the host
// through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
// / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
if (GV && LangOpts.CUDA) {
if (LangOpts.CUDAIsDevice) {
if (Linkage != llvm::GlobalValue::InternalLinkage &&
(D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
GV->setExternallyInitialized(true);
} else {
// Host-side shadows of external declarations of device-side
// global variables become internal definitions. These have to
// be internal in order to prevent name conflicts with global
// host variables with the same name in a different TUs.
if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
D->hasAttr<HIPPinnedShadowAttr>()) {
Linkage = llvm::GlobalValue::InternalLinkage;
// Shadow variables and their properties must be registered
// with CUDA runtime.
unsigned Flags = 0;
if (!D->hasDefinition())
Flags |= CGCUDARuntime::ExternDeviceVar;
if (D->hasAttr<CUDAConstantAttr>())
Flags |= CGCUDARuntime::ConstantDeviceVar;
// Extern global variables will be registered in the TU where they are
// defined.
if (!D->hasExternalStorage())
getCUDARuntime().registerDeviceVar(D, *GV, Flags);
} else if (D->hasAttr<CUDASharedAttr>())
// __shared__ variables are odd. Shadows do get created, but
// they are not registered with the CUDA runtime, so they
// can't really be used to access their device-side
// counterparts. It's not clear yet whether it's nvcc's bug or
// a feature, but we've got to do the same for compatibility.
Linkage = llvm::GlobalValue::InternalLinkage;
}
}
if (!IsHIPPinnedShadowVar)
GV->setInitializer(Init);
if (emitter) emitter->finalize(GV);
// If it is safe to mark the global 'constant', do so now.
GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
isTypeConstant(D->getType(), true));
// If it is in a read-only section, mark it 'constant'.
if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
GV->setConstant(true);
}
GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
// On Darwin, if the normal linkage of a C++ thread_local variable is
// LinkOnce or Weak, we keep the normal linkage to prevent multiple
// copies within a linkage unit; otherwise, the backing variable has
// internal linkage and all accesses should just be calls to the
// Itanium-specified entry point, which has the normal linkage of the
// variable. This is to preserve the ability to change the implementation
// behind the scenes.
if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Context.getTargetInfo().getTriple().isOSDarwin() &&
!llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
!llvm::GlobalVariable::isWeakLinkage(Linkage))
Linkage = llvm::GlobalValue::InternalLinkage;
GV->setLinkage(Linkage);
if (D->hasAttr<DLLImportAttr>())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
else if (D->hasAttr<DLLExportAttr>())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
else
GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
if (Linkage == llvm::GlobalVariable::CommonLinkage) {
// common vars aren't constant even if declared const.
GV->setConstant(false);
// Tentative definition of global variables may be initialized with
// non-zero null pointers. In this case they should have weak linkage
// since common linkage must have zero initializer and must not have
// explicit section therefore cannot have non-zero initial value.
if (!GV->getInitializer()->isNullValue())
GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
}
setNonAliasAttributes(D, GV);
if (D->getTLSKind() && !GV->isThreadLocal()) {
if (D->getTLSKind() == VarDecl::TLS_Dynamic)
CXXThreadLocals.push_back(D);
setTLSMode(GV, *D);
}
maybeSetTrivialComdat(*D, *GV);
// Emit the initializer function if necessary.
if (NeedsGlobalCtor || NeedsGlobalDtor)
EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
// Emit global variable debug information.
if (CGDebugInfo *DI = getModuleDebugInfo())
if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
DI->EmitGlobalVariable(GV, D);
}
static bool isVarDeclStrongDefinition(const ASTContext &Context,
CodeGenModule &CGM, const VarDecl *D,
bool NoCommon) {
// Don't give variables common linkage if -fno-common was specified unless it
// was overridden by a NoCommon attribute.
if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
return true;
// C11 6.9.2/2:
// A declaration of an identifier for an object that has file scope without
// an initializer, and without a storage-class specifier or with the
// storage-class specifier static, constitutes a tentative definition.
if (D->getInit() || D->hasExternalStorage())
return true;
// A variable cannot be both common and exist in a section.
if (D->hasAttr<SectionAttr>())
return true;
// A variable cannot be both common and exist in a section.
// We don't try to determine which is the right section in the front-end.
// If no specialized section name is applicable, it will resort to default.
if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
D->hasAttr<PragmaClangDataSectionAttr>() ||
D->hasAttr<PragmaClangRodataSectionAttr>())
return true;
// Thread local vars aren't considered common linkage.
if (D->getTLSKind())
return true;
// Tentative definitions marked with WeakImportAttr are true definitions.
if (D->hasAttr<WeakImportAttr>())
return true;
// A variable cannot be both common and exist in a comdat.
if (shouldBeInCOMDAT(CGM, *D))
return true;
// Declarations with a required alignment do not have common linkage in MSVC
// mode.
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
if (D->hasAttr<AlignedAttr>())
return true;
QualType VarType = D->getType();
if (Context.isAlignmentRequired(VarType))
return true;
if (const auto *RT = VarType->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
for (const FieldDecl *FD : RD->fields()) {
if (FD->isBitField())
continue;
if (FD->hasAttr<AlignedAttr>())
return true;
if (Context.isAlignmentRequired(FD->getType()))
return true;
}
}
}
// Microsoft's link.exe doesn't support alignments greater than 32 bytes for
// common symbols, so symbols with greater alignment requirements cannot be
// common.
// Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
// alignments for common symbols via the aligncomm directive, so this
// restriction only applies to MSVC environments.
if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
Context.getTypeAlignIfKnown(D->getType()) >
Context.toBits(CharUnits::fromQuantity(32)))
return true;
return false;
}
llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
if (Linkage == GVA_Internal)
return llvm::Function::InternalLinkage;
if (D->hasAttr<WeakAttr>()) {
if (IsConstantVariable)
return llvm::GlobalVariable::WeakODRLinkage;
else
return llvm::GlobalVariable::WeakAnyLinkage;
}
if (const auto *FD = D->getAsFunction())
if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
return llvm::GlobalVariable::LinkOnceAnyLinkage;
// We are guaranteed to have a strong definition somewhere else,
// so we can use available_externally linkage.
if (Linkage == GVA_AvailableExternally)
return llvm::GlobalValue::AvailableExternallyLinkage;
// Note that Apple's kernel linker doesn't support symbol
// coalescing, so we need to avoid linkonce and weak linkages there.
// Normally, this means we just map to internal, but for explicit
// instantiations we'll map to external.
// In C++, the compiler has to emit a definition in every translation unit
// that references the function. We should use linkonce_odr because
// a) if all references in this translation unit are optimized away, we
// don't need to codegen it. b) if the function persists, it needs to be
// merged with other definitions. c) C++ has the ODR, so we know the
// definition is dependable.
if (Linkage == GVA_DiscardableODR)
return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
: llvm::Function::InternalLinkage;
// An explicit instantiation of a template has weak linkage, since
// explicit instantiations can occur in multiple translation units
// and must all be equivalent. However, we are not allowed to
// throw away these explicit instantiations.
//
// We don't currently support CUDA device code spread out across multiple TUs,
// so say that CUDA templates are either external (for kernels) or internal.
// This lets llvm perform aggressive inter-procedural optimizations.
if (Linkage == GVA_StrongODR) {
if (Context.getLangOpts().AppleKext)
return llvm::Function::ExternalLinkage;
if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
: llvm::Function::InternalLinkage;
return llvm::Function::WeakODRLinkage;
}
// C++ doesn't have tentative definitions and thus cannot have common
// linkage.
if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
!isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
CodeGenOpts.NoCommon))
return llvm::GlobalVariable::CommonLinkage;
// selectany symbols are externally visible, so use weak instead of
// linkonce. MSVC optimizes away references to const selectany globals, so
// all definitions should be the same and ODR linkage should be used.
// http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
if (D->hasAttr<SelectAnyAttr>())
return llvm::GlobalVariable::WeakODRLinkage;
// Otherwise, we have strong external linkage.
assert(Linkage == GVA_StrongExternal);
return llvm::GlobalVariable::ExternalLinkage;
}
llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
const VarDecl *VD, bool IsConstant) {
GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
}
/// Replace the uses of a function that was declared with a non-proto type.
/// We want to silently drop extra arguments from call sites
static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
llvm::Function *newFn) {
// Fast path.
if (old->use_empty()) return;
llvm::Type *newRetTy = newFn->getReturnType();
SmallVector<llvm::Value*, 4> newArgs;
SmallVector<llvm::OperandBundleDef, 1> newBundles;
for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
ui != ue; ) {
llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
llvm::User *user = use->getUser();
// Recognize and replace uses of bitcasts. Most calls to
// unprototyped functions will use bitcasts.
if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
if (bitcast->getOpcode() == llvm::Instruction::BitCast)
replaceUsesOfNonProtoConstant(bitcast, newFn);
continue;
}
// Recognize calls to the function.
llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
if (!callSite) continue;
if (!callSite->isCallee(&*use))
continue;
// If the return types don't match exactly, then we can't
// transform this call unless it's dead.
if (callSite->getType() != newRetTy && !callSite->use_empty())
continue;
// Get the call site's attribute list.
SmallVector<llvm::AttributeSet, 8> newArgAttrs;
llvm::AttributeList oldAttrs = callSite->getAttributes();
// If the function was passed too few arguments, don't transform.
unsigned newNumArgs = newFn->arg_size();
if (callSite->arg_size() < newNumArgs)
continue;
// If extra arguments were passed, we silently drop them.
// If any of the types mismatch, we don't transform.
unsigned argNo = 0;
bool dontTransform = false;
for (llvm::Argument &A : newFn->args()) {
if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
dontTransform = true;
break;
}
// Add any parameter attributes.
newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
argNo++;
}
if (dontTransform)
continue;
// Okay, we can transform this. Create the new call instruction and copy
// over the required information.
newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
// Copy over any operand bundles.
callSite->getOperandBundlesAsDefs(newBundles);
llvm::CallBase *newCall;
if (dyn_cast<llvm::CallInst>(callSite)) {
newCall =
llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
} else {
auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
oldInvoke->getUnwindDest(), newArgs,
newBundles, "", callSite);
}
newArgs.clear(); // for the next iteration
if (!newCall->getType()->isVoidTy())
newCall->takeName(callSite);
newCall->setAttributes(llvm::AttributeList::get(
newFn->getContext(), oldAttrs.getFnAttributes(),
oldAttrs.getRetAttributes(), newArgAttrs));
newCall->setCallingConv(callSite->getCallingConv());
// Finally, remove the old call, replacing any uses with the new one.
if (!callSite->use_empty())
callSite->replaceAllUsesWith(newCall);
// Copy debug location attached to CI.
if (callSite->getDebugLoc())
newCall->setDebugLoc(callSite->getDebugLoc());
callSite->eraseFromParent();
}
}
/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
/// implement a function with no prototype, e.g. "int foo() {}". If there are
/// existing call uses of the old function in the module, this adjusts them to
/// call the new function directly.
///
/// This is not just a cleanup: the always_inline pass requires direct calls to
/// functions to be able to inline them. If there is a bitcast in the way, it
/// won't inline them. Instcombine normally deletes these calls, but it isn't
/// run at -O0.
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
llvm::Function *NewFn) {
// If we're redefining a global as a function, don't transform it.
if (!isa<llvm::Function>(Old)) return;
replaceUsesOfNonProtoConstant(Old, NewFn);
}
void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
auto DK = VD->isThisDeclarationADefinition();
if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
return;
TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
// If we have a definition, this might be a deferred decl. If the
// instantiation is explicit, make sure we emit it at the end.
if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
GetAddrOfGlobalVar(VD);
EmitTopLevelDecl(VD);
}
void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
llvm::GlobalValue *GV) {
const auto *D = cast<FunctionDecl>(GD.getDecl());
// Compute the function info and LLVM type.
const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
// Get or create the prototype for the function.
if (!GV || (GV->getType()->getElementType() != Ty))
GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
/*DontDefer=*/true,
ForDefinition));
// Already emitted.
if (!GV->isDeclaration())
return;
// We need to set linkage and visibility on the function before
// generating code for it because various parts of IR generation
// want to propagate this information down (e.g. to local static
// declarations).
auto *Fn = cast<llvm::Function>(GV);
setFunctionLinkage(GD, Fn);
// FIXME: this is redundant with part of setFunctionDefinitionAttributes
setGVProperties(Fn, GD);
MaybeHandleStaticInExternC(D, Fn);
maybeSetTrivialComdat(*D, *Fn);
CodeGenFunction(*this).GenerateCode(D, Fn, FI);
setNonAliasAttributes(GD, Fn);
SetLLVMFunctionAttributesForDefinition(D, Fn);
if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
AddGlobalCtor(Fn, CA->getPriority());
if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
AddGlobalDtor(Fn, DA->getPriority());
if (D->hasAttr<AnnotateAttr>())
AddGlobalAnnotations(D, Fn);
}
void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
const auto *D = cast<ValueDecl>(GD.getDecl());
const AliasAttr *AA = D->getAttr<AliasAttr>();
assert(AA && "Not an alias?");
StringRef MangledName = getMangledName(GD);
if (AA->getAliasee() == MangledName) {
Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
return;
}
// If there is a definition in the module, then it wins over the alias.
// This is dubious, but allow it to be safe. Just ignore the alias.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration())
return;
Aliases.push_back(GD);
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
// Create a reference to the named value. This ensures that it is emitted
// if a deferred decl.
llvm::Constant *Aliasee;
llvm::GlobalValue::LinkageTypes LT;
if (isa<llvm::FunctionType>(DeclTy)) {
Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
/*ForVTable=*/false);
LT = getFunctionLinkage(GD);
} else {
Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
llvm::PointerType::getUnqual(DeclTy),
/*D=*/nullptr);
LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
D->getType().isConstQualified());
}
// Create the new alias itself, but don't set a name yet.
auto *GA =
llvm::GlobalAlias::create(DeclTy, 0, LT, "", Aliasee, &getModule());
if (Entry) {
if (GA->getAliasee() == Entry) {
Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
return;
}
assert(Entry->isDeclaration());
// If there is a declaration in the module, then we had an extern followed
// by the alias, as in:
// extern int test6();
// ...
// int test6() __attribute__((alias("test7")));
//
// Remove it and replace uses of it with the alias.
GA->takeName(Entry);
Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Entry->getType()));
Entry->eraseFromParent();
} else {
GA->setName(MangledName);
}
// Set attributes which are particular to an alias; this is a
// specialization of the attributes which may be set on a global
// variable/function.
if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
D->isWeakImported()) {
GA->setLinkage(llvm::Function::WeakAnyLinkage);
}
if (const auto *VD = dyn_cast<VarDecl>(D))
if (VD->getTLSKind())
setTLSMode(GA, *VD);
SetCommonAttributes(GD, GA);
}
void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
const auto *D = cast<ValueDecl>(GD.getDecl());
const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
assert(IFA && "Not an ifunc?");
StringRef MangledName = getMangledName(GD);
if (IFA->getResolver() == MangledName) {
Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
return;
}
// Report an error if some definition overrides ifunc.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration()) {
GlobalDecl OtherGD;
if (lookupRepresentativeDecl(MangledName, OtherGD) &&
DiagnosedConflictingDefinitions.insert(GD).second) {
Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
<< MangledName;
Diags.Report(OtherGD.getDecl()->getLocation(),
diag::note_previous_definition);
}
return;
}
Aliases.push_back(GD);
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
llvm::Constant *Resolver =
GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
/*ForVTable=*/false);
llvm::GlobalIFunc *GIF =
llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
"", Resolver, &getModule());
if (Entry) {
if (GIF->getResolver() == Entry) {
Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
return;
}
assert(Entry->isDeclaration());
// If there is a declaration in the module, then we had an extern followed
// by the ifunc, as in:
// extern int test();
// ...
// int test() __attribute__((ifunc("resolver")));
//
// Remove it and replace uses of it with the ifunc.
GIF->takeName(Entry);
Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
Entry->getType()));
Entry->eraseFromParent();
} else
GIF->setName(MangledName);
SetCommonAttributes(GD, GIF);
}
llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
ArrayRef<llvm::Type*> Tys) {
return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Tys);
}
static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
const StringLiteral *Literal, bool TargetIsLSB,
bool &IsUTF16, unsigned &StringLength) {
StringRef String = Literal->getString();
unsigned NumBytes = String.size();
// Check for simple case.
if (!Literal->containsNonAsciiOrNull()) {
StringLength = NumBytes;
return *Map.insert(std::make_pair(String, nullptr)).first;
}
// Otherwise, convert the UTF8 literals into a string of shorts.
IsUTF16 = true;
SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
llvm::UTF16 *ToPtr = &ToBuf[0];
(void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
ToPtr + NumBytes, llvm::strictConversion);
// ConvertUTF8toUTF16 returns the length in ToPtr.
StringLength = ToPtr - &ToBuf[0];
// Add an explicit null.
*ToPtr = 0;
return *Map.insert(std::make_pair(
StringRef(reinterpret_cast<const char *>(ToBuf.data()),
(StringLength + 1) * 2),
nullptr)).first;
}
ConstantAddress
CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
unsigned StringLength = 0;
bool isUTF16 = false;
llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
GetConstantCFStringEntry(CFConstantStringMap, Literal,
getDataLayout().isLittleEndian(), isUTF16,
StringLength);
if (auto *C = Entry.second)
return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
llvm::Constant *Zeros[] = { Zero, Zero };
const ASTContext &Context = getContext();
const llvm::Triple &Triple = getTriple();
const auto CFRuntime = getLangOpts().CFRuntime;
const bool IsSwiftABI =
static_cast<unsigned>(CFRuntime) >=
static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
// If we don't already have it, get __CFConstantStringClassReference.
if (!CFConstantStringClassRef) {
const char *CFConstantStringClassName = "__CFConstantStringClassReference";
llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Ty = llvm::ArrayType::get(Ty, 0);
switch (CFRuntime) {
default: break;
case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
case LangOptions::CoreFoundationABI::Swift5_0:
CFConstantStringClassName =
Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
: "$s10Foundation19_NSCFConstantStringCN";
Ty = IntPtrTy;
break;
case LangOptions::CoreFoundationABI::Swift4_2:
CFConstantStringClassName =
Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
: "$S10Foundation19_NSCFConstantStringCN";
Ty = IntPtrTy;
break;
case LangOptions::CoreFoundationABI::Swift4_1:
CFConstantStringClassName =
Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
: "__T010Foundation19_NSCFConstantStringCN";
Ty = IntPtrTy;
break;
}
llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
llvm::GlobalValue *GV = nullptr;
if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
IdentifierInfo &II = Context.Idents.get(GV->getName());
TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
const VarDecl *VD = nullptr;
for (const auto &Result : DC->lookup(&II))
if ((VD = dyn_cast<VarDecl>(Result)))
break;
if (Triple.isOSBinFormatELF()) {
if (!VD)
GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
} else {
GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
if (!VD || !VD->hasAttr<DLLExportAttr>())
GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
else
GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
}
setDSOLocal(GV);
}
}
// Decay array -> ptr
CFConstantStringClassRef =
IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
: llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
}
QualType CFTy = Context.getCFConstantStringType();
auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
ConstantInitBuilder Builder(*this);
auto Fields = Builder.beginStruct(STy);
// Class pointer.
Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
// Flags.
if (IsSwiftABI) {
Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
} else {
Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
}
// String pointer.
llvm::Constant *C = nullptr;
if (isUTF16) {
auto Arr = llvm::makeArrayRef(
reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
Entry.first().size() / 2);
C = llvm::ConstantDataArray::get(VMContext, Arr);
} else {
C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
}
// Note: -fwritable-strings doesn't make the backing store strings of
// CFStrings writable. (See <rdar://problem/10657500>)
auto *GV =
new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
llvm::GlobalValue::PrivateLinkage, C, ".str");
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
// Don't enforce the target's minimum global alignment, since the only use
// of the string is via this class initializer.
CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
: Context.getTypeAlignInChars(Context.CharTy);
GV->setAlignment(Align.getQuantity());
// FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
// Without it LLVM can merge the string with a non unnamed_addr one during
// LTO. Doing that changes the section it ends in, which surprises ld64.
if (Triple.isOSBinFormatMachO())
GV->setSection(isUTF16 ? "__TEXT,__ustring"
: "__TEXT,__cstring,cstring_literals");
// Make sure the literal ends up in .rodata to allow for safe ICF and for
// the static linker to adjust permissions to read-only later on.
else if (Triple.isOSBinFormatELF())
GV->setSection(".rodata");
// String.
llvm::Constant *Str =
llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
if (isUTF16)
// Cast the UTF16 string to the correct type.
Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
Fields.add(Str);
// String length.
llvm::IntegerType *LengthTy =
llvm::IntegerType::get(getModule().getContext(),
Context.getTargetInfo().getLongWidth());
if (IsSwiftABI) {
if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
LengthTy = Int32Ty;
else
LengthTy = IntPtrTy;
}
Fields.addInt(LengthTy, StringLength);
CharUnits Alignment = getPointerAlign();
// The struct.
GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
/*isConstant=*/false,
llvm::GlobalVariable::PrivateLinkage);
GV->addAttribute("objc_arc_inert");
switch (Triple.getObjectFormat()) {
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("unknown file format");
case llvm::Triple::XCOFF:
llvm_unreachable("XCOFF is not yet implemented");
case llvm::Triple::COFF:
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
GV->setSection("cfstring");
break;
case llvm::Triple::MachO:
GV->setSection("__DATA,__cfstring");
break;
}
Entry.second = GV;
return ConstantAddress(GV, Alignment);
}
bool CodeGenModule::getExpressionLocationsEnabled() const {
return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
}
QualType CodeGenModule::getObjCFastEnumerationStateType() {
if (ObjCFastEnumerationStateType.isNull()) {
RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
D->startDefinition();
QualType FieldTypes[] = {
Context.UnsignedLongTy,
Context.getPointerType(Context.getObjCIdType()),
Context.getPointerType(Context.UnsignedLongTy),
Context.getConstantArrayType(Context.UnsignedLongTy,
llvm::APInt(32, 5), ArrayType::Normal, 0)
};
for (size_t i = 0; i < 4; ++i) {
FieldDecl *Field = FieldDecl::Create(Context,
D,
SourceLocation(),
SourceLocation(), nullptr,
FieldTypes[i], /*TInfo=*/nullptr,
/*BitWidth=*/nullptr,
/*Mutable=*/false,
ICIS_NoInit);
Field->setAccess(AS_public);
D->addDecl(Field);
}
D->completeDefinition();
ObjCFastEnumerationStateType = Context.getTagDeclType(D);
}
return ObjCFastEnumerationStateType;
}
llvm::Constant *
CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
assert(!E->getType()->isPointerType() && "Strings are always arrays");
// Don't emit it as the address of the string, emit the string data itself
// as an inline array.
if (E->getCharByteWidth() == 1) {
SmallString<64> Str(E->getString());
// Resize the string to the right size, which is indicated by its type.
const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
Str.resize(CAT->getSize().getZExtValue());
return llvm::ConstantDataArray::getString(VMContext, Str, false);
}
auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
llvm::Type *ElemTy = AType->getElementType();
unsigned NumElements = AType->getNumElements();
// Wide strings have either 2-byte or 4-byte elements.
if (ElemTy->getPrimitiveSizeInBits() == 16) {
SmallVector<uint16_t, 32> Elements;
Elements.reserve(NumElements);
for(unsigned i = 0, e = E->getLength(); i != e; ++i)
Elements.push_back(E->getCodeUnit(i));
Elements.resize(NumElements);
return llvm::ConstantDataArray::get(VMContext, Elements);
}
assert(ElemTy->getPrimitiveSizeInBits() == 32);
SmallVector<uint32_t, 32> Elements;
Elements.reserve(NumElements);
for(unsigned i = 0, e = E->getLength(); i != e; ++i)
Elements.push_back(E->getCodeUnit(i));
Elements.resize(NumElements);
return llvm::ConstantDataArray::get(VMContext, Elements);
}
static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
CodeGenModule &CGM, StringRef GlobalName,
CharUnits Alignment) {
unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
CGM.getStringLiteralAddressSpace());
llvm::Module &M = CGM.getModule();
// Create a global variable for this string
auto *GV = new llvm::GlobalVariable(
M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
GV->setAlignment(Alignment.getQuantity());
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
if (GV->isWeakForLinker()) {
assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
GV->setComdat(M.getOrInsertComdat(GV->getName()));
}
CGM.setDSOLocal(GV);
return GV;
}
/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
/// constant array for the given string literal.
ConstantAddress
CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
StringRef Name) {
CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
llvm::GlobalVariable **Entry = nullptr;
if (!LangOpts.WritableStrings) {
Entry = &ConstantStringMap[C];
if (auto GV = *Entry) {
if (Alignment.getQuantity() > GV->getAlignment())
GV->setAlignment(Alignment.getQuantity());
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
Alignment);
}
}
SmallString<256> MangledNameBuffer;
StringRef GlobalVariableName;
llvm::GlobalValue::LinkageTypes LT;
// Mangle the string literal if that's how the ABI merges duplicate strings.
// Don't do it if they are writable, since we don't want writes in one TU to
// affect strings in another.
if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
!LangOpts.WritableStrings) {
llvm::raw_svector_ostream Out(MangledNameBuffer);
getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
LT = llvm::GlobalValue::LinkOnceODRLinkage;
GlobalVariableName = MangledNameBuffer;
} else {
LT = llvm::GlobalValue::PrivateLinkage;
GlobalVariableName = Name;
}
auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
if (Entry)
*Entry = GV;
SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
QualType());
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
Alignment);
}
/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
/// array for the given ObjCEncodeExpr node.
ConstantAddress
CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
std::string Str;
getContext().getObjCEncodingForType(E->getEncodedType(), Str);
return GetAddrOfConstantCString(Str);
}
/// GetAddrOfConstantCString - Returns a pointer to a character array containing
/// the literal and a terminating '\0' character.
/// The result has pointer to array type.
ConstantAddress CodeGenModule::GetAddrOfConstantCString(
const std::string &Str, const char *GlobalName) {
StringRef StrWithNull(Str.c_str(), Str.size() + 1);
CharUnits Alignment =
getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
llvm::Constant *C =
llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
// Don't share any string literals if strings aren't constant.
llvm::GlobalVariable **Entry = nullptr;
if (!LangOpts.WritableStrings) {
Entry = &ConstantStringMap[C];
if (auto GV = *Entry) {
if (Alignment.getQuantity() > GV->getAlignment())
GV->setAlignment(Alignment.getQuantity());
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
Alignment);
}
}
// Get the default prefix if a name wasn't specified.
if (!GlobalName)
GlobalName = ".str";
// Create a global variable for this.
auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
GlobalName, Alignment);
if (Entry)
*Entry = GV;
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
Alignment);
}
ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
const MaterializeTemporaryExpr *E, const Expr *Init) {
assert((E->getStorageDuration() == SD_Static ||
E->getStorageDuration() == SD_Thread) && "not a global temporary");
const auto *VD = cast<VarDecl>(E->getExtendingDecl());
// If we're not materializing a subobject of the temporary, keep the
// cv-qualifiers from the type of the MaterializeTemporaryExpr.
QualType MaterializedType = Init->getType();
if (Init == E->GetTemporaryExpr())
MaterializedType = E->getType();
CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
return ConstantAddress(Slot, Align);
// FIXME: If an externally-visible declaration extends multiple temporaries,
// we need to give each temporary the same name in every translation unit (and
// we also need to make the temporaries externally-visible).
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
getCXXABI().getMangleContext().mangleReferenceTemporary(
VD, E->getManglingNumber(), Out);
APValue *Value = nullptr;
if (E->getStorageDuration() == SD_Static) {
// We might have a cached constant initializer for this temporary. Note
// that this might have a different value from the value computed by
// evaluating the initializer if the surrounding constant expression
// modifies the temporary.
Value = getContext().getMaterializedTemporaryValue(E, false);
if (Value && Value->isAbsent())
Value = nullptr;
}
// Try evaluating it now, it might have a constant initializer.
Expr::EvalResult EvalResult;
if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
!EvalResult.hasSideEffects())
Value = &EvalResult.Val;
LangAS AddrSpace =
VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
Optional<ConstantEmitter> emitter;
llvm::Constant *InitialValue = nullptr;
bool Constant = false;
llvm::Type *Type;
if (Value) {
// The temporary has a constant initializer, use it.
emitter.emplace(*this);
InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
MaterializedType);
Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
Type = InitialValue->getType();
} else {
// No initializer, the initialization will be provided when we
// initialize the declaration which performed lifetime extension.
Type = getTypes().ConvertTypeForMem(MaterializedType);
}
// Create a global variable for this lifetime-extended temporary.
llvm::GlobalValue::LinkageTypes Linkage =
getLLVMLinkageVarDefinition(VD, Constant);
if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
const VarDecl *InitVD;
if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
// Temporaries defined inside a class get linkonce_odr linkage because the
// class can be defined in multiple translation units.
Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
} else {
// There is no need for this temporary to have external linkage if the
// VarDecl has external linkage.
Linkage = llvm::GlobalVariable::InternalLinkage;
}
}
auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
auto *GV = new llvm::GlobalVariable(
getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
/*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
if (emitter) emitter->finalize(GV);
setGVProperties(GV, VD);
GV->setAlignment(Align.getQuantity());
if (supportsCOMDAT() && GV->isWeakForLinker())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
if (VD->getTLSKind())
setTLSMode(GV, *VD);
llvm::Constant *CV = GV;
if (AddrSpace != LangAS::Default)
CV = getTargetCodeGenInfo().performAddrSpaceCast(
*this, GV, AddrSpace, LangAS::Default,
Type->getPointerTo(
getContext().getTargetAddressSpace(LangAS::Default)));
MaterializedGlobalTemporaryMap[E] = CV;
return ConstantAddress(CV, Align);
}
/// EmitObjCPropertyImplementations - Emit information for synthesized
/// properties for an implementation.
void CodeGenModule::EmitObjCPropertyImplementations(const
ObjCImplementationDecl *D) {
for (const auto *PID : D->property_impls()) {
// Dynamic is just for type-checking.
if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
ObjCPropertyDecl *PD = PID->getPropertyDecl();
// Determine which methods need to be implemented, some may have
// been overridden. Note that ::isPropertyAccessor is not the method
// we want, that just indicates if the decl came from a
// property. What we want to know is if the method is defined in
// this implementation.
if (!D->getInstanceMethod(PD->getGetterName()))
CodeGenFunction(*this).GenerateObjCGetter(
const_cast<ObjCImplementationDecl *>(D), PID);
if (!PD->isReadOnly() &&
!D->getInstanceMethod(PD->getSetterName()))
CodeGenFunction(*this).GenerateObjCSetter(
const_cast<ObjCImplementationDecl *>(D), PID);
}
}
}
static bool needsDestructMethod(ObjCImplementationDecl *impl) {
const ObjCInterfaceDecl *iface = impl->getClassInterface();
for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
ivar; ivar = ivar->getNextIvar())
if (ivar->getType().isDestructedType())
return true;
return false;
}
static bool AllTrivialInitializers(CodeGenModule &CGM,
ObjCImplementationDecl *D) {
CodeGenFunction CGF(CGM);
for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
E = D->init_end(); B != E; ++B) {
CXXCtorInitializer *CtorInitExp = *B;
Expr *Init = CtorInitExp->getInit();
if (!CGF.isTrivialInitializer(Init))
return false;
}
return true;
}
/// EmitObjCIvarInitializations - Emit information for ivar initialization
/// for an implementation.
void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
// We might need a .cxx_destruct even if we don't have any ivar initializers.
if (needsDestructMethod(D)) {
IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
ObjCMethodDecl *DTORMethod =
ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
cxxSelector, getContext().VoidTy, nullptr, D,
/*isInstance=*/true, /*isVariadic=*/false,
/*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
/*isDefined=*/false, ObjCMethodDecl::Required);
D->addInstanceMethod(DTORMethod);
CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
D->setHasDestructors(true);
}
// If the implementation doesn't have any ivar initializers, we don't need
// a .cxx_construct.
if (D->getNumIvarInitializers() == 0 ||
AllTrivialInitializers(*this, D))
return;
IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
// The constructor returns 'self'.
ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
D->getLocation(),
D->getLocation(),
cxxSelector,
getContext().getObjCIdType(),
nullptr, D, /*isInstance=*/true,
/*isVariadic=*/false,
/*isPropertyAccessor=*/true,
/*isImplicitlyDeclared=*/true,
/*isDefined=*/false,
ObjCMethodDecl::Required);
D->addInstanceMethod(CTORMethod);
CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
D->setHasNonZeroConstructors(true);
}
// EmitLinkageSpec - Emit all declarations in a linkage spec.
void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
ErrorUnsupported(LSD, "linkage spec");
return;
}
EmitDeclContext(LSD);
}
void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
for (auto *I : DC->decls()) {
// Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
// are themselves considered "top-level", so EmitTopLevelDecl on an
// ObjCImplDecl does not recursively visit them. We need to do that in
// case they're nested inside another construct (LinkageSpecDecl /
// ExportDecl) that does stop them from being considered "top-level".
if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
for (auto *M : OID->methods())
EmitTopLevelDecl(M);
}
EmitTopLevelDecl(I);
}
}
/// EmitTopLevelDecl - Emit code for a single top level declaration.
void CodeGenModule::EmitTopLevelDecl(Decl *D) {
// Ignore dependent declarations.
if (D->isTemplated())
return;
switch (D->getKind()) {
case Decl::CXXConversion:
case Decl::CXXMethod:
case Decl::Function:
EmitGlobal(cast<FunctionDecl>(D));
// Always provide some coverage mapping
// even for the functions that aren't emitted.
AddDeferredUnusedCoverageMapping(D);
break;
case Decl::CXXDeductionGuide:
// Function-like, but does not result in code emission.
break;
case Decl::Var:
case Decl::Decomposition:
case Decl::VarTemplateSpecialization:
EmitGlobal(cast<VarDecl>(D));
if (auto *DD = dyn_cast<DecompositionDecl>(D))
for (auto *B : DD->bindings())
if (auto *HD = B->getHoldingVar())
EmitGlobal(HD);
break;
// Indirect fields from global anonymous structs and unions can be
// ignored; only the actual variable requires IR gen support.
case Decl::IndirectField:
break;
// C++ Decls
case Decl::Namespace:
EmitDeclContext(cast<NamespaceDecl>(D));
break;
case Decl::ClassTemplateSpecialization: {
const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
if (DebugInfo &&
Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
Spec->hasDefinition())
DebugInfo->completeTemplateDefinition(*Spec);
} LLVM_FALLTHROUGH;
case Decl::CXXRecord:
if (DebugInfo) {
if (auto *ES = D->getASTContext().getExternalSource())
if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
}
// Emit any static data members, they may be definitions.
for (auto *I : cast<CXXRecordDecl>(D)->decls())
if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
EmitTopLevelDecl(I);
break;
// No code generation needed.
case Decl::UsingShadow:
case Decl::ClassTemplate:
case Decl::VarTemplate:
case Decl::Concept:
case Decl::VarTemplatePartialSpecialization:
case Decl::FunctionTemplate:
case Decl::TypeAliasTemplate:
case Decl::Block:
case Decl::Empty:
case Decl::Binding:
break;
case Decl::Using: // using X; [C++]
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitUsingDecl(cast<UsingDecl>(*D));
return;
case Decl::NamespaceAlias:
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
return;
case Decl::UsingDirective: // using namespace X; [C++]
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
return;
case Decl::CXXConstructor:
getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
break;
case Decl::CXXDestructor:
getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
break;
case Decl::StaticAssert:
// Nothing to do.
break;
// Objective-C Decls
// Forward declarations, no (immediate) code generation.
case Decl::ObjCInterface:
case Decl::ObjCCategory:
break;
case Decl::ObjCProtocol: {
auto *Proto = cast<ObjCProtocolDecl>(D);
if (Proto->isThisDeclarationADefinition())
ObjCRuntime->GenerateProtocol(Proto);
break;
}
case Decl::ObjCCategoryImpl:
// Categories have properties but don't support synthesize so we
// can ignore them here.
ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
break;
case Decl::ObjCImplementation: {
auto *OMD = cast<ObjCImplementationDecl>(D);
EmitObjCPropertyImplementations(OMD);
EmitObjCIvarInitializations(OMD);
ObjCRuntime->GenerateClass(OMD);
// Emit global variable debug information.
if (CGDebugInfo *DI = getModuleDebugInfo())
if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
OMD->getClassInterface()), OMD->getLocation());
break;
}
case Decl::ObjCMethod: {
auto *OMD = cast<ObjCMethodDecl>(D);
// If this is not a prototype, emit the body.
if (OMD->getBody())
CodeGenFunction(*this).GenerateObjCMethod(OMD);
break;
}
case Decl::ObjCCompatibleAlias:
ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
break;
case Decl::PragmaComment: {
const auto *PCD = cast<PragmaCommentDecl>(D);
switch (PCD->getCommentKind()) {
case PCK_Unknown:
llvm_unreachable("unexpected pragma comment kind");
case PCK_Linker:
AppendLinkerOptions(PCD->getArg());
break;
case PCK_Lib:
AddDependentLib(PCD->getArg());
break;
case PCK_Compiler:
case PCK_ExeStr:
case PCK_User:
break; // We ignore all of these.
}
break;
}
case Decl::PragmaDetectMismatch: {
const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
AddDetectMismatch(PDMD->getName(), PDMD->getValue());
break;
}
case Decl::LinkageSpec:
EmitLinkageSpec(cast<LinkageSpecDecl>(D));
break;
case Decl::FileScopeAsm: {
// File-scope asm is ignored during device-side CUDA compilation.
if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
break;
// File-scope asm is ignored during device-side OpenMP compilation.
if (LangOpts.OpenMPIsDevice)
break;
auto *AD = cast<FileScopeAsmDecl>(D);
getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
break;
}
case Decl::Import: {
auto *Import = cast<ImportDecl>(D);
// If we've already imported this module, we're done.
if (!ImportedModules.insert(Import->getImportedModule()))
break;
// Emit debug information for direct imports.
if (!Import->getImportedOwningModule()) {
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitImportDecl(*Import);
}
// Find all of the submodules and emit the module initializers.
llvm::SmallPtrSet<clang::Module *, 16> Visited;
SmallVector<clang::Module *, 16> Stack;
Visited.insert(Import->getImportedModule());
Stack.push_back(Import->getImportedModule());
while (!Stack.empty()) {
clang::Module *Mod = Stack.pop_back_val();
if (!EmittedModuleInitializers.insert(Mod).second)
continue;
for (auto *D : Context.getModuleInitializers(Mod))
EmitTopLevelDecl(D);
// Visit the submodules of this module.
for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
SubEnd = Mod->submodule_end();
Sub != SubEnd; ++Sub) {
// Skip explicit children; they need to be explicitly imported to emit
// the initializers.
if ((*Sub)->IsExplicit)
continue;
if (Visited.insert(*Sub).second)
Stack.push_back(*Sub);
}
}
break;
}
case Decl::Export:
EmitDeclContext(cast<ExportDecl>(D));
break;
case Decl::OMPThreadPrivate:
EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
break;
case Decl::OMPAllocate:
break;
case Decl::OMPDeclareReduction:
EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
break;
case Decl::OMPDeclareMapper:
EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
break;
case Decl::OMPRequires:
EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
break;
default:
// Make sure we handled everything we should, every other kind is a
// non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
// function. Need to recode Decl::Kind to do that easily.
assert(isa<TypeDecl>(D) && "Unsupported decl kind");
break;
}
}
void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
// Do we need to generate coverage mapping?
if (!CodeGenOpts.CoverageMapping)
return;
switch (D->getKind()) {
case Decl::CXXConversion:
case Decl::CXXMethod:
case Decl::Function:
case Decl::ObjCMethod:
case Decl::CXXConstructor:
case Decl::CXXDestructor: {
if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
return;
SourceManager &SM = getContext().getSourceManager();
if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
return;
auto I = DeferredEmptyCoverageMappingDecls.find(D);
if (I == DeferredEmptyCoverageMappingDecls.end())
DeferredEmptyCoverageMappingDecls[D] = true;
break;
}
default:
break;
};
}
void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
// Do we need to generate coverage mapping?
if (!CodeGenOpts.CoverageMapping)
return;
if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
if (Fn->isTemplateInstantiation())
ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
}
auto I = DeferredEmptyCoverageMappingDecls.find(D);
if (I == DeferredEmptyCoverageMappingDecls.end())
DeferredEmptyCoverageMappingDecls[D] = false;
else
I->second = false;
}
void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
// We call takeVector() here to avoid use-after-free.
// FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
// we deserialize function bodies to emit coverage info for them, and that
// deserializes more declarations. How should we handle that case?
for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
if (!Entry.second)
continue;
const Decl *D = Entry.first;
switch (D->getKind()) {
case Decl::CXXConversion:
case Decl::CXXMethod:
case Decl::Function:
case Decl::ObjCMethod: {
CodeGenPGO PGO(*this);
GlobalDecl GD(cast<FunctionDecl>(D));
PGO.emitEmptyCounterMapping(D, getMangledName(GD),
getFunctionLinkage(GD));
break;
}
case Decl::CXXConstructor: {
CodeGenPGO PGO(*this);
GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
PGO.emitEmptyCounterMapping(D, getMangledName(GD),
getFunctionLinkage(GD));
break;
}
case Decl::CXXDestructor: {
CodeGenPGO PGO(*this);
GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
PGO.emitEmptyCounterMapping(D, getMangledName(GD),
getFunctionLinkage(GD));
break;
}
default:
break;
};
}
}
/// Turns the given pointer into a constant.
static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
const void *Ptr) {
uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
return llvm::ConstantInt::get(i64, PtrInt);
}
static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
llvm::NamedMDNode *&GlobalMetadata,
GlobalDecl D,
llvm::GlobalValue *Addr) {
if (!GlobalMetadata)
GlobalMetadata =
CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
// TODO: should we report variant information for ctors/dtors?
llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
llvm::ConstantAsMetadata::get(GetPointerConstant(
CGM.getLLVMContext(), D.getDecl()))};
GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
}
/// For each function which is declared within an extern "C" region and marked
/// as 'used', but has internal linkage, create an alias from the unmangled
/// name to the mangled name if possible. People expect to be able to refer
/// to such functions with an unmangled name from inline assembly within the
/// same translation unit.
void CodeGenModule::EmitStaticExternCAliases() {
if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
return;
for (auto &I : StaticExternCValues) {
IdentifierInfo *Name = I.first;
llvm::GlobalValue *Val = I.second;
if (Val && !getModule().getNamedValue(Name->getName()))
addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
}
}
bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
GlobalDecl &Result) const {
auto Res = Manglings.find(MangledName);
if (Res == Manglings.end())
return false;
Result = Res->getValue();
return true;
}
/// Emits metadata nodes associating all the global values in the
/// current module with the Decls they came from. This is useful for
/// projects using IR gen as a subroutine.
///
/// Since there's currently no way to associate an MDNode directly
/// with an llvm::GlobalValue, we create a global named metadata
/// with the name 'clang.global.decl.ptrs'.
void CodeGenModule::EmitDeclMetadata() {
llvm::NamedMDNode *GlobalMetadata = nullptr;
for (auto &I : MangledDeclNames) {
llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
// Some mangled names don't necessarily have an associated GlobalValue
// in this module, e.g. if we mangled it for DebugInfo.
if (Addr)
EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
}
}
/// Emits metadata nodes for all the local variables in the current
/// function.
void CodeGenFunction::EmitDeclMetadata() {
if (LocalDeclMap.empty()) return;
llvm::LLVMContext &Context = getLLVMContext();
// Find the unique metadata ID for this name.
unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
llvm::NamedMDNode *GlobalMetadata = nullptr;
for (auto &I : LocalDeclMap) {
const Decl *D = I.first;
llvm::Value *Addr = I.second.getPointer();
if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Alloca->setMetadata(
DeclPtrKind, llvm::MDNode::get(
Context, llvm::ValueAsMetadata::getConstant(DAddr)));
} else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
}
}
}
void CodeGenModule::EmitVersionIdentMetadata() {
llvm::NamedMDNode *IdentMetadata =
TheModule.getOrInsertNamedMetadata("llvm.ident");
std::string Version = getClangFullVersion();
llvm::LLVMContext &Ctx = TheModule.getContext();
llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
}
void CodeGenModule::EmitCommandLineMetadata() {
llvm::NamedMDNode *CommandLineMetadata =
TheModule.getOrInsertNamedMetadata("llvm.commandline");
std::string CommandLine = getCodeGenOpts().RecordCommandLine;
llvm::LLVMContext &Ctx = TheModule.getContext();
llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
}
void CodeGenModule::EmitTargetMetadata() {
// Warning, new MangledDeclNames may be appended within this loop.
// We rely on MapVector insertions adding new elements to the end
// of the container.
// FIXME: Move this loop into the one target that needs it, and only
// loop over those declarations for which we couldn't emit the target
// metadata when we emitted the declaration.
for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
auto Val = *(MangledDeclNames.begin() + I);
const Decl *D = Val.first.getDecl()->getMostRecentDecl();
llvm::GlobalValue *GV = GetGlobalValue(Val.second);
getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
}
}
void CodeGenModule::EmitCoverageFile() {
if (getCodeGenOpts().CoverageDataFile.empty() &&
getCodeGenOpts().CoverageNotesFile.empty())
return;
llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
if (!CUNode)
return;
llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
llvm::LLVMContext &Ctx = TheModule.getContext();
auto *CoverageDataFile =
llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
auto *CoverageNotesFile =
llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
llvm::MDNode *CU = CUNode->getOperand(i);
llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
}
}
llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
// Sema has checked that all uuid strings are of the form
// "12345678-1234-1234-1234-1234567890ab".
assert(Uuid.size() == 36);
for (unsigned i = 0; i < 36; ++i) {
if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
else assert(isHexDigit(Uuid[i]));
}
// The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
llvm::Constant *Field3[8];
for (unsigned Idx = 0; Idx < 8; ++Idx)
Field3[Idx] = llvm::ConstantInt::get(
Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
llvm::Constant *Fields[4] = {
llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
};
return llvm::ConstantStruct::getAnon(Fields);
}
llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
bool ForEH) {
// Return a bogus pointer if RTTI is disabled, unless it's for EH.
// FIXME: should we even be calling this method if RTTI is disabled
// and it's not for EH?
if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
return llvm::Constant::getNullValue(Int8PtrTy);
if (ForEH && Ty->isObjCObjectPointerType() &&
LangOpts.ObjCRuntime.isGNUFamily())
return ObjCRuntime->GetEHType(Ty);
return getCXXABI().getAddrOfRTTIDescriptor(Ty);
}
void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
// Do not emit threadprivates in simd-only mode.
if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
return;
for (auto RefExpr : D->varlists()) {
auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
bool PerformInit =
VD->getAnyInitializer() &&
!VD->getAnyInitializer()->isConstantInitializer(getContext(),
/*ForRef=*/false);
Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
VD, Addr, RefExpr->getBeginLoc(), PerformInit))
CXXGlobalInits.push_back(InitFunction);
}
}
llvm::Metadata *
CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
StringRef Suffix) {
llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
if (InternalId)
return InternalId;
if (isExternallyVisible(T->getLinkage())) {
std::string OutName;
llvm::raw_string_ostream Out(OutName);
getCXXABI().getMangleContext().mangleTypeName(T, Out);
Out << Suffix;
InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
} else {
InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
llvm::ArrayRef<llvm::Metadata *>());
}
return InternalId;
}
llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
}
llvm::Metadata *
CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
}
// Generalize pointer types to a void pointer with the qualifiers of the
// originally pointed-to type, e.g. 'const char *' and 'char * const *'
// generalize to 'const void *' while 'char *' and 'const char **' generalize to
// 'void *'.
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
if (!Ty->isPointerType())
return Ty;
return Ctx.getPointerType(
QualType(Ctx.VoidTy).withCVRQualifiers(
Ty->getPointeeType().getCVRQualifiers()));
}
// Apply type generalization to a FunctionType's return and argument types
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
SmallVector<QualType, 8> GeneralizedParams;
for (auto &Param : FnType->param_types())
GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
return Ctx.getFunctionType(
GeneralizeType(Ctx, FnType->getReturnType()),
GeneralizedParams, FnType->getExtProtoInfo());
}
if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
return Ctx.getFunctionNoProtoType(
GeneralizeType(Ctx, FnType->getReturnType()));
llvm_unreachable("Encountered unknown FunctionType");
}
llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
GeneralizedMetadataIdMap, ".generalized");
}
/// Returns whether this module needs the "all-vtables" type identifier.
bool CodeGenModule::NeedAllVtablesTypeId() const {
// Returns true if at least one of vtable-based CFI checkers is enabled and
// is not in the trapping mode.
return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
(LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
(LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
(LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
}
void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
CharUnits Offset,
const CXXRecordDecl *RD) {
llvm::Metadata *MD =
CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
VTable->addTypeMetadata(Offset.getQuantity(), MD);
if (CodeGenOpts.SanitizeCfiCrossDso)
if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
VTable->addTypeMetadata(Offset.getQuantity(),
llvm::ConstantAsMetadata::get(CrossDsoTypeId));
if (NeedAllVtablesTypeId()) {
llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
VTable->addTypeMetadata(Offset.getQuantity(), MD);
}
}
TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
assert(TD != nullptr);
TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
ParsedAttr.Features.erase(
llvm::remove_if(ParsedAttr.Features,
[&](const std::string &Feat) {
return !Target.isValidFeatureName(
StringRef{Feat}.substr(1));
}),
ParsedAttr.Features.end());
return ParsedAttr;
}
// Fills in the supplied string map with the set of target features for the
// passed in function.
void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
GlobalDecl GD) {
StringRef TargetCPU = Target.getTargetOpts().CPU;
const FunctionDecl *FD = GD.getDecl()->getAsFunction();
if (const auto *TD = FD->getAttr<TargetAttr>()) {
TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
// Make a copy of the features as passed on the command line into the
// beginning of the additional features from the function to override.
ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Target.getTargetOpts().FeaturesAsWritten.begin(),
Target.getTargetOpts().FeaturesAsWritten.end());
if (ParsedAttr.Architecture != "" &&
Target.isValidCPUName(ParsedAttr.Architecture))
TargetCPU = ParsedAttr.Architecture;
// Now populate the feature map, first with the TargetCPU which is either
// the default or a new one from the target attribute string. Then we'll use
// the passed in features (FeaturesAsWritten) along with the new ones from
// the attribute.
Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
ParsedAttr.Features);
} else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
llvm::SmallVector<StringRef, 32> FeaturesTmp;
Target.getCPUSpecificCPUDispatchFeatures(
SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
} else {
Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
Target.getTargetOpts().Features);
}
}
llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
if (!SanStats)
SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
return *SanStats;
}
llvm::Value *
CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
CodeGenFunction &CGF) {
llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
"__translate_sampler_initializer"),
{C});
}
| [
"stefan.teleman@cavium.com"
] | stefan.teleman@cavium.com |
5949251edaf56c2e7ba8ff2a31bec46305e8b9ac | 6501845f28181a8bd11ee73a55b0589e60264481 | /lock_guard.cpp | c0f3669bdb1b13f68069e8965774228b6ef6641a | [
"MIT"
] | permissive | xkilluax/mevent | 3da8c5b11067630360736b42a4076ddcef6d4ce4 | fa268e93b33264c71d086ba9387b5ab2fabd0257 | refs/heads/master | 2021-12-15T00:57:44.839656 | 2021-11-16T02:50:04 | 2021-11-16T02:50:04 | 81,443,331 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 349 | cpp | #include "lock_guard.h"
#include "util.h"
namespace mevent {
LockGuard::LockGuard(pthread_mutex_t &mutex) : mtx(mutex) {
if (pthread_mutex_lock(&mtx) != 0) {
MEVENT_LOG_DEBUG_EXIT(NULL);
}
}
LockGuard::~LockGuard() {
if (pthread_mutex_unlock(&mtx) != 0) {
MEVENT_LOG_DEBUG_EXIT(NULL);
}
}
}//namespace mevent
| [
"looyao@thinksky.hk"
] | looyao@thinksky.hk |
b969bc266726290783ea6f3f4b0b58512653a4a5 | df6a7072020c0cce62a2362761f01c08f1375be7 | /doc/quickbook/oalplus/quickref/enums/context_attrib_class.hpp | 6cd098d34bc1396508cf7f85dcd2786f03ea5e7b | [
"BSL-1.0"
] | permissive | matus-chochlik/oglplus | aa03676bfd74c9877d16256dc2dcabcc034bffb0 | 76dd964e590967ff13ddff8945e9dcf355e0c952 | refs/heads/develop | 2023-03-07T07:08:31.615190 | 2021-10-26T06:11:43 | 2021-10-26T06:11:43 | 8,885,160 | 368 | 58 | BSL-1.0 | 2018-09-21T16:57:52 | 2013-03-19T17:52:30 | C++ | UTF-8 | C++ | false | false | 1,099 | hpp | // File doc/quickbook/oalplus/quickref/enums/context_attrib_class.hpp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oalplus/context_attrib.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 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
//
//[oalplus_enums_context_attrib_class
#if !__OGLPLUS_NO_ENUM_VALUE_CLASSES
namespace enums {
template <typename Base, template<__ContextAttrib> class Transform>
class __EnumToClass<Base, __ContextAttrib, Transform> /*<
Specialization of __EnumToClass for the __ContextAttrib enumeration.
>*/
: public Base
{
public:
EnumToClass();
EnumToClass(Base&& base);
Transform<ContextAttrib::Frequency>
Frequency;
Transform<ContextAttrib::Refresh>
Refresh;
Transform<ContextAttrib::Sync>
Sync;
Transform<ContextAttrib::MonoSources>
MonoSources;
Transform<ContextAttrib::StereoSources>
StereoSources;
};
} // namespace enums
#endif
//]
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
efbcf47c9063c5cafa0b32b5b040b0f67ae05ba5 | bd433a1d9a408bb876a252747068151202673b8a | /exam2/answer/Q94/CPU.cpp | 5f67293ec8a4ad59603e337fb66a3b3181cb8958 | [] | no_license | DemoTree/cpp | d8f80f6a879a935d44d2b04657dac3ce7b9a5f3c | cfe0c23d99f3a6e70106e48473a18b436e488ef3 | refs/heads/master | 2020-09-22T06:56:57.588496 | 2020-02-18T07:56:09 | 2020-02-18T07:56:09 | 225,093,504 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,789 | cpp | #include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
class Task {
protected:
int name;
int type;
int priority;
int arrive_time;
int task_take;
int coreId = 0;
int current_time;
public:
Task(int name, int type, int priority, int arrive_time, int task_take) {
this->name = name;
this->type = type;
this->priority = priority;
this->arrive_time = arrive_time;
this->task_take = task_take;
}
int get_name() {
return name;
}
int get_priority() {
return priority;
}
int get_arrive_time() {
return arrive_time;
}
int get_task_take() {
return task_take;
}
string get_type() {
string label = "";
if (type == 0) {
label = "LoadDatabase";
}
else if (type == 1) {
label = "ETL";
}
else if (type == 2) {
label = "DataAnalyze";
}
return label;
}
void set_coreId(int coreId) {
this->coreId = coreId;
}
int get_coreId() {
return coreId;
}
void set_current_time(int time) {
this->current_time = time;
}
int get_current_time() {
return current_time;
}
void printLoad() {
cout << "task " << name << " load: time " << 0 << " coreId " << coreId << " name task"
<< name << " type "<< get_type() << " priority " << priority << endl;
cout << "task " << name << " execute: time " << 0 << " coreId " << coreId << endl;
}
void printFinish() {
cout << "task " << name << " finish: time " << task_take << " coreId " << coreId << endl;
}
virtual void printExecute() = 0;
};
class LoadDatabase :public Task {
public:
LoadDatabase(int name, int type, int priority, int arrive_time, int task_take) :Task(name, type, priority, arrive_time, task_take) {
this->name = name;
this->type = type;
this->priority = priority;
this->arrive_time = arrive_time;
this->task_take = task_take;
}
void printExecute() override{
cout << "task " << name << " --- Load driver" << endl;
cout << "task " << name << " --- Establish a database connection" << endl;
cout << "task " << name << " --- Create a Statement object" << endl;
cout << "task " << name << " --- Execute SQL" << endl;
cout << "task " << name << " --- Close the database" << endl;
}
};
class ETL :public Task {
public:
ETL(int name, int type, int priority, int arrive_time, int task_take) :Task(name, type, priority, arrive_time, task_take) {
this->name = name;
this->type = type;
this->priority = priority;
this->arrive_time = arrive_time;
this->task_take = task_take;
}
void printExecute() override {
cout << "task " << name << " --- Read data from a file" << endl;
cout << "task " << name << " --- Data transform" << endl;
cout << "task " << name << " --- Load data into the database" << endl;
}
};
class DataAnalyze :public Task {
public:
DataAnalyze(int name, int type, int priority, int arrive_time, int task_take) :Task(name, type, priority, arrive_time, task_take) {
this->name = name;
this->type = type;
this->priority = priority;
this->arrive_time = arrive_time;
this->task_take = task_take;
}
void printExecute() override {
cout << "task " << name << " --- Finding the center point" << endl;
cout << "task " << name << " --- Data Classification" << endl;
cout << "task " << name << " --- Data comparison" << endl;
cout << "task " << name << " --- Data Display" << endl;
}
};
class Factory {
public:
static Task* createTask(int name, int type, int priority, int arrive_time, int task_take) {
switch (type) {
case 0:
return new LoadDatabase(name, type, priority, arrive_time, task_take);
case 1:
return new ETL(name, type, priority, arrive_time, task_take);
case 2:
return new DataAnalyze(name, type, priority, arrive_time, task_take);
}
return 0;
}
};
class CPU {
protected:
int num;
map<int, Task*> tasks;//存储所有任务
int** cpus = new int*[num];
int time = 0;
vector<Task*> loads;//加载顺序
public:
CPU(int numOfCPU) {
this->num = numOfCPU;
}
void setCPU() {
for (int i = 0; i < num; i++) {
cpus[i] = new int[2];
for (int j = 0; j < 2; j++) {
cpus[i][j] = 0;
}
}
}
void addTask(int name, int type, int priority, int arrive_time, int task_take) {
tasks[name] = Factory::createTask(name, type, priority, arrive_time, task_take);
}
//分配core
void setTask(Task* task) {
for (int i = 0; i < num; i++) {
if (cpus[i][0] == 0) {
task->set_coreId(i);
cpus[i][0] = 1;
cpus[i][1] = task->get_name();
}
}
}
//TODO 结束后释放CPU
void freeTask() {
}
//TODO 加载顺序队列
void loading() {
map<int, Task*>::iterator itr = tasks.begin();
loads.push_back(itr->second);
while (itr != tasks.end()) {
if(itr!=tasks.begin()){
for (auto itv = loads.begin(); itv != loads.end(); itv++) {
if (itr->second->get_arrive_time() > (*itv)->get_arrive_time()) {
//时间大的放在后面
loads.push_back(itr->second);
}
else if (itr->second->get_arrive_time() < (*itv)->get_arrive_time()) {
//时间小的放在前面
loads.insert(itv, itr->second);
}
else {
//时间相同的判断优先级
if (itr->second->get_priority() > (*itv)->get_priority()) {
//优先级数字小代表优先级大,放在前面
loads.insert(itv, itr->second);
}
else {
loads.push_back(itr->second);
}
}
}
}
itr++;
}
}
//TODO
void printPSA() {
//loading();
//for (auto itr = loads.begin(); itr != loads.end(); itr++) {
//cout << (*itr)->get_name() << " " << endl;
//}
map<int, Task*>::iterator itr = tasks.begin();
while (itr != tasks.end()) {
setTask(itr->second);
itr->second->printLoad();
itr->second->printExecute();
itr->second->printFinish();
itr++;
}
}
//TODO
void printHRRF() {
map<int, Task*>::iterator itr = tasks.begin();
while (itr != tasks.end()) {
setTask(itr->second);
itr->second->printLoad();
itr->second->printExecute();
itr->second->printFinish();
itr++;
}
}
};
int main() {
int numofCPU, numofTask;
char* way = new char[5];
cin >> numofCPU >> way >> numofTask;
CPU cpu(numofCPU);
cpu.setCPU();
for (int i = 0; i < numofTask; i++) {
int id, type, priority, arrive_time, task_take;
char* cname = new char[5];
cin >> id >> cname >> type >> priority >> arrive_time >> task_take;
string sname = cname;
sname.erase(0, 4);
int name = stoi(sname);
cpu.addTask(name, type, priority, arrive_time, task_take);
}
if (strcmp(way, "PSA") == 0) {
cpu.printPSA();
}
else{
cpu.printHRRF();
}
system("pause");
} | [
"zzy9967@126.com"
] | zzy9967@126.com |
24d35796497d06af7f66c04d3e9ebc216ea0d031 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5688567749672960_1/C++/Sameth/newa.cpp | fd143609d5a6bea3f79bc93ee91adfe6b534ba66 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | cpp | #include <cstdio>
#include <cassert>
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <cstring>
#include <cstdlib>
#include <cmath>
#define For(i, n) for (int i = 0; i < (int) n; ++i)
#define SIZE(x) ((int) (x).size())
#define mp(a, b) make_pair(a, b)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
#ifndef DG
#define DG 0
#endif
#define LOG(...) (DG ? fprintf(stderr, __VA_ARGS__) : 0)
ll digits(ll what) {
ll res = 0;
while (what > 0){
res ++;
what /= 10;
}
return res;
}
ll myexp(ll what) {
ll res = 1;
For(i, what) res *= 10;
return res;
}
ll reverse(ll what) {
ll res = 0;
while (what > 0) {
res *= 10;
res += what % 10;
what /= 10;
}
return res;
}
int main(){
int T;
scanf("%d", &T);
For(cases, T) {
ll n;
scanf("%lld", &n);
if (n < 10) {
printf("Case #%d: %lld\n", cases+1, n);
continue;
}
ll steps = 0, mydigits = 1;
while (mydigits < digits(n)) {
steps += myexp((mydigits+1) / 2) - 1;
steps += myexp(mydigits / 2);
mydigits ++;
}
ll ihave = myexp(mydigits - 1);
if (ihave == n) {
printf("Case #%d: %lld\n", cases+1, steps);
continue;
}
bool increment = false;
if (n % myexp((mydigits + 1) / 2) == 0) {
increment = true;
n --;
}
steps += reverse(n) % myexp(mydigits / 2);
if (reverse(n) % myexp(mydigits / 2) == 1) steps --;
steps += n % myexp((mydigits + 1) / 2);
if (increment) steps ++;
printf("Case #%d: %lld\n", cases+1, steps);
}
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
39df26bc79f43fa90026c3036b3500fd3b8b11c5 | a300c35fc8e99b67d1d2b02e23b77e49771a63bc | /Solved/Codeforces/560C - Gerald's Hexagon.cpp | 279a598af24d68e6b4c8df918043b45f87eae0b6 | [] | no_license | FabiOquendo/Competitive-Programming | c035b865eb79b89b587ad919e45cf00e0b35de83 | adbcde84bbd10fee10143101b56bb3dbb0b79b6b | refs/heads/master | 2021-01-18T22:55:56.307662 | 2017-06-01T16:21:17 | 2017-06-01T16:21:17 | 49,735,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cpp | //============================================================
// Name : 560C - Gerald's Hexagon.cpp
// Author : Team UQuick
// Author : Fabio Stiven Oquendo Soler
// Description : Programming Problems CODEFORCES
// Number : 560C
//============================================================
#include <bits/stdc++.h>
using namespace std;
int main() {
int a1, a2, a3, a4, a5, a6;
long int res;
while(scanf("%d %d %d %d %d %d", &a1, &a2, &a3, &a4, &a5, &a6) == 6) {
// Formula para calcular los triangulos equilateros de 1 unidad
// en un exagono de lados a1 a2 a3 a4 a5 y a6
res = (a1+a2+a3)*(a1+a2+a3);
res -= (a1*a1)+(a3*a3)+(a5*a5);
printf("%ld\n", res);
}
return 0;
}
| [
"fabioquendo95@gmail.com"
] | fabioquendo95@gmail.com |
2ff2281b174f857a77681928597791ea41d3aad9 | 0d314decc17cf7bb7918a9b5ac72ebe1e1abca1e | /src/test/univalue_tests.cpp | 7874010b68da6be8d82799f7dbfab2a9072dae92 | [
"MIT"
] | permissive | gus3008/protoncoin | 798375f90c6fd97de29ad75bf79def555fae1888 | 320fe64295c487a0af6a18ceb8da8012b822cd86 | refs/heads/master | 2020-03-21T19:30:19.506175 | 2018-07-10T23:52:02 | 2018-07-10T23:52:02 | 138,953,437 | 0 | 0 | MIT | 2018-06-28T01:58:07 | 2018-06-28T01:58:06 | null | UTF-8 | C++ | false | false | 9,503 | cpp | // Copyright 2014 BitPay, Inc.
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include <univalue.h>
#include "test/test_proton.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(univalue_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(univalue_constructor)
{
UniValue v1;
BOOST_CHECK(v1.isNull());
UniValue v2(UniValue::VSTR);
BOOST_CHECK(v2.isStr());
UniValue v3(UniValue::VSTR, "foo");
BOOST_CHECK(v3.isStr());
BOOST_CHECK_EQUAL(v3.getValStr(), "foo");
UniValue numTest;
BOOST_CHECK(numTest.setNumStr("82"));
BOOST_CHECK(numTest.isNum());
BOOST_CHECK_EQUAL(numTest.getValStr(), "82");
uint64_t vu64 = 82;
UniValue v4(vu64);
BOOST_CHECK(v4.isNum());
BOOST_CHECK_EQUAL(v4.getValStr(), "82");
int64_t vi64 = -82;
UniValue v5(vi64);
BOOST_CHECK(v5.isNum());
BOOST_CHECK_EQUAL(v5.getValStr(), "-82");
int vi = -688;
UniValue v6(vi);
BOOST_CHECK(v6.isNum());
BOOST_CHECK_EQUAL(v6.getValStr(), "-688");
double vd = -7.21;
UniValue v7(vd);
BOOST_CHECK(v7.isNum());
BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21");
string vs("yawn");
UniValue v8(vs);
BOOST_CHECK(v8.isStr());
BOOST_CHECK_EQUAL(v8.getValStr(), "yawn");
const char *vcs = "zappa";
UniValue v9(vcs);
BOOST_CHECK(v9.isStr());
BOOST_CHECK_EQUAL(v9.getValStr(), "zappa");
}
BOOST_AUTO_TEST_CASE(univalue_typecheck)
{
UniValue v1;
BOOST_CHECK(v1.setNumStr("1"));
BOOST_CHECK(v1.isNum());
BOOST_CHECK_THROW(v1.get_bool(), runtime_error);
UniValue v2;
BOOST_CHECK(v2.setBool(true));
BOOST_CHECK_EQUAL(v2.get_bool(), true);
BOOST_CHECK_THROW(v2.get_int(), runtime_error);
UniValue v3;
BOOST_CHECK(v3.setNumStr("32482348723847471234"));
BOOST_CHECK_THROW(v3.get_int64(), runtime_error);
BOOST_CHECK(v3.setNumStr("1000"));
BOOST_CHECK_EQUAL(v3.get_int64(), 1000);
UniValue v4;
BOOST_CHECK(v4.setNumStr("2147483648"));
BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648ULL);
BOOST_CHECK_THROW(v4.get_int(), runtime_error);
BOOST_CHECK(v4.setNumStr("1000"));
BOOST_CHECK_EQUAL(v4.get_int(), 1000);
BOOST_CHECK_THROW(v4.get_str(), runtime_error);
BOOST_CHECK_EQUAL(v4.get_real(), 1000);
BOOST_CHECK_THROW(v4.get_array(), runtime_error);
BOOST_CHECK_THROW(v4.getKeys(), runtime_error);
BOOST_CHECK_THROW(v4.getValues(), runtime_error);
BOOST_CHECK_THROW(v4.get_obj(), runtime_error);
UniValue v5;
BOOST_CHECK(v5.read("[true, 10]"));
BOOST_CHECK_NO_THROW(v5.get_array());
std::vector<UniValue> vals = v5.getValues();
BOOST_CHECK_THROW(vals[0].get_int(), runtime_error);
BOOST_CHECK_EQUAL(vals[0].get_bool(), true);
BOOST_CHECK_EQUAL(vals[1].get_int(), 10);
BOOST_CHECK_THROW(vals[1].get_bool(), runtime_error);
}
BOOST_AUTO_TEST_CASE(univalue_set)
{
UniValue v(UniValue::VSTR, "foo");
v.clear();
BOOST_CHECK(v.isNull());
BOOST_CHECK_EQUAL(v.getValStr(), "");
BOOST_CHECK(v.setObject());
BOOST_CHECK(v.isObject());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK_EQUAL(v.getType(), UniValue::VOBJ);
BOOST_CHECK(v.empty());
BOOST_CHECK(v.setArray());
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK(v.setStr("zum"));
BOOST_CHECK(v.isStr());
BOOST_CHECK_EQUAL(v.getValStr(), "zum");
BOOST_CHECK(v.setFloat(-1.01));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1.01");
BOOST_CHECK(v.setInt((int)1023));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setInt((int64_t)-1023LL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1023");
BOOST_CHECK(v.setInt((uint64_t)1023ULL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setNumStr("-688"));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-688");
BOOST_CHECK(v.setBool(false));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), false);
BOOST_CHECK_EQUAL(v.isFalse(), true);
BOOST_CHECK_EQUAL(v.getBool(), false);
BOOST_CHECK(v.setBool(true));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), true);
BOOST_CHECK_EQUAL(v.isFalse(), false);
BOOST_CHECK_EQUAL(v.getBool(), true);
BOOST_CHECK(!v.setNumStr("zombocom"));
BOOST_CHECK(v.setNull());
BOOST_CHECK(v.isNull());
}
BOOST_AUTO_TEST_CASE(univalue_array)
{
UniValue arr(UniValue::VARR);
UniValue v((int64_t)1023LL);
BOOST_CHECK(arr.push_back(v));
string vStr("zippy");
BOOST_CHECK(arr.push_back(vStr));
const char *s = "pippy";
BOOST_CHECK(arr.push_back(s));
vector<UniValue> vec;
v.setStr("boing");
vec.push_back(v);
v.setStr("going");
vec.push_back(v);
BOOST_CHECK(arr.push_backV(vec));
BOOST_CHECK_EQUAL(arr.empty(), false);
BOOST_CHECK_EQUAL(arr.size(), 5);
BOOST_CHECK_EQUAL(arr[0].getValStr(), "1023");
BOOST_CHECK_EQUAL(arr[1].getValStr(), "zippy");
BOOST_CHECK_EQUAL(arr[2].getValStr(), "pippy");
BOOST_CHECK_EQUAL(arr[3].getValStr(), "boing");
BOOST_CHECK_EQUAL(arr[4].getValStr(), "going");
BOOST_CHECK_EQUAL(arr[999].getValStr(), "");
arr.clear();
BOOST_CHECK(arr.empty());
BOOST_CHECK_EQUAL(arr.size(), 0);
}
BOOST_AUTO_TEST_CASE(univalue_object)
{
UniValue obj(UniValue::VOBJ);
string strKey, strVal;
UniValue v;
strKey = "age";
v.setInt(100);
BOOST_CHECK(obj.pushKV(strKey, v));
strKey = "first";
strVal = "John";
BOOST_CHECK(obj.pushKV(strKey, strVal));
strKey = "last";
const char *cVal = "Smith";
BOOST_CHECK(obj.pushKV(strKey, cVal));
strKey = "distance";
BOOST_CHECK(obj.pushKV(strKey, (int64_t) 25));
strKey = "time";
BOOST_CHECK(obj.pushKV(strKey, (uint64_t) 3600));
strKey = "calories";
BOOST_CHECK(obj.pushKV(strKey, (int) 12));
strKey = "temperature";
BOOST_CHECK(obj.pushKV(strKey, (double) 90.012));
UniValue obj2(UniValue::VOBJ);
BOOST_CHECK(obj2.pushKV("cat1", 9000));
BOOST_CHECK(obj2.pushKV("cat2", 12345));
BOOST_CHECK(obj.pushKVs(obj2));
BOOST_CHECK_EQUAL(obj.empty(), false);
BOOST_CHECK_EQUAL(obj.size(), 9);
BOOST_CHECK_EQUAL(obj["age"].getValStr(), "100");
BOOST_CHECK_EQUAL(obj["first"].getValStr(), "John");
BOOST_CHECK_EQUAL(obj["last"].getValStr(), "Smith");
BOOST_CHECK_EQUAL(obj["distance"].getValStr(), "25");
BOOST_CHECK_EQUAL(obj["time"].getValStr(), "3600");
BOOST_CHECK_EQUAL(obj["calories"].getValStr(), "12");
BOOST_CHECK_EQUAL(obj["temperature"].getValStr(), "90.012");
BOOST_CHECK_EQUAL(obj["cat1"].getValStr(), "9000");
BOOST_CHECK_EQUAL(obj["cat2"].getValStr(), "12345");
BOOST_CHECK_EQUAL(obj["nyuknyuknyuk"].getValStr(), "");
BOOST_CHECK(obj.exists("age"));
BOOST_CHECK(obj.exists("first"));
BOOST_CHECK(obj.exists("last"));
BOOST_CHECK(obj.exists("distance"));
BOOST_CHECK(obj.exists("time"));
BOOST_CHECK(obj.exists("calories"));
BOOST_CHECK(obj.exists("temperature"));
BOOST_CHECK(obj.exists("cat1"));
BOOST_CHECK(obj.exists("cat2"));
BOOST_CHECK(!obj.exists("nyuknyuknyuk"));
map<string, UniValue::VType> objTypes;
objTypes["age"] = UniValue::VNUM;
objTypes["first"] = UniValue::VSTR;
objTypes["last"] = UniValue::VSTR;
objTypes["distance"] = UniValue::VNUM;
objTypes["time"] = UniValue::VNUM;
objTypes["calories"] = UniValue::VNUM;
objTypes["temperature"] = UniValue::VNUM;
objTypes["cat1"] = UniValue::VNUM;
objTypes["cat2"] = UniValue::VNUM;
BOOST_CHECK(obj.checkObject(objTypes));
objTypes["cat2"] = UniValue::VSTR;
BOOST_CHECK(!obj.checkObject(objTypes));
obj.clear();
BOOST_CHECK(obj.empty());
BOOST_CHECK_EQUAL(obj.size(), 0);
}
static const char *json1 =
"[1.10000000,{\"key1\":\"str\\u0000\",\"key2\":800,\"key3\":{\"name\":\"martian http://test.com\"}}]";
BOOST_AUTO_TEST_CASE(univalue_readwrite)
{
UniValue v;
BOOST_CHECK(v.read(json1));
string strJson1(json1);
BOOST_CHECK(v.read(strJson1));
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 2);
BOOST_CHECK_EQUAL(v[0].getValStr(), "1.10000000");
UniValue obj = v[1];
BOOST_CHECK(obj.isObject());
BOOST_CHECK_EQUAL(obj.size(), 3);
BOOST_CHECK(obj["key1"].isStr());
std::string correctValue("str");
correctValue.push_back('\0');
BOOST_CHECK_EQUAL(obj["key1"].getValStr(), correctValue);
BOOST_CHECK(obj["key2"].isNum());
BOOST_CHECK_EQUAL(obj["key2"].getValStr(), "800");
BOOST_CHECK(obj["key3"].isObject());
BOOST_CHECK_EQUAL(strJson1, v.write());
/* Check for (correctly reporting) a parsing error if the initial
JSON construct is followed by more stuff. Note that whitespace
is, of course, exempt. */
BOOST_CHECK(v.read(" {}\n "));
BOOST_CHECK(v.isObject());
BOOST_CHECK(v.read(" []\n "));
BOOST_CHECK(v.isArray());
BOOST_CHECK(!v.read("@{}"));
BOOST_CHECK(!v.read("{} garbage"));
BOOST_CHECK(!v.read("[]{}"));
BOOST_CHECK(!v.read("{}[]"));
BOOST_CHECK(!v.read("{} 42"));
}
BOOST_AUTO_TEST_SUITE_END()
| [
"newprotoncoin@gmail.com"
] | newprotoncoin@gmail.com |
eb5421c3f8f3d26c3fe83785c7bd2dee14d47ae8 | cc7661edca4d5fb2fc226bd6605a533f50a2fb63 | /System.Xml/SoapSchemaMember.h | c692fa4ac8553273c2f9a432a24a9523d9f44014 | [
"MIT"
] | permissive | g91/Rust-C-SDK | 698e5b573285d5793250099b59f5453c3c4599eb | d1cce1133191263cba5583c43a8d42d8d65c21b0 | refs/heads/master | 2020-03-27T05:49:01.747456 | 2017-08-23T09:07:35 | 2017-08-23T09:07:35 | 146,053,940 | 1 | 0 | null | 2018-08-25T01:13:44 | 2018-08-25T01:13:44 | null | UTF-8 | C++ | false | false | 422 | h | #pragma once
#include "..\UnityEngine\UnicodeString*.h"
#include "..\System\Xml\XmlQualifiedName.h"
namespace System
{
namespace Xml
{
{
namespace Serialization
{
class SoapSchemaMember : public Object // 0x0
{
public:
UnityEngine::UnicodeString* memberName; // 0x10 (size: 0x8, flags: 0x1, type: 0xe)
System::Xml::XmlQualifiedName* memberType; // 0x18 (size: 0x8, flags: 0x1, type: 0x12)
}; // size = 0x20
}
| [
"info@cvm-solutions.co.uk"
] | info@cvm-solutions.co.uk |
dccc942c86f9f5754e02fb3aa227020dcc76527c | 5da2b11371e80f92d07e602c0b961b490cf17ba7 | /MFC_Code/Code/038/038/038.h | 0dc532894ef06fcc50a4f9e58513beb4976e9488 | [] | no_license | Michael-prog/MFCTutorial | 694a5a6a76388bbb02b6fdc183cd8f6bf1259344 | e372ba0a8a40107490dac6745052c5a52df2311e | refs/heads/master | 2022-02-23T23:52:34.136004 | 2019-03-01T08:42:06 | 2019-03-01T08:42:06 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 446 | h |
// 038.h : PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CMy038App:
// 有关此类的实现,请参阅 038.cpp
//
class CMy038App : public CWinApp
{
public:
CMy038App();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
};
extern CMy038App theApp; | [
"dearfuture2012@gmail.com"
] | dearfuture2012@gmail.com |
79b048efd0aa701377db6b0ee20f1ab40342f26f | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13714/function13714_schedule_7/function13714_schedule_7_wrapper.cpp | 2226a0e38c7765cf0a95936f5cfac466deb08820 | [] | 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,463 | cpp | #include "Halide.h"
#include "function13714_schedule_7_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(512, 512);
Halide::Buffer<int32_t> buf01(512);
Halide::Buffer<int32_t> buf02(512);
Halide::Buffer<int32_t> buf03(512, 128);
Halide::Buffer<int32_t> buf04(512);
Halide::Buffer<int32_t> buf05(512);
Halide::Buffer<int32_t> buf06(512);
Halide::Buffer<int32_t> buf07(512, 128);
Halide::Buffer<int32_t> buf08(512);
Halide::Buffer<int32_t> buf0(512, 512, 128);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13714_schedule_7(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf08.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13714/function13714_schedule_7/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
7e04f33dfe6861f1eb266780c2fa340879d9e79e | 0f08276e557de8437759659970efc829a9cbc669 | /problems/p1661.h | a15782a8117b02f09d6f0166b2e06b8df8422188 | [] | no_license | petru-d/leetcode-solutions-reboot | 4fb35a58435f18934b9fe7931e01dabcc9d05186 | 680dc63d24df4c0cc58fcad429135e90f7dfe8bd | refs/heads/master | 2023-06-14T21:58:53.553870 | 2021-07-11T20:41:57 | 2021-07-11T20:41:57 | 250,795,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66 | h | #pragma once
namespace p1661
{
class Solution
{
};
}
| [
"berserk.ro@gmail.com"
] | berserk.ro@gmail.com |
1e8267217b0a556329cf0c44f0a6f1d8bec92847 | d932716790743d0e2ae7db7218fa6d24f9bc85dc | /components/ntp_snippets/content_suggestions_service.h | 40c442bc6bbb4d0d68834a41e2593b4282e66e9a | [
"BSD-3-Clause"
] | permissive | vade/chromium | c43f0c92fdede38e8a9b858abd4fd7c2bb679d9c | 35c8a0b1c1a76210ae000a946a17d8979b7d81eb | refs/heads/Syphon | 2023-02-28T00:10:11.977720 | 2017-05-24T16:38:21 | 2017-05-24T16:38:21 | 80,049,719 | 19 | 3 | null | 2017-05-24T19:05:34 | 2017-01-25T19:31:53 | null | UTF-8 | C++ | false | false | 19,215 | h | // Copyright 2016 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 COMPONENTS_NTP_SNIPPETS_CONTENT_SUGGESTIONS_SERVICE_H_
#define COMPONENTS_NTP_SNIPPETS_CONTENT_SUGGESTIONS_SERVICE_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/callback_forward.h"
#include "base/observer_list.h"
#include "base/optional.h"
#include "base/scoped_observer.h"
#include "base/supports_user_data.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/time/time.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_service_observer.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/ntp_snippets/callbacks.h"
#include "components/ntp_snippets/category.h"
#include "components/ntp_snippets/category_rankers/category_ranker.h"
#include "components/ntp_snippets/category_status.h"
#include "components/ntp_snippets/content_suggestions_provider.h"
#include "components/ntp_snippets/remote/remote_suggestions_scheduler.h"
#include "components/ntp_snippets/user_classifier.h"
#include "components/signin/core/browser/signin_manager.h"
class PrefService;
class PrefRegistrySimple;
namespace favicon {
class LargeIconService;
} // namespace favicon
namespace favicon_base {
struct LargeIconImageResult;
} // namespace favicon_base
namespace ntp_snippets {
class RemoteSuggestionsProvider;
// Retrieves suggestions from a number of ContentSuggestionsProviders and serves
// them grouped into categories. There can be at most one provider per category.
class ContentSuggestionsService : public KeyedService,
public base::SupportsUserData,
public ContentSuggestionsProvider::Observer,
public SigninManagerBase::Observer,
public history::HistoryServiceObserver {
public:
class Observer {
public:
// Fired every time the service receives a new set of data for the given
// |category|, replacing any previously available data (though in most cases
// there will be an overlap and only a few changes within the data). The new
// data is then available through |GetSuggestionsForCategory(category)|.
virtual void OnNewSuggestions(Category category) = 0;
// Fired when the status of a suggestions category changed. Note that for
// some status changes, the UI must update immediately (e.g. to remove
// invalidated suggestions). See comments on the individual CategoryStatus
// values for details.
virtual void OnCategoryStatusChanged(Category category,
CategoryStatus new_status) = 0;
// Fired when a suggestion has been invalidated. The UI must immediately
// clear the suggestion even from open NTPs. Invalidation happens, for
// example, when the content that the suggestion refers to is gone.
// Note that this event may be fired even if the corresponding category is
// not currently AVAILABLE, because open UIs may still be showing the
// suggestion that is to be removed. This event may also be fired for
// |suggestion_id|s that never existed and should be ignored in that case.
virtual void OnSuggestionInvalidated(
const ContentSuggestion::ID& suggestion_id) = 0;
// Fired when the previously sent data is not valid anymore and a refresh
// of all the suggestions is required. Called for example when the sign in
// state changes and personalised suggestions have to be shown or discarded.
virtual void OnFullRefreshRequired() = 0;
// Sent when the service is shutting down. After the service has shut down,
// it will not provide any data anymore, though calling the getters is still
// safe.
virtual void ContentSuggestionsServiceShutdown() = 0;
protected:
virtual ~Observer() = default;
};
enum State {
ENABLED,
DISABLED,
};
ContentSuggestionsService(
State state,
SigninManagerBase* signin_manager, // Can be nullptr in unittests.
history::HistoryService* history_service, // Can be nullptr in unittests.
// Can be nullptr in unittests.
favicon::LargeIconService* large_icon_service,
PrefService* pref_service,
std::unique_ptr<CategoryRanker> category_ranker,
std::unique_ptr<UserClassifier> user_classifier,
std::unique_ptr<RemoteSuggestionsScheduler>
remote_suggestions_scheduler // Can be nullptr in unittests.
);
~ContentSuggestionsService() override;
// Inherited from KeyedService.
void Shutdown() override;
static void RegisterProfilePrefs(PrefRegistrySimple* registry);
State state() { return state_; }
// Gets all categories for which a provider is registered. The categories may
// or may not be available, see |GetCategoryStatus()|. The order in which the
// categories are returned is the order in which they should be displayed.
std::vector<Category> GetCategories() const;
// Gets the status of a category.
CategoryStatus GetCategoryStatus(Category category) const;
// Gets the meta information of a category.
base::Optional<CategoryInfo> GetCategoryInfo(Category category) const;
// Gets the available suggestions for a category. The result is empty if the
// category is available and empty, but also if the category is unavailable
// for any reason, see |GetCategoryStatus()|.
const std::vector<ContentSuggestion>& GetSuggestionsForCategory(
Category category) const;
// Fetches the image for the suggestion with the given |suggestion_id| and
// runs the |callback|. If that suggestion doesn't exist or the fetch fails,
// the callback gets an empty image. The callback will not be called
// synchronously.
void FetchSuggestionImage(const ContentSuggestion::ID& suggestion_id,
const ImageFetchedCallback& callback);
// Fetches the favicon from local cache (if larger than or equal to
// |minimum_size_in_pixel|) or from Google server (if there is no icon in the
// cache) and returns the results in the callback. If that suggestion doesn't
// exist or the fetch fails, the callback gets an empty image. The callback
// will not be called synchronously.
void FetchSuggestionFavicon(const ContentSuggestion::ID& suggestion_id,
int minimum_size_in_pixel,
int desired_size_in_pixel,
const ImageFetchedCallback& callback);
// Dismisses the suggestion with the given |suggestion_id|, if it exists.
// This will not trigger an update through the observers (i.e. providers must
// not call |Observer::OnNewSuggestions|).
void DismissSuggestion(const ContentSuggestion::ID& suggestion_id);
// Dismisses the given |category|, if it exists.
// This will not trigger an update through the observers.
void DismissCategory(Category category);
// Restores all dismissed categories.
// This will not trigger an update through the observers.
void RestoreDismissedCategories();
// Returns whether |category| is dismissed.
bool IsCategoryDismissed(Category category) const;
// Fetches additional contents for the given |category|. If the fetch was
// completed, the given |callback| is called with the updated content.
// This includes new and old data.
// TODO(jkrcal): Consider either renaming this to FetchMore or unify the ways
// to get suggestions to just this async Fetch() API.
void Fetch(const Category& category,
const std::set<std::string>& known_suggestion_ids,
const FetchDoneCallback& callback);
// Reloads suggestions from all categories, from all providers. If a provider
// naturally has some ability to generate fresh suggestions, it may provide a
// completely new set of suggestions. If the provider has no ability to
// generate fresh suggestions on demand, it may only fill in any vacant space
// by suggestions that were previously not included due to space limits (there
// may be vacant space because of the user dismissing suggestions in the
// meantime).
void ReloadSuggestions();
// Observer accessors.
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
// Registers a new ContentSuggestionsProvider. It must be ensured that at most
// one provider is registered for every category and that this method is
// called only once per provider.
void RegisterProvider(std::unique_ptr<ContentSuggestionsProvider> provider);
// Removes history from the specified time range where the URL matches the
// |filter| from all providers. The data removed depends on the provider. Note
// that the data outside the time range may be deleted, for example
// suggestions, which are based on history from that time range. Providers
// should immediately clear any data related to history from the specified
// time range where the URL matches the |filter|.
void ClearHistory(base::Time begin,
base::Time end,
const base::Callback<bool(const GURL& url)>& filter);
// Removes all suggestions from all caches or internal stores in all
// providers. See |ClearCachedSuggestions|.
void ClearAllCachedSuggestions();
// Removes all suggestions of the given |category| from all caches or internal
// stores in the service and the corresponding provider. It does, however, not
// remove any suggestions from the provider's sources, so if its configuration
// hasn't changed, it might return the same results when it fetches the next
// time. In particular, calling this method will not mark any suggestions as
// dismissed.
void ClearCachedSuggestions(Category category);
// Only for debugging use through the internals page.
// Retrieves suggestions of the given |category| that have previously been
// dismissed and are still stored in the respective provider. If the
// provider doesn't store dismissed suggestions, the callback receives an
// empty vector. The callback may be called synchronously.
void GetDismissedSuggestionsForDebugging(
Category category,
const DismissedSuggestionsCallback& callback);
// Only for debugging use through the internals page. Some providers
// internally store a list of dismissed suggestions to prevent them from
// reappearing. This function clears all suggestions of the given |category|
// from such lists, making dismissed suggestions reappear (if the provider
// supports it).
void ClearDismissedSuggestionsForDebugging(Category category);
// Enables or disables the remote suggestions provider.
void SetRemoteSuggestionsEnabled(bool enabled);
// Returns true if the remote suggestions provider is enabled.
bool AreRemoteSuggestionsEnabled() const;
// Returns true if the remote provider is managed by an adminstrator's policy.
bool AreRemoteSuggestionsManaged() const;
// Returns true if the remote provider is managed by the guardian/parent of a
// child account.
bool AreRemoteSuggestionsManagedByCustodian() const;
// The reference to the RemoteSuggestionsProvider provider should
// only be set by the factory and only used for debugging.
// TODO(jkrcal) The way we deal with the circular dependency feels wrong.
// Consider swapping the dependencies: first constructing all providers, then
// constructing the service (passing the remote provider as arg), finally
// registering the service as an observer of all providers?
// TODO(jkrcal) Move the getter into the scheduler interface (the setter is
// then not needed any more). crbug.com/695447
void set_remote_suggestions_provider(
RemoteSuggestionsProvider* remote_suggestions_provider) {
remote_suggestions_provider_ = remote_suggestions_provider;
}
RemoteSuggestionsProvider* remote_suggestions_provider_for_debugging() {
return remote_suggestions_provider_;
}
// The interface is suited for informing about external events that have
// influence on scheduling remote fetches. Can be nullptr in tests.
RemoteSuggestionsScheduler* remote_suggestions_scheduler() {
return remote_suggestions_scheduler_.get();
}
// Can be nullptr in tests.
// TODO(jkrcal): The getter is only used from the bridge and from
// snippets-internals. Can we get rid of it with the metrics refactoring?
UserClassifier* user_classifier() { return user_classifier_.get(); }
CategoryRanker* category_ranker() { return category_ranker_.get(); }
private:
friend class ContentSuggestionsServiceTest;
// Implementation of ContentSuggestionsProvider::Observer.
void OnNewSuggestions(ContentSuggestionsProvider* provider,
Category category,
std::vector<ContentSuggestion> suggestions) override;
void OnCategoryStatusChanged(ContentSuggestionsProvider* provider,
Category category,
CategoryStatus new_status) override;
void OnSuggestionInvalidated(
ContentSuggestionsProvider* provider,
const ContentSuggestion::ID& suggestion_id) override;
// SigninManagerBase::Observer implementation
void GoogleSigninSucceeded(const std::string& account_id,
const std::string& username,
const std::string& password) override;
void GoogleSignedOut(const std::string& account_id,
const std::string& username) override;
// history::HistoryServiceObserver implementation.
void OnURLsDeleted(history::HistoryService* history_service,
bool all_history,
bool expired,
const history::URLRows& deleted_rows,
const std::set<GURL>& favicon_urls) override;
void HistoryServiceBeingDeleted(
history::HistoryService* history_service) override;
// Registers the given |provider| for the given |category|, unless it is
// already registered. Returns true if the category was newly registered or
// false if it is dismissed or was present before.
bool TryRegisterProviderForCategory(ContentSuggestionsProvider* provider,
Category category);
void RegisterCategory(Category category,
ContentSuggestionsProvider* provider);
void UnregisterCategory(Category category,
ContentSuggestionsProvider* provider);
// Removes a suggestion from the local store |suggestions_by_category_|, if it
// exists. Returns true if a suggestion was removed.
bool RemoveSuggestionByID(const ContentSuggestion::ID& suggestion_id);
// Fires the OnCategoryStatusChanged event for the given |category|.
void NotifyCategoryStatusChanged(Category category);
void OnSignInStateChanged();
// Re-enables a dismissed category, making querying its provider possible.
void RestoreDismissedCategory(Category category);
void RestoreDismissedCategoriesFromPrefs();
void StoreDismissedCategoriesToPrefs();
// Get the domain of the suggestion suitable for fetching the favicon.
GURL GetFaviconDomain(const ContentSuggestion::ID& suggestion_id);
// Initiate the fetch of a favicon from the local cache.
void GetFaviconFromCache(const GURL& publisher_url,
int minimum_size_in_pixel,
int desired_size_in_pixel,
const ImageFetchedCallback& callback,
bool continue_to_google_server);
// Callbacks for fetching favicons.
void OnGetFaviconFromCacheFinished(
const GURL& publisher_url,
int minimum_size_in_pixel,
int desired_size_in_pixel,
const ImageFetchedCallback& callback,
bool continue_to_google_server,
const favicon_base::LargeIconImageResult& result);
void OnGetFaviconFromGoogleServerFinished(
const GURL& publisher_url,
int minimum_size_in_pixel,
int desired_size_in_pixel,
const ImageFetchedCallback& callback,
bool success);
// Whether the content suggestions feature is enabled.
State state_;
// All registered providers, owned by the service.
std::vector<std::unique_ptr<ContentSuggestionsProvider>> providers_;
// All registered categories and their providers. A provider may be contained
// multiple times, if it provides multiple categories. The keys of this map
// are exactly the entries of |categories_| and the values are a subset of
// |providers_|.
std::map<Category, ContentSuggestionsProvider*, Category::CompareByID>
providers_by_category_;
// All dismissed categories and their providers. These may be restored by
// RestoreDismissedCategories(). The provider can be null if the dismissed
// category has received no updates since initialisation.
// (see RestoreDismissedCategoriesFromPrefs())
std::map<Category, ContentSuggestionsProvider*, Category::CompareByID>
dismissed_providers_by_category_;
// All current suggestion categories in arbitrary order. This vector contains
// exactly the same categories as |providers_by_category_|.
std::vector<Category> categories_;
// All current suggestions grouped by category. This contains an entry for
// every category in |categories_| whose status is an available status. It may
// contain an empty vector if the category is available but empty (or still
// loading).
std::map<Category, std::vector<ContentSuggestion>, Category::CompareByID>
suggestions_by_category_;
// Observer for the SigninManager. All observers are notified when the signin
// state changes so that they can refresh their list of suggestions.
ScopedObserver<SigninManagerBase, SigninManagerBase::Observer>
signin_observer_;
// Observer for the HistoryService. All providers are notified when history is
// deleted.
ScopedObserver<history::HistoryService, history::HistoryServiceObserver>
history_service_observer_;
base::ObserverList<Observer> observers_;
const std::vector<ContentSuggestion> no_suggestions_;
base::CancelableTaskTracker favicons_task_tracker_;
// Keep a direct reference to this special provider to redirect debugging
// calls to it. If the RemoteSuggestionsProvider is loaded, it is also present
// in |providers_|, otherwise this is a nullptr.
RemoteSuggestionsProvider* remote_suggestions_provider_;
favicon::LargeIconService* large_icon_service_;
PrefService* pref_service_;
// Interface for informing about external events that have influence on
// scheduling remote fetches.
std::unique_ptr<RemoteSuggestionsScheduler> remote_suggestions_scheduler_;
// Classifies the user on the basis of long-term user interactions.
std::unique_ptr<UserClassifier> user_classifier_;
// Provides order for categories.
std::unique_ptr<CategoryRanker> category_ranker_;
DISALLOW_COPY_AND_ASSIGN(ContentSuggestionsService);
};
} // namespace ntp_snippets
#endif // COMPONENTS_NTP_SNIPPETS_CONTENT_SUGGESTIONS_SERVICE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
158bdd7bcb7334b280408d694aff80acd413c92a | 1dd521e69331aefcce34c2c733ea8cc518d8fa5d | /src/Core/Algorithms/Field/Tests/ExtractSimpleIsoSurfaceAlgoTests.cc | 9725759f936c2678019906fd6f96c4af4ee9579d | [
"MIT"
] | permissive | Nahusa/SCIRun | b75d4d283d9cc6f802aed390d4c8d210a901ba2d | c54e714d4c7e956d053597cf194e07616e28a498 | refs/heads/master | 2020-03-23T20:23:00.688044 | 2018-08-15T17:48:35 | 2018-08-15T17:48:35 | 142,037,816 | 0 | 0 | MIT | 2018-07-23T16:04:23 | 2018-07-23T16:04:23 | null | UTF-8 | C++ | false | false | 3,756 | cc | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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.
author: Moritz Dannhauer
last change: 04/21/2015
*/
#include <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/ExtractSimpleIsosurfaceAlgo.h>
#include <Testing/Utils/SCIRunUnitTests.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Testing/Utils/MatrixTestUtilities.h>
#include <Core/Datatypes/DenseMatrix.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
FieldHandle LoadInTriangles()
{
return loadFieldFromFile(TestResources::rootDir() / "Fields/extractsimpleisosurface/test_isosimsuf_tri.fld");
}
FieldHandle LoadInTetrahedrals()
{
return loadFieldFromFile(TestResources::rootDir() / "Fields/extractsimpleisosurface/test_isosimsuf_tet.fld");
}
FieldHandle LoadInLatVol()
{
return loadFieldFromFile(TestResources::rootDir() / "Fields/extractsimpleisosurface/test_isosimsuf_latvol.fld");
}
TEST(ExtractSimpleIsoSurfaceAlgoTest, ExtractSimpleIsoSurf_Triangles_DataOnNodes)
{
ExtractSimpleIsosurfaceAlgo algo;
FieldHandle input_tiangle, output;
input_tiangle=LoadInTriangles();
std::vector<double> isovalues;
isovalues.push_back(1.5);
algo.run(input_tiangle,isovalues,output);
EXPECT_EQ(output->vmesh()->num_nodes(),12);
EXPECT_EQ(output->vmesh()->num_elems(),12);
EXPECT_EQ(output->vfield()->num_values(),12);
}
TEST(ExtractSimpleIsoSurfaceAlgoTest, ExtractSimpleIsoSurf_Tetrahedrals_DataOnNodes)
{
ExtractSimpleIsosurfaceAlgo algo;
FieldHandle input_tiangle, output;
input_tiangle=LoadInTetrahedrals();
std::vector<double> isovalues;
isovalues.push_back(0.0);
algo.run(input_tiangle,isovalues,output);
EXPECT_EQ(output->vmesh()->num_nodes(),60);
EXPECT_EQ(output->vmesh()->num_elems(),116);
EXPECT_EQ(output->vfield()->num_values(),60);
}
TEST(ExtractSimpleIsoSurfaceAlgoTest, ExtractSimpleIsoSurf_LatVol_DataOnNodes)
{
ExtractSimpleIsosurfaceAlgo algo;
FieldHandle input_tiangle, output;
input_tiangle=LoadInLatVol();
std::vector<double> isovalues;
isovalues.push_back(0.3);
algo.run(input_tiangle,isovalues,output);
EXPECT_EQ(output->vmesh()->num_nodes(),5);
EXPECT_EQ(output->vmesh()->num_elems(),3);
EXPECT_EQ(output->vfield()->num_values(),5);
}
| [
"moritz@sci.utah.edu"
] | moritz@sci.utah.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.