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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
111abc3b4edb8f0d9d195a6656ca6baa353533f4 | 200df01c4c9eb9f6cca4e8b453acc782086340ef | /cpp/limit_direction.cpp | 306883c00675a57993a78a017bea90e1eebc2e40 | [] | no_license | lacrymose/3bem | 18255b0e1e65d7f844c24ff489cb2ea817bd785d | 8558df4b0786c55593078f261e20739f40fe3701 | refs/heads/master | 2021-05-29T07:08:41.197154 | 2015-09-17T21:29:33 | 2015-09-17T21:29:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,371 | cpp | #include "limit_direction.h"
#include "geometry.h"
#include "nearest_neighbors.h"
#include "gte_wrapper.h"
#include "intersect_balls.h"
namespace tbem {
template <size_t dim>
NearfieldFacetFinder<dim>::NearfieldFacetFinder(
const std::vector<Vec<Vec<double,dim>,dim>>& facets,
double far_threshold):
nn_data(facets, 20),
far_threshold(far_threshold)
{}
template <size_t dim>
NearfieldFacets<dim>
NearfieldFacetFinder<dim>::find(const Vec<double,dim>& pt) const
{
//steps:
//-- find the nearest facet (nearest neighbors search)
auto nearest_neighbor = nearest_facet(pt, nn_data);
auto closest_facet_idx = nearest_neighbor.idx;
if (nn_data.facets.size() == 0) {
return {{}, 0, zeros<Vec<double,dim>>::make(), 0};
}
//-- determine the search radius for nearfield facets
auto closest_facet = nn_data.facets[closest_facet_idx];
auto closest_facet_ball = facet_ball(closest_facet);
Ball<dim> search_ball{
closest_facet_ball.center, closest_facet_ball.radius * far_threshold
};
//-- find the facet balls intersecting the sphere with that radius
auto near_ball_indices = intersect_balls(
search_ball, nn_data.facet_balls, nn_data.oct
);
//-- filter the facet balls to find the facets that actually intersected
//by the sphere (rather than just the surrounding ball)
std::vector<size_t> close_facet_indices;
for (size_t facet_idx: near_ball_indices) {
auto f = nn_data.facets[facet_idx];
auto closest_pt = closest_pt_facet(pt, f);
if (closest_pt.distance <= search_ball.radius) {
close_facet_indices.push_back(facet_idx);
}
}
return {
close_facet_indices, closest_facet_idx,
nearest_neighbor.pt, nearest_neighbor.distance
};
}
template struct NearfieldFacetFinder<2>;
template struct NearfieldFacetFinder<3>;
template <size_t dim>
Vec<double,dim> backup_halfway_from_intersection(Vec<double,dim> end_pt,
double len_scale, const Vec<double,dim>& pt,
const NearfieldFacets<dim>& nearfield_facets,
const std::vector<Vec<Vec<double,dim>,dim>>& facets)
{
for (auto f_idx: nearfield_facets.facet_indices) {
if (f_idx == nearfield_facets.nearest_facet_idx) {
continue;
}
auto f = facets[f_idx];
std::vector<Vec<double,dim>> intersections =
seg_facet_intersection<dim>(f, {end_pt, pt});
assert(intersections.size() != 2);
if (intersections.size() == 1 && intersections[0] != pt) {
auto to_intersection_dir = intersections[0] - pt;
if (hypot(to_intersection_dir) < 1e-12 * len_scale) {
continue;
}
end_pt = pt + to_intersection_dir / 2.0;
}
}
return end_pt;
}
template <size_t dim>
Vec<double,dim> decide_limit_dir(const Vec<double,dim>& pt,
const NearfieldFacets<dim>& nearfield_facets,
const std::vector<Vec<Vec<double,dim>,dim>>& facets,
double safety_factor,
double epsilon)
{
if (nearfield_facets.facet_indices.size() == 0) {
return zeros<Vec<double,dim>>::make();
}
auto closest_facet = facets[nearfield_facets.nearest_facet_idx];
// The length scale here needs to be exactly double the length scale
// used in finding the nearest facets.
double len_scale = facet_ball(closest_facet).radius * 2;
// If the point isn't lying precisely on any facet, then no limit
// needs to be taken, in which case the limit direction is the 0 vector.
double threshold = len_scale * epsilon;
if (nearfield_facets.distance > threshold) {
return zeros<Vec<double,dim>>::make();
}
// In the plane of the facet, the limit direction will point towards the
// centroid of the facet. Out of the plane of the facet, the limit direction
// will point in the same direction as the facet's normal, with a magnitude
// similar to the length scale of the facet.
auto close_center = centroid(closest_facet);
auto end_pt = close_center + facet_normal(closest_facet) * len_scale;
// Make sure that the end point is within the interior of the mesh (the
// line segment from the centroid of the element to the end_pt does not
// intersect any edges)
// auto interior_pt = end_pt;
// TODO: Figure out why this doesn't work in 3D
auto interior_pt = backup_halfway_from_intersection(
end_pt, len_scale, close_center, nearfield_facets, facets
);
// Check if the vector intersects any facets.
// If it does, back up to halfway between the intersection point and the
// singular point
auto backup_pt = backup_halfway_from_intersection(
interior_pt, len_scale, pt, nearfield_facets, facets
);
// Scaling from facet length scale down after doing the
// intersection tests is safer because a wider range of
// facet intersections are checked and avoided.
auto limit_dir = (backup_pt - pt) * safety_factor;
return limit_dir;
}
template Vec<double,2>
decide_limit_dir(const Vec<double,2>&, const NearfieldFacets<2>&,
const std::vector<Vec<Vec<double,2>,2>>&, double, double);
template Vec<double,3>
decide_limit_dir(const Vec<double,3>&, const NearfieldFacets<3>&,
const std::vector<Vec<Vec<double,3>,3>>&, double, double);
} // end namespace tbem
| [
"t.ben.thompson@gmail.com"
] | t.ben.thompson@gmail.com |
0a8287d800acdd2e261a5c990ca56d1ff26cb929 | 506a0df6c523efc8b2a4e74a7e302cd8bb09fbd9 | /opencv/main8.cpp | 40fed3b69d672317b09eb076147482fd4c24d2f1 | [] | no_license | SatoshiShimada/ppm | 180492e4e5d22ac0aee4683bc36ae97343cc9b2b | 78a26ab1582aec1c04914940ca968a9d90e52d14 | refs/heads/master | 2016-09-06T04:58:27.645762 | 2015-09-02T13:03:16 | 2015-09-02T13:03:16 | 40,110,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,122 | cpp |
#include "cv.h"
#include "highgui.h"
#include "ctype.h"
int main(void)
{
IplImage *src_img = 0;
IplImage *src_img_gray = 0;
IplImage *dst_img = 0;
IplImage *dst_img1 = 0;
IplImage *dst_img2 = 0;
IplImage *tmp_img = 0;
IplImage *out1 = 0, *out2 = 0, *out3 = 0;
char *filename = (char *)"image_320x240.png";
int x, y;
unsigned char r, g, b;
src_img = cvLoadImage(filename, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR);
tmp_img = cvCloneImage(src_img);
dst_img = cvCloneImage(src_img);
dst_img1 = cvCreateImage(cvGetSize(src_img), IPL_DEPTH_8U, 1);
dst_img2 = cvCreateImage(cvGetSize(src_img), IPL_DEPTH_8U, 1);
out1 = cvCreateImage(cvGetSize(src_img), IPL_DEPTH_8U, 1);
out2 = cvCreateImage(cvGetSize(src_img), IPL_DEPTH_8U, 1);
out3 = cvCreateImage(cvGetSize(src_img), IPL_DEPTH_8U, 1);
////////////////////////////////////////////////////////////
src_img_gray = cvCreateImage(cvGetSize(src_img), IPL_DEPTH_8U, 1);
cvCvtColor(src_img, src_img_gray, CV_BGR2GRAY);
cvThreshold(src_img_gray, dst_img1, 138, 255, CV_THRESH_BINARY);
////////////////////////////////////////////////////////////
for(y = 0; y < tmp_img->height; y++) {
for(x = 0; x < tmp_img->width; x++) {
b = tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 0];
g = tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 1];
r = tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 2];
if(r < 100 || b < 100) {
tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 0] = 0x00;
tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 1] = 0x00;
tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 2] = 0x00;
} else {
tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 0] = 0xff;
tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 1] = 0xff;
tmp_img->imageData[tmp_img->widthStep * y + x * 3 + 2] = 0xff;
}
}
}
cvCvtColor(tmp_img, dst_img2, CV_BGR2GRAY);
////////////////////////////////////////////////////////////
/* AND OR */
cvAnd(dst_img1, dst_img2, out1, NULL);
cvOr(dst_img1, dst_img2, out2, NULL);
cvXor(dst_img1, dst_img2, out3);
cvCvtColor(out2, tmp_img, CV_GRAY2BGR);
cvAnd(src_img, tmp_img, dst_img);
////////////////////////////////////////////////////////////
cvNamedWindow("Source", CV_WINDOW_AUTOSIZE);
cvShowImage("Source", src_img);
cvNamedWindow("Threshold1", CV_WINDOW_AUTOSIZE);
cvShowImage("Threshold1", dst_img1);
cvNamedWindow("Threshold2", CV_WINDOW_AUTOSIZE);
cvShowImage("Threshold2", dst_img2);
cvNamedWindow("AND", CV_WINDOW_AUTOSIZE);
cvShowImage("AND", out1);
cvNamedWindow("OR", CV_WINDOW_AUTOSIZE);
cvShowImage("OR", out2);
cvNamedWindow("EX_OR", CV_WINDOW_AUTOSIZE);
cvShowImage("EX_OR", out2);
cvNamedWindow("Robot vision", CV_WINDOW_AUTOSIZE);
cvShowImage("Robot vision", dst_img);
cvWaitKey(0);
cvDestroyWindow("Source");
cvDestroyWindow("Threshold1");
cvDestroyWindow("Threshold2");
cvDestroyWindow("AND");
cvDestroyWindow("OR");
cvDestroyWindow("EX_OR");
cvDestroyWindow("Robot vision");
cvReleaseImage(&src_img);
cvReleaseImage(&src_img_gray);
cvReleaseImage(&dst_img1);
cvReleaseImage(&dst_img2);
return 0;
}
| [
"mylinux1204@gmail.com"
] | mylinux1204@gmail.com |
de1b87c2a390edb22cd128d3e22251889275388d | f1618c71c0f5a175ffe06f3c0e0adf9b703ac87d | /ogl-training/12-OGL-MultipleLights-project/OGL-first-project/main.cpp | 3e7a45fdbaf16aa80662abc02ee922d95daf8d6b | [] | no_license | whaleeej/Learn-OpenGL | 7d352305687219b246cb080e37753421ce02f43b | f56f85c60369e28c656e47884e13556efebb9be1 | refs/heads/master | 2023-08-05T08:38:37.422191 | 2019-07-06T08:04:45 | 2019-07-06T08:04:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,632 | cpp | #define STB_IMAGE_IMPLEMENTATION
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include "Shader.h"
#include "stb_image.h"
#include "camera.h"
//camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
//framerate
float currentFrame = glfwGetTime();
float deltaTime = 0.0f; // Time between current frame and last frame
float lastFrame = currentFrame;
//screen parameter
int screenWidth = 1920;
int screenHeight = 1080;
float lastX = screenWidth/2, lastY = screenHeight/2;
bool firstMouse = true;
//------------------------------------data
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
glm::vec3 pointLightPositions[] = {
glm::vec3(0.7f, 0.2f, 2.0f),
glm::vec3(2.3f, -3.3f, -4.0f),
glm::vec3(-4.0f, 2.0f, -8.0f),
glm::vec3(0.0f, 0.0f, -3.0f)
};
glm::vec3 pointLightColors[] = {
glm::vec3(1.0f, 1.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 1.0f),
glm::vec3(0.0f, 0.0f, 1.0f),
glm::vec3(1.0f, 0.4f, 0.0f)
};
float vertices[] = {
// positions // normals // texture coords
-0.5f, -0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0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void processInput(GLFWwindow *window);
unsigned int loadTexture(char const * path);
int main()
{
//------------------------------------Window initial
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glViewport(0, 0, screenWidth, screenHeight);
//------------------------------------register
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
//------------------------------------vertex buffer
//color cube gen a VAO
unsigned int VAO;
glGenVertexArrays(1, &VAO);
//generate a VBO
unsigned int VBO;
glGenBuffers(1, &VBO);
// bind Vertex Array Object
glBindVertexArray(VAO);
//buffer for VBO
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//set our vertex attributes pointers
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(0));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(sizeof(float)*3));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(sizeof(float)*6));
glEnableVertexAttribArray(2);
//light cube gen a VAO
unsigned int LightVAO;
glGenVertexArrays(1, &LightVAO);
glBindVertexArray(LightVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)(0));
glEnableVertexAttribArray(0);
//------------------------------------texture
unsigned int textureDiffuse=loadTexture("container.png");
unsigned int textureSpecular = loadTexture("container2_specular.png");
//------------------------------------shader
Shader lightShader("lightshader.vs", "lightshader.fs");
lightShader.use();
lightShader.setInt("material.diffuse",0);//bind with the texture
lightShader.setInt("material.specular", 1);
lightShader.setFloat("material.shininess", 32.0f);
Shader normalShader("normalshader.vs", "normalshader.fs");
normalShader.use();
//------------------------------------z-buffer
glEnable(GL_DEPTH_TEST);
//------------------------------------render loop
while (!glfwWindowShouldClose(window))
{
//frametime
currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// input
processInput(window);
// rendering commands here
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);//state-setting
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//state-using
//view
glm::mat4 view = camera.GetViewMatrix();
//proj
glm::mat4 projection;
projection = glm::perspective(glm::radians(camera.Zoom), (float)screenWidth / (float)screenHeight, 0.1f, 100.0f);
//Light CUBE
normalShader.use();
//view and proj
normalShader.setMat4("view", view);
normalShader.setMat4("projection", projection);
glBindVertexArray(LightVAO);
for (int i = 0; i < 4; i++)
{
//shader
normalShader.setVec3("color", pointLightColors[i]);
//model
int modelLoc = glGetUniformLocation(lightShader.ID, "model");
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, pointLightPositions[i]);
model = glm::scale(model, glm::vec3(0.1f));
normalShader.setMat4("model",model);
//draw
glDrawArrays(GL_TRIANGLES, 0, 36);
}
//COLOR CUBE
lightShader.use();
//diffuse and specular map
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureDiffuse);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureSpecular);
//view and proj
lightShader.setMat4("view", view);
lightShader.setMat4("projection", projection);
lightShader.setVec3("viewPos", camera.Position);
//lights
{
// directional light
lightShader.setVec3("directlight.direction", -0.2f, -1.0f, -0.3f);
lightShader.setVec3("directlight.ambient", 0.05f, 0.05f, 0.05f);
lightShader.setVec3("directlight.diffuse", 0.6f, 0.6f, 0.64f);
lightShader.setVec3("directlight.specular", 0.8f, 0.8f, 0.8f);
// point light 1
lightShader.setVec3("pointlights[0].position", pointLightPositions[0]);
lightShader.setVec3("pointlights[0].ambient", 0.5f*pointLightColors[0]);
lightShader.setVec3("pointlights[0].diffuse", 0.8f*pointLightColors[0]);
lightShader.setVec3("pointlights[0].specular", pointLightColors[0]);
lightShader.setFloat("pointlights[0].constant", 1.0f);
lightShader.setFloat("pointlights[0].linear", 0.09);
lightShader.setFloat("pointlights[0].quadratic", 0.032);
// point light 2
lightShader.setVec3("pointlights[1].position", pointLightPositions[1]);
lightShader.setVec3("pointlights[1].ambient", 0.5f*pointLightColors[1]);
lightShader.setVec3("pointlights[1].diffuse", 0.8f*pointLightColors[1]);
lightShader.setVec3("pointlights[1].specular", pointLightColors[1]);
lightShader.setFloat("pointlights[1].constant", 1.0f);
lightShader.setFloat("pointlights[1].linear", 0.09);
lightShader.setFloat("pointlights[1].quadratic", 0.032);
// point light 3
lightShader.setVec3("pointlights[2].position", pointLightPositions[2]);
lightShader.setVec3("pointlights[2].ambient", 0.5f*pointLightColors[2]);
lightShader.setVec3("pointlights[2].diffuse", 0.8f*pointLightColors[2]);
lightShader.setVec3("pointlights[2].specular", pointLightColors[2]);
lightShader.setFloat("pointlights[2].constant", 1.0f);
lightShader.setFloat("pointlights[2].linear", 0.09);
lightShader.setFloat("pointlights[2].quadratic", 0.032);
// point light 4
lightShader.setVec3("pointlights[3].position", pointLightPositions[3]);
lightShader.setVec3("pointlights[3].ambient", 0.5f*pointLightColors[3]);
lightShader.setVec3("pointlights[3].diffuse", 0.8f*pointLightColors[3]);
lightShader.setVec3("pointlights[3].specular", pointLightColors[3]);
lightShader.setFloat("pointlights[3].constant", 1.0f);
lightShader.setFloat("pointlights[3].linear", 0.09);
lightShader.setFloat("pointlights[3].quadratic", 0.032);
// spotLight
lightShader.setVec3("spotlight.position", camera.Position);
lightShader.setVec3("spotlight.direction", camera.Front);
lightShader.setVec3("spotlight.ambient", 0.0f, 0.0f, 0.0f);
lightShader.setVec3("spotlight.diffuse", 0.5f, 0.5f, 0.5f);
lightShader.setVec3("spotlight.specular", 1.0f, 1.0f, 1.0f);
lightShader.setFloat("spotlight.constant", 1.0f);
lightShader.setFloat("spotlight.linear", 0.09);
lightShader.setFloat("spotlight.quadratic", 0.032);
lightShader.setFloat("spotlight.innercutOff", glm::cos(glm::radians(10.0f)));
lightShader.setFloat("spotlight.outercutOff", glm::cos(glm::radians(12.5f)));
}
glBindVertexArray(VAO);
for (int i = 0; i < 10; i++)
{
//model
int modelLoc = glGetUniformLocation(lightShader.ID, "model");
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, cubePositions[i]);
float angle = 20.0f * i;
model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
lightShader.setMat4("model", model);
//draw
glDrawArrays(GL_TRIANGLES, 0, 36);
}
// check and call events and swap the buffers
glfwPollEvents();
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
unsigned int loadTexture(char const * path)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
screenHeight = height;
screenWidth = width;
glViewport(0, 0, width, height);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse) // this bool variable is initially set to true
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
else {
camera.ProcessMouseMovement(xpos - lastX, lastY - ypos);
lastX = xpos;
lastY = ypos;
}
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
float cameraSpeed = 2.5f * deltaTime;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(Camera_Movement::RIGHT, deltaTime);
} | [
"ceej_7@hotmail.com"
] | ceej_7@hotmail.com |
3ae0ed67cb5204819350778b493dc9acfc7af686 | 937c4ae23e4ecf98f728b2fe5fcbc935078ab4f6 | /2022/OMI-presencial/OMI-2022-bruxismo/solutions/sol_sub3.cpp | b9fb1bb3ae1f326b6f719a966a09d7782ccfbfca | [] | no_license | ComiteMexicanoDeInformatica/OMI-Archive | b57e9bbca81d07d16b6bf00426592528cf8934fb | 16e49707474132496efb8bae9e2c24e11de0d5fb | refs/heads/main | 2023-06-08T11:04:34.141168 | 2023-06-01T16:25:08 | 2023-06-01T16:25:08 | 239,215,823 | 9 | 11 | null | 2023-06-01T16:25:10 | 2020-02-08T22:52:24 | Roff | UTF-8 | C++ | false | false | 3,242 | cpp | #include <algorithm>
#include <iostream>
#include <set>
#include <vector>
#define debugsl(x) std::cout << #x << " = " << x << ", "
#define debug(x) debugsl(x) << "\n";
#define MAX 250000
#define MAXD 10000
#define MAXA 20
#define fuerza first
#define id second
#define fin first
#define maximo second
int n, a[MAX + 2], b[MAX + 2], d[MAX + 2], m[MAX + 2], res[MAX + 2];
int T, t[MAXD + 2], valordia[MAXD + 2];
int offset;
std::set<int> diasEnCero;
std::vector<std::pair<int, int> > eventos;
std::pair<int, int> stmax[MAX * 4 + 2];
void actualiza(int nodo, int val) {
nodo = offset + nodo; // PONLE EL OFFSET DEL SEGMENT TREE
stmax[nodo].fin = val;
stmax[nodo].maximo = std::max(0, val);
nodo >>= 1;
while (nodo) {
int hi = nodo * 2;
int hd = hi ^ 1;
stmax[nodo].fin = stmax[hi].fin + stmax[hd].fin;
stmax[nodo].maximo =
std::max(stmax[hi].maximo, stmax[hd].maximo + stmax[hi].fin);
nodo >>= 1;
}
}
int main() {
std::cin >> n >> T;
for (int i = 1; i <= n; ++i) std::cin >> d[i] >> a[i] >> b[i] >> m[i];
for (int i = 1; i <= T; ++i) std::cin >> t[i];
offset = 1;
while (offset < T) offset <<= 1;
--offset;
// PARA OPTIMIZAR EL PROCESO SE VAN A PROCESAR LOS DIAS EN ORDEN DE FUERZA DE
// MAYOR A MENOR Y EN PARALELO LOS DIENTES DE MAYOR A MENOR RESISTENCIA. EL
// OBJETIVO ES QUE CUANDO SE PROCESE UN DIENTE YA SE HAYAN PROCESADO TODOS LOS
// DIAS DE FUERZA MAYOR A SU RESISTENCIA, ES DECIR, AQUELLOS DIAS EN LOS QUE
// EL DIENTE SUFRIO DANO.
for (int i = 1; i <= n; ++i) eventos.emplace_back(d[i], i);
for (int i = 1; i <= T; ++i) {
eventos.emplace_back(t[i], -i);
diasEnCero.emplace_hint(diasEnCero.end(), i);
}
std::sort(eventos.begin(), eventos.end());
std::reverse(eventos.begin(), eventos.end());
for (auto ev : eventos) {
if (ev.id < 0) { // ES DE TIPO DIA
// CUANDO UN DIA APLICA SU DANIO CAMBIA A POSITIVO. LOS DIAS ADELANTE DE
// EL SE VEN AFECTADOS, SI UN DIA ERA POSITIVO O NEGATIVO SUBE SU VALOR,
// SI ERA CERO, PUEDE VOLVERSE NEGATIVO PARA TRATAR DE "REGRESAR" LA
// GRAFICA A CERO. DEPENDIENDO DE SI EL VALOR DEL DIA AFECTADO ERA CERO O
// NEGATIVO (NO PUEDE SER POSITIVO) SE DEBEN ACTUALIZAR 1 O 2 VALORES CERO
// ADELANTE DE EL
auto it = diasEnCero.lower_bound(-ev.id);
int afectados;
if (it != diasEnCero.end() && *it == -ev.id) {
// ESE DIA TENIA VALOR 0, SOLO HAY QUE ACTUALIZAR UN 0 A NEGATIVO
afectados = 1;
it = diasEnCero.erase(it); // BORRALO Y APUNTA AL SIGUIENTE
} else
afectados = 2; // EL DIA YA ERA NEGATIVO, HAY QUE AFECTAR DOS CEROS.
actualiza(-ev.id, 1);
while (it != diasEnCero.end() && afectados) {
actualiza(*it, -1); // ACTUALIZA ESTE DIA PARA QUE SEA UN NEGATIVO
it = diasEnCero.erase(it); // BORRALO DE LOS CEROS
--afectados;
}
} else {
// SI ES UN EVENTO DE DIA, HAY QUE VER CUAL ES EL MAXIMO EN ESE MOMENTO,
// MULTIPLICARLO POR EL DANIO ESPECIFICO DE ESE DIENTE Y VER SI SE CAE
if (a[ev.id] * stmax[1].maximo >= m[ev.id]) res[ev.id] = 1;
}
}
for (int i = 1; i <= n; ++i) std::cout << res[i] << " ";
std::cout << "\n";
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
5cce8d90f6dee7d858f7e31c238b5dc81c9bff7b | 35e37301da769cb95898174b3947d48108b54d64 | /qroilib/qroilib/roilib/layeritem.cpp | 969d19a77e0431adf61720f90fe9e13be021ac0a | [] | no_license | sheiling/QT-qroilib | 437eb175e3d1ed3172fccf24435f6f1d95ef7b07 | ea87dc83dedbcca6b8980847cad7da72610d4ed0 | refs/heads/master | 2020-09-03T10:22:24.742871 | 2018-12-03T06:10:14 | 2018-12-03T06:10:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | cpp | /*
* layeritem.cpp
* Copyright 2017, Thorbjørn Lindeijer <bjorn@lindeijer.nl>
*
* This file is part of Tiled.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "layeritem.h"
#include "layer.h"
#include <qroilib/documentview/documentview.h>
#include <qroilib/documentview/rasterimageview.h>
namespace Qroilib {
LayerItem::LayerItem(Layer *layer, QGraphicsItem *parent)
: QGraphicsItem(parent)
, mLayer(layer)
{
setOpacity(layer->opacity());
//setPos(layer->offset());
}
QRectF LayerItem::boundingRect() const
{
return QRectF();
// QSizeF size = mapDocument()->size();
// const qreal zoom = mapDocument()->zoom();
// return QRectF(QPointF(0,0), size*zoom);
}
} // namespace Qroilib
| [
"jerry1455@gmail.com"
] | jerry1455@gmail.com |
3e8aedc85c4767029adc6ea03a14fe7c06931ae4 | cd91d1d93936077c9e4dccb4f548b40c47b1f5af | /C++/Annotator/PointAnimation.h | 59df017bf5987e2fa279e05b51ec9f3f94a05efb | [] | no_license | dbremner/Hilo | a6218197555dca097de586ff8c6a28d507c98639 | ba7d1ca59d60e0d54b5b37d74416be2290540611 | refs/heads/master | 2016-08-11T12:42:32.240157 | 2015-11-29T23:01:25 | 2015-11-29T23:01:25 | 47,081,033 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,610 | h | //===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED 'AS IS' WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
#pragma once
#include "Animation.h"
class PointAnimation : public IInitializable, public IPointAnimation
{
public:
HRESULT __stdcall GetCurrentPoint(__out D2D1_POINT_2F* point) override;
HRESULT __stdcall Setup(D2D1_POINT_2F targetPoint, double duration) override;
protected:
// Constructor / destructor
PointAnimation(D2D1_POINT_2F initialPoint);
virtual ~PointAnimation();
// Interface helper
bool QueryInterfaceHelper(const IID &iid, void **object)
{
return CastHelper<IInitializable>::CastTo(iid, this, object) ||
PointAnimation::QueryInterfaceHelper(iid, object);;
}
virtual HRESULT __stdcall Initialize() override;
private:
// Initial point. Used during SharedObject<PointAnimation>::Create method
D2D1_POINT_2F m_initialPoint;
// Animation variables
ComPtr<IUIAnimationVariable> m_pointX;
ComPtr<IUIAnimationVariable> m_pointY;
}; | [
"dbremner@gmail.com"
] | dbremner@gmail.com |
4ef2061521ab9db64230a05a1ea771b390a3165d | 2dbfb3c6b1c8718019ea9fe62c0f1c38398b0fd2 | /Apps/Common Files/HotlineFolderDownload.h | 9609caf7e922b86965cef488a945d0f70e266c20 | [] | no_license | NebuHiiEjamu/GLoarbLine | f11a76f61448b63e6fd5bf91296514171fbdf921 | 2592629bda74d700fd7cf480f1a5fc1cc67d8d58 | refs/heads/master | 2020-12-01T17:23:11.158214 | 2020-01-07T06:37:53 | 2020-01-07T06:37:53 | 230,709,766 | 0 | 0 | null | 2019-12-29T06:00:07 | 2019-12-29T06:00:06 | null | UTF-8 | C++ | false | false | 1,182 | h | /* (c)2003 Hotsprings Inc. Licensed under GPL - see LICENSE in HotlineSources diresctory */
class CMyDLItem;
class CMyDLFldr
{
public:
CMyDLFldr(TFSRefObj* inRef, CMyDLFldr *inParent, bool inDBAccess);
~CMyDLFldr();
Uint32 GetTotalItems();
Uint32 GetTotalSize();
bool HasItem(TFSRefObj* inRef);
TFSRefObj* GetFolder() { return mRef; }
CMyDLFldr *GetParent() { return mParent; }
TFSRefObj* GetNextItem(Uint8*& ioPathStart, Int16& ioMaxPathSize, Uint16& ioCount, bool *outIsFolder);
protected:
TFSRefObj* mRef;
CMyDLFldr *mParent;
Uint32 mCurrentItem;
CPtrList<CMyDLItem> mItems;
};
class CMyDLItem
{
public:
CMyDLItem(SFSListItem *inItem, CMyDLFldr *inParent, bool inDBAccess);
~CMyDLItem();
Uint32 GetTotalItems() { return mFldr ? mFldr->GetTotalItems() : mFile ? 1 : 0; }
Uint32 GetTotalSize() { return mFldr ? mFldr->GetTotalSize() : mFile ? mFile->GetSize() : 0; }
TFSRefObj* GetNextItem(Uint8*& ioPathStart, Int16& ioMaxPathSize, Uint16& ioCount, bool *outIsFolder);
bool HasItem(TFSRefObj* inRef);
protected:
TFSRefObj* mFile;
union {
CMyDLFldr *mFldr;
bool mIsDone;
};
};
| [
"cmmeurin@gmail.com"
] | cmmeurin@gmail.com |
f2a4f9dce5798f1931524112b21a196c2fce975d | a8555a9bc8c4cdc4ed994d226faeb6d0a79ac33c | /settingsdialog.cpp | 52643cf90e45556f029f7ee13d789e9869074e7c | [] | no_license | chenzilin/maple | 7725fb0f92a172db938e48be40646cb9b5e827da | 523e2d85f08cd20de358c6bbb343b4a66770d2e8 | refs/heads/master | 2021-01-16T21:44:16.989356 | 2017-05-24T05:55:07 | 2017-05-24T05:55:07 | 63,944,419 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,727 | cpp | #include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include <QLineEdit>
#include <QIntValidator>
#include <QtSerialPort/QSerialPortInfo>
QT_USE_NAMESPACE
static const char blankString[] = QT_TRANSLATE_NOOP("SettingsDialog", "N/A");
SettingsDialog::SettingsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SettingsDialog)
{
ui->setupUi(this);
intValidator = new QIntValidator(0, 4000000, this);
ui->baudRateBox->setInsertPolicy(QComboBox::NoInsert);
connect(ui->applyButton, SIGNAL(clicked()),
this, SLOT(apply()));
connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(showPortInfo(int)));
connect(ui->baudRateBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(checkCustomBaudRatePolicy(int)));
connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(checkCustomDevicePathPolicy(int)));
fillPortsParameters();
fillPortsInfo();
updateSettings();
}
SettingsDialog::~SettingsDialog()
{
delete ui;
}
SettingsDialog::Settings SettingsDialog::settings() const
{
return currentSettings;
}
void SettingsDialog::showPortInfo(int idx)
{
if (idx == -1)
return;
QStringList list = ui->serialPortInfoListBox->itemData(idx).toStringList();
ui->descriptionLabel->setText(tr("Description: %1").arg(list.count() > 1 ? list.at(1) : tr(blankString)));
ui->manufacturerLabel->setText(tr("Manufacturer: %1").arg(list.count() > 2 ? list.at(2) : tr(blankString)));
ui->serialNumberLabel->setText(tr("Serial number: %1").arg(list.count() > 3 ? list.at(3) : tr(blankString)));
ui->locationLabel->setText(tr("Location: %1").arg(list.count() > 4 ? list.at(4) : tr(blankString)));
ui->vidLabel->setText(tr("Vendor Identifier: %1").arg(list.count() > 5 ? list.at(5) : tr(blankString)));
ui->pidLabel->setText(tr("Product Identifier: %1").arg(list.count() > 6 ? list.at(6) : tr(blankString)));
}
void SettingsDialog::apply()
{
updateSettings();
hide();
}
void SettingsDialog::checkCustomBaudRatePolicy(int idx)
{
bool isCustomBaudRate = !ui->baudRateBox->itemData(idx).isValid();
ui->baudRateBox->setEditable(isCustomBaudRate);
if (isCustomBaudRate) {
ui->baudRateBox->clearEditText();
QLineEdit *edit = ui->baudRateBox->lineEdit();
edit->setValidator(intValidator);
}
}
void SettingsDialog::checkCustomDevicePathPolicy(int idx)
{
bool isCustomPath = !ui->serialPortInfoListBox->itemData(idx).isValid();
ui->serialPortInfoListBox->setEditable(isCustomPath);
if (isCustomPath)
ui->serialPortInfoListBox->clearEditText();
}
void SettingsDialog::fillPortsParameters()
{
ui->baudRateBox->addItem(QStringLiteral("9600"), QSerialPort::Baud9600);
ui->baudRateBox->addItem(QStringLiteral("19200"), QSerialPort::Baud19200);
ui->baudRateBox->addItem(QStringLiteral("38400"), QSerialPort::Baud38400);
ui->baudRateBox->addItem(QStringLiteral("115200"), QSerialPort::Baud115200);
ui->baudRateBox->addItem(tr("Custom"));
ui->baudRateBox->setCurrentIndex(3);
ui->dataBitsBox->addItem(QStringLiteral("5"), QSerialPort::Data5);
ui->dataBitsBox->addItem(QStringLiteral("6"), QSerialPort::Data6);
ui->dataBitsBox->addItem(QStringLiteral("7"), QSerialPort::Data7);
ui->dataBitsBox->addItem(QStringLiteral("8"), QSerialPort::Data8);
ui->dataBitsBox->setCurrentIndex(3);
ui->parityBox->addItem(tr("None"), QSerialPort::NoParity);
ui->parityBox->addItem(tr("Even"), QSerialPort::EvenParity);
ui->parityBox->addItem(tr("Odd"), QSerialPort::OddParity);
ui->parityBox->addItem(tr("Mark"), QSerialPort::MarkParity);
ui->parityBox->addItem(tr("Space"), QSerialPort::SpaceParity);
ui->stopBitsBox->addItem(QStringLiteral("1"), QSerialPort::OneStop);
#ifdef Q_OS_WIN
ui->stopBitsBox->addItem(tr("1.5"), QSerialPort::OneAndHalfStop);
#endif
ui->stopBitsBox->addItem(QStringLiteral("2"), QSerialPort::TwoStop);
ui->flowControlBox->addItem(tr("None"), QSerialPort::NoFlowControl);
ui->flowControlBox->addItem(tr("RTS/CTS"), QSerialPort::HardwareControl);
ui->flowControlBox->addItem(tr("XON/XOFF"), QSerialPort::SoftwareControl);
}
void SettingsDialog::fillPortsInfo()
{
ui->serialPortInfoListBox->clear();
QString description;
QString manufacturer;
QString serialNumber;
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
QStringList list;
description = info.description();
manufacturer = info.manufacturer();
serialNumber = info.serialNumber();
list << info.portName()
<< (!description.isEmpty() ? description : blankString)
<< (!manufacturer.isEmpty() ? manufacturer : blankString)
<< (!serialNumber.isEmpty() ? serialNumber : blankString)
<< info.systemLocation()
<< (info.vendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : blankString)
<< (info.productIdentifier() ? QString::number(info.productIdentifier(), 16) : blankString);
ui->serialPortInfoListBox->addItem(list.first(), list);
}
ui->serialPortInfoListBox->addItem(tr("Custom"));
}
void SettingsDialog::updateSettings()
{
currentSettings.name = ui->serialPortInfoListBox->currentText();
if (ui->baudRateBox->currentIndex() == 4) {
currentSettings.baudRate = ui->baudRateBox->currentText().toInt();
} else {
currentSettings.baudRate = static_cast<QSerialPort::BaudRate>(
ui->baudRateBox->itemData(ui->baudRateBox->currentIndex()).toInt());
}
currentSettings.stringBaudRate = QString::number(currentSettings.baudRate);
currentSettings.dataBits = static_cast<QSerialPort::DataBits>(
ui->dataBitsBox->itemData(ui->dataBitsBox->currentIndex()).toInt());
currentSettings.stringDataBits = ui->dataBitsBox->currentText();
currentSettings.parity = static_cast<QSerialPort::Parity>(
ui->parityBox->itemData(ui->parityBox->currentIndex()).toInt());
currentSettings.stringParity = ui->parityBox->currentText();
currentSettings.stopBits = static_cast<QSerialPort::StopBits>(
ui->stopBitsBox->itemData(ui->stopBitsBox->currentIndex()).toInt());
currentSettings.stringStopBits = ui->stopBitsBox->currentText();
currentSettings.flowControl = static_cast<QSerialPort::FlowControl>(
ui->flowControlBox->itemData(ui->flowControlBox->currentIndex()).toInt());
currentSettings.stringFlowControl = ui->flowControlBox->currentText();
currentSettings.localEchoEnabled = ui->localEchoCheckBox->isChecked();
}
| [
"chenzilin@autoio.cn"
] | chenzilin@autoio.cn |
3d4e7ecd20936a2157f56db448d347c452e1dc06 | 51973d4f0b22d6b82416ab4c8e36ebf79d5efede | /hpctoolkit/src/tool/hpcrun/fnbounds/fnbounds_client.c | 205e9a7ea037cb2637f5a7521856ce61b4e73f0b | [] | no_license | proywm/ccprof_hpctoolkit_deps | a18df3c3701c41216d74dca54f957e634ac7c2ed | 62d86832ecbe41b5d7a9fb5254eb2b202982b4ed | refs/heads/master | 2023-03-29T21:41:21.412066 | 2021-04-08T17:11:19 | 2021-04-08T17:11:19 | 355,986,924 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,618 | c | // -*-Mode: C++;-*- // technically C99
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2017, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
// The client side of the new fnbounds server. Hpcrun creates a pipe
// and then forks and execs hpcfnbounds in server mode (-s). The file
// descriptors are passed as command-line arguments.
//
// This file implements the client side of the pipe. For each query,
// send the file name to the server. On success, mmap space for the
// answer, read the array of addresses from the pipe and read the
// extra info in the fnbounds file header. The file 'syserv-mesg.h'
// defines the API for messages over the pipe.
//
// Notes:
// 1. Automatically restart the server if it fails.
//
// 2. Automatically restart short reads. Reading from a pipe can
// return a short answer, especially if the other side buffers the
// writes.
//
// 3. Catch SIGPIPE. Writing to a pipe after the other side has
// exited triggers a SIGPIPE and terminates the process. It's
// important to catch (or ignore) SIGPIPE in the client so that if the
// server crashes, it doesn't also kill hpcrun.
//
// 4. We don't need to lock queries to the server. Calls to
// hpcrun_syserv_query() already hold the FNBOUNDS_LOCK.
//
// 5. Dup the hpcrun log file fd onto stdout and stderr to prevent
// stray output from the server.
//
// 6. The bottom of this file has code for an interactive, stand-alone
// client for testing hpcfnbounds in server mode.
//
// Todo:
// 1. The memory leak is fixed in symtab 8.0.
//
// 2. Kill Zombies! If the server exits, it will persist as a zombie.
// That's mostly harmless, but we could clean them up with waitpid().
// But we need to do it non-blocking.
//***************************************************************************
// To build an interactive, stand-alone client for testing:
// (1) turn on this #if and (2) fetch copies of syserv-mesg.h
// and fnbounds_file_header.h.
#if 0
#define STAND_ALONE_CLIENT
#define EMSG(...)
#define TMSG(...)
#define SAMPLE_SOURCES(...) zero_fcn()
#define dup2(...) zero_fcn()
#define hpcrun_set_disabled()
#define monitor_real_fork fork
#define monitor_real_execve execve
#define monitor_sigaction(...) 0
int zero_fcn(void) { return 0; }
#endif
//***************************************************************************
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if !defined(STAND_ALONE_CLIENT)
#include <hpcfnbounds/syserv-mesg.h>
#include "client.h"
#include "disabled.h"
#include "fnbounds_file_header.h"
#include "messages.h"
#include "sample_sources_all.h"
#include "monitor.h"
#else
#include "syserv-mesg.h"
#include "fnbounds_file_header.h"
#endif
// Limit on memory use at which we restart the server in Meg.
#define SERVER_MEM_LIMIT 80
#define MIN_NUM_QUERIES 12
#define SUCCESS 0
#define FAILURE -1
#define END_OF_FILE -2
enum {
SYSERV_ACTIVE = 1,
SYSERV_INACTIVE
};
static int client_status = SYSERV_INACTIVE;
static char *server;
static int fdout = -1;
static int fdin = -1;
static pid_t my_pid;
static pid_t child_pid;
// rusage units are Kbytes.
static long mem_limit = SERVER_MEM_LIMIT * 1024;
static int num_queries = 0;
static int mem_warning = 0;
extern char **environ;
//*****************************************************************
// I/O helper functions
//*****************************************************************
// Automatically restart short reads over a pipe.
// Returns: SUCCESS, FAILURE or END_OF_FILE.
//
static int
read_all(int fd, void *buf, size_t count)
{
ssize_t ret;
size_t len;
len = 0;
while (len < count) {
ret = read(fd, ((char *) buf) + len, count - len);
if (ret < 0 && errno != EINTR) {
return FAILURE;
}
if (ret == 0) {
return END_OF_FILE;
}
if (ret > 0) {
len += ret;
}
}
return SUCCESS;
}
// Automatically restart short writes over a pipe.
// Returns: SUCCESS or FAILURE.
//
static int
write_all(int fd, const void *buf, size_t count)
{
ssize_t ret;
size_t len;
len = 0;
while (len < count) {
ret = write(fd, ((const char *) buf) + len, count - len);
if (ret < 0 && errno != EINTR) {
return FAILURE;
}
if (ret > 0) {
len += ret;
}
}
return SUCCESS;
}
// Read a single syserv mesg from incoming pipe.
// Returns: SUCCESS, FAILURE or END_OF_FILE.
//
static int
read_mesg(struct syserv_mesg *mesg)
{
int ret;
memset(mesg, 0, sizeof(*mesg));
ret = read_all(fdin, mesg, sizeof(*mesg));
if (ret == SUCCESS && mesg->magic != SYSERV_MAGIC) {
ret = FAILURE;
}
return ret;
}
// Write a single syserv mesg to outgoing pipe.
// Returns: SUCCESS or FAILURE.
//
static int
write_mesg(int32_t type, int64_t len)
{
struct syserv_mesg mesg;
mesg.magic = SYSERV_MAGIC;
mesg.type = type;
mesg.len = len;
return write_all(fdout, &mesg, sizeof(mesg));
}
//*****************************************************************
// Mmap Helper Functions
//*****************************************************************
// Returns: 'size' rounded up to a multiple of the mmap page size.
static size_t
page_align(size_t size)
{
static size_t pagesize = 0;
if (pagesize == 0) {
#if defined(_SC_PAGESIZE)
long ans = sysconf(_SC_PAGESIZE);
if (ans > 0) {
pagesize = ans;
}
#endif
if (pagesize == 0) {
pagesize = 4096;
}
}
return ((size + pagesize - 1)/pagesize) * pagesize;
}
// Returns: address of anonymous mmap() region, else MAP_FAILED on
// failure.
static void *
mmap_anon(size_t size)
{
int flags, prot;
size = page_align(size);
prot = PROT_READ | PROT_WRITE;
#if defined(MAP_ANONYMOUS)
flags = MAP_PRIVATE | MAP_ANONYMOUS;
#else
flags = MAP_PRIVATE | MAP_ANON;
#endif
return mmap(NULL, size, prot, flags, -1, 0);
}
//*****************************************************************
// Signal Handler
//*****************************************************************
// Catch and ignore SIGPIPE so that if the server crashes it doesn't
// also kill hpcrun.
//
static int
hpcrun_sigpipe_handler(int sig, siginfo_t *info, void *context)
{
TMSG(SYSTEM_SERVER, "caught SIGPIPE: system server must have exited");
return 0;
}
//*****************************************************************
// Start and Stop the System Server
//*****************************************************************
// Launch the server lazily.
// Close our file descriptors to the server. If the server is still
// alive, it will detect end-of-file on read() from the pipe.
//
static void
shutdown_server(void)
{
close(fdout);
close(fdin);
fdout = -1;
fdin = -1;
client_status = SYSERV_INACTIVE;
TMSG(SYSTEM_SERVER, "syserv shutdown");
}
// Returns: 0 on success, else -1 on failure.
static int
launch_server(void)
{
int sendfd[2], recvfd[2];
bool sampling_is_running;
pid_t pid;
// already running
if (client_status == SYSERV_ACTIVE && my_pid == getpid()) {
return 0;
}
// new process after fork
if (client_status == SYSERV_ACTIVE) {
shutdown_server();
}
if (pipe(sendfd) != 0 || pipe(recvfd) != 0) {
EMSG("SYSTEM_SERVER ERROR: syserv launch failed: pipe failed");
return -1;
}
// some sample sources need to be stopped in the parent, or else
// they cause problems in the child.
sampling_is_running = SAMPLE_SOURCES(started);
if (sampling_is_running) {
SAMPLE_SOURCES(stop);
}
pid = monitor_real_fork();
if (pid < 0) {
//
// fork failed
//
EMSG("SYSTEM_SERVER ERROR: syserv launch failed: fork failed");
return -1;
}
else if (pid == 0) {
//
// child process: disable profiling, dup the log file fd onto
// stderr and exec hpcfnbounds in server mode.
//
hpcrun_set_disabled();
close(sendfd[1]);
close(recvfd[0]);
// dup the hpcrun log file fd onto stdout and stderr.
if (dup2(messages_logfile_fd(), 1) < 0) {
warn("dup of log fd onto stdout failed");
}
if (dup2(messages_logfile_fd(), 2) < 0) {
warn("dup of log fd onto stderr failed");
}
// make the command line and exec
char *arglist[8];
char fdin_str[10], fdout_str[10];
sprintf(fdin_str, "%d", sendfd[0]);
sprintf(fdout_str, "%d", recvfd[1]);
arglist[0] = server;
arglist[1] = "-s";
arglist[2] = fdin_str;
arglist[3] = fdout_str;
arglist[4] = NULL;
monitor_real_execve(server, arglist, environ);
err(1, "hpcrun system server: exec(%s) failed", server);
}
//
// parent process: return and wait for queries.
//
close(sendfd[0]);
close(recvfd[1]);
fdout = sendfd[1];
fdin = recvfd[0];
my_pid = getpid();
child_pid = pid;
client_status = SYSERV_ACTIVE;
num_queries = 0;
mem_warning = 0;
TMSG(SYSTEM_SERVER, "syserv launch: success, server: %d", (int) child_pid);
// restart sample sources
if (sampling_is_running) {
SAMPLE_SOURCES(start);
}
return 0;
}
// Returns: 0 on success, else -1 on failure.
int
hpcrun_syserv_init(void)
{
TMSG(SYSTEM_SERVER, "syserv init");
server = getenv("HPCRUN_FNBOUNDS_CMD");
if (server == NULL) {
EMSG("SYSTEM_SERVER ERROR: unable to get HPCRUN_FNBOUNDS_CMD");
return -1;
}
// limit on server memory usage in Meg
char *str = getenv("HPCRUN_SERVER_MEMSIZE");
long size;
if (str == NULL || sscanf(str, "%ld", &size) < 1) {
size = SERVER_MEM_LIMIT;
}
mem_limit = size * 1024;
if (monitor_sigaction(SIGPIPE, &hpcrun_sigpipe_handler, 0, NULL) != 0) {
EMSG("SYSTEM_SERVER ERROR: unable to install handler for SIGPIPE");
}
return launch_server();
}
void
hpcrun_syserv_fini(void)
{
// don't tell the server to exit unless we're the process that
// started it.
if (client_status == SYSERV_ACTIVE && my_pid == getpid()) {
write_mesg(SYSERV_EXIT, 0);
}
shutdown_server();
TMSG(SYSTEM_SERVER, "syserv fini");
}
//*****************************************************************
// Query the System Server
//*****************************************************************
// Returns: pointer to array of void * and fills in the file header,
// or else NULL on error.
//
void *
hpcrun_syserv_query(const char *fname, struct fnbounds_file_header *fh)
{
struct syserv_mesg mesg;
void *addr;
if (fname == NULL || fh == NULL) {
EMSG("SYSTEM_SERVER ERROR: passed NULL pointer to %s", __func__);
return NULL;
}
if (client_status != SYSERV_ACTIVE || my_pid != getpid()) {
launch_server();
}
TMSG(SYSTEM_SERVER, "query: %s", fname);
// Send the file name length (including \0) to the server and look
// for the initial ACK. If the server has died, then make one
// attempt to restart it before giving up.
//
size_t len = strlen(fname) + 1;
if (write_mesg(SYSERV_QUERY, len) != SUCCESS
|| read_mesg(&mesg) != SUCCESS || mesg.type != SYSERV_ACK)
{
TMSG(SYSTEM_SERVER, "restart server");
shutdown_server();
launch_server();
if (write_mesg(SYSERV_QUERY, len) != SUCCESS
|| read_mesg(&mesg) != SUCCESS || mesg.type != SYSERV_ACK)
{
EMSG("SYSTEM_SERVER ERROR: unable to restart system server");
shutdown_server();
return NULL;
}
}
// Send the file name (including \0) and wait for the initial answer
// (OK or ERR). At this point, errors are pretty much fatal.
//
if (write_all(fdout, fname, len) != SUCCESS) {
EMSG("SYSTEM_SERVER ERROR: lost contact with server");
shutdown_server();
return NULL;
}
if (read_mesg(&mesg) != SUCCESS) {
EMSG("SYSTEM_SERVER ERROR: lost contact with server");
shutdown_server();
return NULL;
}
if (mesg.type != SYSERV_OK) {
EMSG("SYSTEM_SERVER ERROR: query failed: %s", fname);
return NULL;
}
// Mmap a region for the answer and read the array of addresses.
// Note: mesg.len is the number of addrs, not bytes.
//
size_t num_bytes = mesg.len * sizeof(void *);
size_t mmap_size = page_align(num_bytes);
addr = mmap_anon(mmap_size);
if (addr == MAP_FAILED) {
// Technically, we could keep the server alive in this case.
// But we would have to read all the data to stay in sync with
// the server.
EMSG("SYSTEM_SERVER ERROR: mmap failed");
shutdown_server();
return NULL;
}
if (read_all(fdin, addr, num_bytes) != SUCCESS) {
EMSG("SYSTEM_SERVER ERROR: lost contact with server");
shutdown_server();
return NULL;
}
// Read the trailing fnbounds file header.
struct syserv_fnbounds_info fnb_info;
int ret = read_all(fdin, &fnb_info, sizeof(fnb_info));
if (ret != SUCCESS || fnb_info.magic != FNBOUNDS_MAGIC) {
EMSG("SYSTEM_SERVER ERROR: lost contact with server");
shutdown_server();
return NULL;
}
if (fnb_info.status != SYSERV_OK) {
EMSG("SYSTEM_SERVER ERROR: query failed: %s", fname);
return NULL;
}
fh->num_entries = fnb_info.num_entries;
fh->reference_offset = fnb_info.reference_offset;
fh->is_relocatable = fnb_info.is_relocatable;
fh->mmap_size = mmap_size;
TMSG(SYSTEM_SERVER, "addr: %p, symbols: %ld, offset: 0x%lx, reloc: %d",
addr, (long) fh->num_entries, (long) fh->reference_offset,
(int) fh->is_relocatable);
TMSG(SYSTEM_SERVER, "server memsize: %ld Meg", fnb_info.memsize / 1024);
// Restart the server if it's done a minimum number of queries and
// has exceeded its memory limit. Issue a warning at 60%.
num_queries++;
if (!mem_warning && fnb_info.memsize > (6 * mem_limit)/10) {
EMSG("SYSTEM_SERVER: warning: memory usage: %ld Meg",
fnb_info.memsize / 1024);
mem_warning = 1;
}
if (num_queries >= MIN_NUM_QUERIES && fnb_info.memsize > mem_limit) {
EMSG("SYSTEM_SERVER: warning: memory usage: %ld Meg, restart server",
fnb_info.memsize / 1024);
shutdown_server();
}
return addr;
}
//*****************************************************************
// Stand Alone Client
//*****************************************************************
#ifdef STAND_ALONE_CLIENT
#define BUF_SIZE 2000
static void
query_loop(void)
{
struct fnbounds_file_header fnb_hdr;
char fname[BUF_SIZE];
void **addr;
long k;
for (;;) {
printf("\nfnbounds> ");
if (fgets(fname, BUF_SIZE, stdin) == NULL) {
break;
}
char *new_line = strchr(fname, '\n');
if (new_line != NULL) {
*new_line = 0;
}
addr = (void **) hpcrun_syserv_query(fname, &fnb_hdr);
if (addr == NULL) {
printf("error\n");
}
else {
for (k = 0; k < fnb_hdr.num_entries; k++) {
printf(" %p\n", addr[k]);
}
printf("num symbols = %ld, offset = 0x%lx, reloc = %d\n",
fnb_hdr.num_entries, fnb_hdr.reference_offset,
fnb_hdr.is_relocatable);
if (munmap(addr, fnb_hdr.mmap_size) != 0) {
err(1, "munmap failed");
}
}
}
}
int
main(int argc, char *argv[])
{
struct sigaction act;
if (argc < 2) {
errx(1, "usage: client /path/to/fnbounds");
}
server = argv[1];
memset(&act, 0, sizeof(act));
act.sa_handler = SIG_IGN;
sigemptyset(&act.sa_mask);
if (sigaction(SIGPIPE, &act, NULL) != 0) {
err(1, "sigaction failed on SIGPIPE");
}
if (launch_server() != 0) {
errx(1, "fnbounds server failed");
}
printf("server: %s\n", server);
printf("parent: %d, child: %d\n", my_pid, child_pid);
printf("connected\n");
query_loop();
write_mesg(SYSERV_EXIT, 0);
printf("done\n");
return 0;
}
#endif // STAND_ALONE_CLIENT
| [
"proy@email.wm.edu"
] | proy@email.wm.edu |
e4e30b72944a3d8ee234c25bc7d71b52a895a765 | 5249bfba86de6e17dd6e341b5fd556dec79b6b5a | /P_main_ZUMO/speedometer_and_battery_ZUMO_h.ino | 8b0c8936ac9369d847827516ff6106c0ca670cec | [] | no_license | Epsilonium/team_pro_zumo | ebea2c9f2794a6d6f65e9b4bf80db3c7268bad51 | 9c86006cdc3d56906826bf04ce35c06a2effeeb4 | refs/heads/master | 2022-04-20T17:27:40.756644 | 2020-04-20T05:14:32 | 2020-04-20T05:14:32 | 257,632,979 | 0 | 0 | null | 2020-04-21T15:07:36 | 2020-04-21T15:07:36 | null | UTF-8 | C++ | false | false | 12,669 | ino | /*
Author: Torje
Revidert: Line
Denne koden inneholder funksjoner for Zumo.
Disse funksjoner skal kjøres sammen som beskrevet. De funksjoner "spedoometer()" består av bør ikke kjøres individuelt.
Funksjonen skal loope i main og kjøres i hver iterasjon. Hvis det mer mye delay blir målingene mindre presise.
Denne funksjonen tar vare på:
- Hastigheten, meter/sek. Oppdatert hvert sekund.
- Høyeste hastighet.
- Total distanse kjørt siden programmet startet Oppdateres hvert sekund.
- gjennomsnittshastighet, oppdatert hvert 60. sekund
- Distanse kjørt hvert 60. sekund
- Antall sekunder bilen har kjørt over 70% av maks hastighet, utregnes hvert 60. sekund.
- Batteri forbrukt
- Batteri gjenstående
- Antall ladesykluser på batteriet
Programmet begrenser også batterikapasiteten utfra antall ladinger og overlading, slik som med et ekte batteri.
Todo:
Slå sammen med alle andre funksjoner for Zumo, og lag bibliotek
*/
//--------Global-----
const float SEVENTY_LIMIT = 0.462; //Grensen for 70% av bilens maxhastighet. (maks hastighet er 0.66 m/s)
float speedSixtyFinal; //Verdien tas vare på for å printe til BLYNK, selv om en ny måling blir gjennomført
float distanceSixtyFinal; //Verdien tas vare på for å printe til BLYNK, selv om en ny måling blir gjennomført
float distanceTotal = 0; //Distansen kjørt, oppgitt i meter
float speedSixty; //Mellomregningsmål for å beregne gjennomsnittshastighet
int numSixty = 0; //Teller for hvor mange summer speedSixty består av. Brukes for å regne ut gjennomsnittet.
float avgSpeedSixty; //Gjennomsnittshastighet hvert 60. sekund
float speedo; //Utregnet meter/sekund. Faktiske speedometerverdien.
float measuredMaxSpeed = 0; //Historisk mål for høyeste hastighet
float speedLeft; //Encoderverdi
float speedRight; //Encoderverdi
unsigned long movementTime; //Tiden for en bevegelse. Brukes for å regne ut hastigheten.
bool newSpeedo = false; //Brukes for å si om det finnes en ny verdi å skrive til ESP
bool newDistanceTotal = false; //Brukes for å si om det finnes en ny verdi å skrive til ESP
bool newSpeedSixtyFinal = false; //Brukes for å si om det finnes en ny verdi å skrive til ESP
bool newDistanceSixtyFinal = false; //Brukes for å si om det finnes en ny verdi å skrive til ESP
bool newMaxSpeed = false; //Brukes for å si om det finnes en ny verdi å skrive til ESP
bool newBatteryPercent = false; //Brukes for å si om det finnes en ny verdi å skrive til ESP
bool lowBatteryToESP = false; //Brukes for å si om det finnes en ny verdi å skrive til ESP
bool toggleLED = false; //Toggel for lavt batterivarsel-led
//float batteryChargeCycles = 0; //Antall totale ladesykluser for batteriet. Brukes også til å begrense toppverdien for batteriet. Flere sykluser gir lavere batterikapasietet.
int batteryPercent; //Batterinivå i prosent.
unsigned long currentMillis;
bool oneCalc = false; //For å sjekke om man er i en beregning av 1 sekunder
unsigned long oneCalcTime = 0; //Timestamp for start av en måling av 1 sekund
//-----------------------Speedometer------------------
void speedometer() {
oneCheck(); //Oppdaterer hastighet hvert sekund
seventyCheck(); //Sjekker om man kjører over 70% eller mer av max, og lagrer tiden
sixtyCheck(); //Sjekker om der har gått 60 sekunder og regner ut gj.snitts hastighet og distanse kjørt på den tiden
batteryCheck(); //Regner ut batteri brukt, eller oppladet
batteryHealth(); //Gir beskjed om service eller bytte av batteri
writeToESP(); //Skriver til ESP som deretter oppdaterer blynk
}
//-----------------------oneCheck--------------------
void oneCheck() {
if (oneCalc == false) { //Sjekke om man er i en "sekundtelling" eller ikke. Starter en måling
oneCalcTime = millis(); //Timestamp
encoders.getCountsAndResetLeft(); //Resetter encoders i starten av en måling
encoders.getCountsAndResetRight(); //Resetter encoders i starten av en måling
oneCalc = true; //Markerer at man er i en måling
}
if (millis() - oneCalcTime >= 1000) { //Når det har gått ett sekund siden sist måling
movementTime = millis() - oneCalcTime; //Regner ut tid for målingen av bevegelsen.
speedLeft = encoders.getCountsLeft(); //Henter encoderverdiene.
speedRight = encoders.getCountsRight(); //Henter encoderverdiene.
speedCheck(); //Regner ut farten under sekundet, og oppdaterer evt. ny maks.hastighet
oneCalc = false; //Ferdig med en hastighetsmåling.
speedSixty += speedo; //Mellomregning for å regne ut gjennomsnittshastighet hvert 60. sekund. Tar med summen av alle fartsberegninger.
numSixty++; //Teller for antall summer i speedSixty. Brukes for å senere regne ut gjennomsnittet av dem.
distanceTotal += (speedo * (movementTime / 1000)); //Nullstilles aldri. Historisk mål for total distanse kjørt, målt i meter
newDistanceTotal = true; //Markerer at en ny verdi er tilgjengelig for å printe til Blynk
}
}
//-----------------------SpeedCheck------------------
void speedCheck() { //Brukes til å beregne hastigheten til gjennomsnittsforflyttningen til hjulene.
const int SPEED_CONVERSION = 7750; // omregning fra dekodertellinger til m.
float combinedSpeed = (speedLeft + speedRight) / 2;
speedo = ((combinedSpeed / SPEED_CONVERSION) / movementTime) * 1000; // hastighet for bevegelsen, hensyntatt konvertering fra "dekodertellinger per millisekund" til "meter/sek"
if (speedo <= 0) { //Hvis man snurrer om sin egen akse har man ikke fart, og det skal ikke påvirke snittfarta.
speedo = 0;
numSixty--;
}
if (speedo > measuredMaxSpeed) { //Historisk mål for høyeste hastighet
measuredMaxSpeed = speedo;
newMaxSpeed = true; //Markerer at ny verdi er klar til å sendes til Blynk
}
newSpeedo = true; //Markerer at et ny speedometerverdi er oppdatert, så kan den sendes til ESP
}
//-----------------------sixtyCheck-----------------
unsigned long seventyTime; //Total tid over 70% av max
float distanceSixty; //Total distanse innen 60 sekunder
bool sixtyCalc = false; // For å sjekke om man er i en beregning av 60 sekunder
unsigned long sixtyCalcTime; //Timestamp for start av en måling av 1 sekund
void sixtyCheck() {
if (sixtyCalc == false) { //Starter på en ny telling dersom en ikke eksisterer
sixtyCalcTime = millis(); //Timestamp ved starten av en telling
distanceSixty = distanceTotal; //Midlertidig verdi for beregning av total distanse over 60 sekunder
sixtyCalc = true; //Bool for at timestamp ikke skal sjekke igjen
}
if (millis() - sixtyCalcTime >= 60000) { //Sjekker om det har gått 60 sekunder.
distanceSixty = distanceTotal - distanceSixty; //Regner total distanse siden starten av 60-sekundersperioden, basert på differansen mellom den totale distansen over 60 sekunder.
avgSpeedSixty = speedSixty / numSixty; //Gjennomsnittshastigheten over 60 sekunder.
//Tar vare på verdier før man nullstiller og gjør klar for en ny måling
speedSixtyFinal = avgSpeedSixty;
distanceSixtyFinal = distanceSixty;
//nullstiller tellere for å gjøre klart for en ny måling
speedSixty = 0;
distanceSixty = 0;
seventyTime = 0;
numSixty = 0;
sixtyCalc = false; //Bool for at ny timestamp skal kunne gjennomføres (Starten av denne funksjonen)
newSpeedSixtyFinal = true; //Markerer at nye verdier er klare for å sendes til BLYNK
newDistanceSixtyFinal = true; //Markerer at nye verdier er klare for å sendes til BLYNK
//EEPROM.write(0, batteryChargeCycles); //Lagrer antall batterisykluser i EEPROM en gang i minuttet. Gjør dette sjeldent for å ikke "slite ut" minnet, som her levetid på ca 100,000 skrive/slette-runder
}
}
//----------------seventyCheck()-----------
// Funksjonen beregner tiden man er over 70% av max hastighet, etter en terskel man har lagt inn.
bool seventyCalc = false; //For å sjekke når bilen kjører over 70% av maxfart
unsigned long seventyCalcTime; //Timestamp for start av periode med kjøring over 70% av max
void seventyCheck() {
if (speedo >= SEVENTY_LIMIT && seventyCalc == false) {
seventyCalc = true;
seventyCalcTime = millis();
}
if (speedo < SEVENTY_LIMIT && seventyCalc == true) {
seventyCalc = false;
seventyTime += millis() - seventyCalcTime;
}
}
//--------------batteryCheck---------
float charged; //Teller hvor mye som lades
int batteryCapasity = BATTERY_MAX;
bool lowBattery = false;
bool batteryServiceNeeded = false;
bool prevServiceState = false;
bool batteryChangeNeeded = false;
bool prevChangeState = false;
void batteryCheck() {
if (newSpeedo == true) {
batteryLeft -= (speedo * (movementTime / 1000)); //Samme som distansen, men med egen teller. Oppgitt i meter.
newBatteryPercent = true;
}
if (newCharge == true) {
batteryLeft += charged;
batteryChargedTotal += charged; //Teller hvor mye batteriet totalt har blitt oppladet. "Overlading" tærer også på batteriet, som i virkeligheten (Altså om man forsøker å lade over 100%)
batteryChargeCycles = batteryChargedTotal / (BATTERY_MAX - (BATTERY_MAX * (ceil(batteryChargeCycles)) / 10)); //Sjekker hvor mye batteriet har blitt oppladet totalt siden programmet startet
batteryLeft = constrain(batteryLeft, 0, BATTERY_MAX - (BATTERY_MAX * (ceil(batteryChargeCycles)) / 10));
Serial.print("batteryChargeCycles: ");
Serial.println(batteryChargeCycles);
newCharge = false;
newBatteryPercent = true;
}
batteryCapasity = constrain(batteryCapasity, 0, BATTERY_MAX - (BATTERY_MAX * (ceil(batteryChargeCycles)) / 10)); //Begrenser maks batterikapasitet med 10% for hver hele ladesyklus.
batteryPercent = batteryLeft / batteryCapasity * 100;
checkIfLowBattery();
}
void chargeBattery() {
/*Kjøres når "charge"-knappen i blynk blir holdt inne, og lagrer antall sekunder knappen er holdt inne for å regne ut ladningsprosent*/
charged = (ceil((millis() - chargeTime) / 1000)) * 10; //Runder opp til nærmeste antall sek kjørt. 1 sek = 10% batteri oppladet
charged = constrain(charged, 0, BATTERY_MAX - (BATTERY_MAX * (ceil(batteryChargeCycles)) / 10));
Serial.print("charged: ");
Serial.println(charged);
newCharge = true;
}
void checkIfLowBattery() {
if (batteryPercent <= 95 && lowBattery == false) {
lowBattery = true;
lowBatteryToESP = true;
}
if (batteryPercent > 95 && lowBattery == true) {
lowBattery = false;
lowBatteryToESP = true;
}
}
void batteryHealth() {
if (batteryChargeCycles >= 2 && batteryChargeCycles < 3 && batteryServiceNeeded == false) {
batteryServiceNeeded = true;
Serial.println("SERVICE NEEDED");
}
if (batteryChargeCycles >= 3 && batteryChangeNeeded == false) {
batteryChangeNeeded = true;
Serial.println("CHANGE NEEDED");
}
}
//-----------------writeToESP----------
//Skriver alle nye verdier til ESP
void writeToESP() {
if (newSpeedo == true) {
Serial1.write(1);
delay(2);
Serial1.print(float(speedo));
Serial.print("BLYNK speedo: ");
Serial.println(float(speedo));
newSpeedo = false;
}
if (newDistanceTotal == true) {
Serial1.write(2);
delay(2);
Serial1.print(float(distanceTotal));
Serial.print("BLYNK distanceTotal: ");
Serial.println(float(distanceTotal));
newDistanceTotal = false;
}
if (newSpeedSixtyFinal == true) {
Serial1.write(3);
delay(2);
Serial1.print(float(speedSixtyFinal));
Serial.print("BLYNK speedSixtyFinal: ");
Serial.println(speedSixtyFinal);
newSpeedSixtyFinal = false;
}
if (newDistanceSixtyFinal == true) {
Serial1.write(4);
delay(2);
Serial1.print(float(distanceSixtyFinal));
Serial.print("BLYNK distanceSixtyFinal: ");
Serial.println(float(distanceSixtyFinal));
newDistanceSixtyFinal = false;
}
if (newMaxSpeed == true) {
Serial1.write(5);
delay(2);
Serial1.write(int(measuredMaxSpeed));
Serial.print("BLYNK MAXSPEED: ");
Serial.println(measuredMaxSpeed);
newMaxSpeed = false;
}
if (newBatteryPercent == true) {
Serial1.write(6);
delay(2);
Serial1.write(batteryPercent);
Serial.print("BLYNK batteryPercent: ");
Serial.println(batteryPercent);
newBatteryPercent = false;
}
if (lowBatteryToESP == true) {
Serial1.write(7);
delay(2);
toggleLED = !toggleLED;
Serial1.write(toggleLED);
Serial.print("BLYNK update low battery LED: ");
Serial.println(toggleLED);
lowBatteryToESP = false;
}
}
| [
"63612725+linehoyb@users.noreply.github.com"
] | 63612725+linehoyb@users.noreply.github.com |
85e4a9403aa44f39cd82986a68d9c0730abbf91d | 1f3a328c6acdbff25adb296eed3fda328d49f55f | /src/kernel.cpp | 8787b0ae0672a5e83b378f1530c5c926285ba9f7 | [
"MIT"
] | permissive | ariacoin-project/ariacoin | 2124e10249198c637051f5fd6242e06870923a9e | 4fed7fed320f975b179ee66ae5163fbdd34a4f2d | refs/heads/main | 2023-07-03T14:31:40.296067 | 2021-08-10T18:49:39 | 2021-08-10T18:49:39 | 394,699,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,365 | cpp | /* @flow */
// Copyright (c) 2012-2013 The PPCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include <boost/lexical_cast.hpp>
#include "db.h"
#include "kernel.h"
#include "script/interpreter.h"
#include "timedata.h"
#include "util.h"
using namespace std;
bool fTestNet = false; //Params().NetworkID() == CBaseChainParams::TESTNET;
// Modifier interval: time to elapse before new modifier is computed
// Set to 3-hour for production network and 20-minute for test network
unsigned int nModifierInterval;
int nStakeTargetSpacing = 60;
unsigned int getIntervalVersion(bool fTestNet)
{
if (fTestNet)
return MODIFIER_INTERVAL_TESTNET;
else
return MODIFIER_INTERVAL;
}
// Hard checkpoints of stake modifiers to ensure they are deterministic
static std::map<int, unsigned int> mapStakeModifierCheckpoints =
boost::assign::map_list_of(0, 0xfd11f4e7u);
// Get time weight
int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd)
{
return nIntervalEnd - nIntervalBeginning - nStakeMinAge;
}
// Get the last stake modifier and its generation time from a given block
static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime)
{
if (!pindex)
return error("GetLastStakeModifier: null pindex");
while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
pindex = pindex->pprev;
if (!pindex->GeneratedStakeModifier())
return error("GetLastStakeModifier: no generation at genesis block");
nStakeModifier = pindex->nStakeModifier;
nModifierTime = pindex->GetBlockTime();
return true;
}
// Get selection interval section (in seconds)
static int64_t GetStakeModifierSelectionIntervalSection(int nSection)
{
assert(nSection >= 0 && nSection < 64);
int64_t a = getIntervalVersion(fTestNet) * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)));
return a;
}
// Get stake modifier selection interval (in seconds)
static int64_t GetStakeModifierSelectionInterval()
{
int64_t nSelectionInterval = 0;
for (int nSection = 0; nSection < 64; nSection++) {
nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
}
return nSelectionInterval;
}
// select a block from the candidate blocks in vSortedByTimestamp, excluding
// already selected blocks in vSelectedBlocks, and with timestamp up to
// nSelectionIntervalStop.
static bool SelectBlockFromCandidates(
vector<pair<int64_t, uint256> >& vSortedByTimestamp,
map<uint256, const CBlockIndex*>& mapSelectedBlocks,
int64_t nSelectionIntervalStop,
uint64_t nStakeModifierPrev,
const CBlockIndex** pindexSelected)
{
bool fModifierV2 = false;
bool fFirstRun = true;
bool fSelected = false;
uint256 hashBest = 0;
*pindexSelected = (const CBlockIndex*)0;
BOOST_FOREACH (const PAIRTYPE(int64_t, uint256) & item, vSortedByTimestamp) {
if (!mapBlockIndex.count(item.second))
return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
const CBlockIndex* pindex = mapBlockIndex[item.second];
if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
break;
//if the lowest block height (vSortedByTimestamp[0]) is >= switch height, use new modifier calc
if (fFirstRun){
fModifierV2 = pindex->nHeight >= Params().ModifierUpgradeBlock();
fFirstRun = false;
}
if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
continue;
// compute the selection hash by hashing an input that is unique to that block
uint256 hashProof;
if(fModifierV2)
hashProof = pindex->GetBlockHash();
else
hashProof = pindex->IsProofOfStake() ? 0 : pindex->GetBlockHash();
CDataStream ss(SER_GETHASH, 0);
ss << hashProof << nStakeModifierPrev;
uint256 hashSelection = Hash(ss.begin(), ss.end());
// the selection hash is divided by 2**32 so that proof-of-stake block
// is always favored over proof-of-work block. this is to preserve
// the energy efficiency property
if (pindex->IsProofOfStake())
hashSelection >>= 32;
if (fSelected && hashSelection < hashBest) {
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
} else if (!fSelected) {
fSelected = true;
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
}
}
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
return fSelected;
}
// Stake Modifier (hash modifier of proof-of-stake):
// The purpose of stake modifier is to prevent a txout (coin) owner from
// computing future proof-of-stake generated by this txout at the time
// of transaction confirmation. To meet kernel protocol, the txout
// must hash with a future stake modifier to generate the proof.
// Stake modifier consists of bits each of which is contributed from a
// selected block of a given block group in the past.
// The selection of a block is based on a hash of the block's proof-hash and
// the previous stake modifier.
// Stake modifier is recomputed at a fixed time interval instead of every
// block. This is to make it difficult for an attacker to gain control of
// additional bits in the stake modifier, even after generating a chain of
// blocks.
bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier)
{
nStakeModifier = 0;
fGeneratedStakeModifier = false;
if (!pindexPrev) {
fGeneratedStakeModifier = true;
return true; // genesis block's modifier is 0
}
if (pindexPrev->nHeight == 0) {
//Give a stake modifier to the first block
fGeneratedStakeModifier = true;
nStakeModifier = uint64_t("stakemodifier");
return true;
}
// First find current stake modifier and its generation block time
// if it's not old enough, return the same stake modifier
int64_t nModifierTime = 0;
if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
return error("ComputeNextStakeModifier: unable to get last modifier");
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: prev modifier= %s time=%s\n", boost::lexical_cast<std::string>(nStakeModifier).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nModifierTime).c_str());
if (nModifierTime / getIntervalVersion(fTestNet) >= pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet))
return true;
// Sort candidate blocks by timestamp
vector<pair<int64_t, uint256> > vSortedByTimestamp;
vSortedByTimestamp.reserve(64 * getIntervalVersion(fTestNet) / nStakeTargetSpacing);
int64_t nSelectionInterval = GetStakeModifierSelectionInterval();
int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet)) * getIntervalVersion(fTestNet) - nSelectionInterval;
const CBlockIndex* pindex = pindexPrev;
while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) {
vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
pindex = pindex->pprev;
}
int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
// Select 64 blocks from candidate blocks to generate stake modifier
uint64_t nStakeModifierNew = 0;
int64_t nSelectionIntervalStop = nSelectionIntervalStart;
map<uint256, const CBlockIndex*> mapSelectedBlocks;
for (int nRound = 0; nRound < min(64, (int)vSortedByTimestamp.size()); nRound++) {
// add an interval section to the current selection round
nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
// select a block from the candidates of current round
if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
// write the entropy bit of the selected block
nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
// add the selected block from candidates to selected list
mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
if (fDebug || GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
nRound, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
}
// Print selection map for visualization of the selected blocks
if (fDebug || GetBoolArg("-printstakemodifier", false)) {
string strSelectionMap = "";
// '-' indicates proof-of-work blocks not selected
strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
pindex = pindexPrev;
while (pindex && pindex->nHeight >= nHeightFirstCandidate) {
// '=' indicates proof-of-stake blocks not selected
if (pindex->IsProofOfStake())
strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
pindex = pindex->pprev;
}
BOOST_FOREACH (const PAIRTYPE(uint256, const CBlockIndex*) & item, mapSelectedBlocks) {
// 'S' indicates selected proof-of-stake blocks
// 'W' indicates selected proof-of-work blocks
strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake() ? "S" : "W");
}
LogPrintf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
}
if (fDebug || GetBoolArg("-printstakemodifier", false)) {
LogPrintf("ComputeNextStakeModifier: new modifier=%s time=%s\n", boost::lexical_cast<std::string>(nStakeModifierNew).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexPrev->GetBlockTime()).c_str());
}
nStakeModifier = nStakeModifierNew;
fGeneratedStakeModifier = true;
return true;
}
// The stake modifier used to hash for a stake kernel is chosen as the stake
// modifier about a selection interval later than the coin generating the kernel
bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
{
nStakeModifier = 0;
if (!mapBlockIndex.count(hashBlockFrom))
return error("GetKernelStakeModifier() : block not indexed");
const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
nStakeModifierHeight = pindexFrom->nHeight;
nStakeModifierTime = pindexFrom->GetBlockTime();
int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
const CBlockIndex* pindex = pindexFrom;
CBlockIndex* pindexNext = chainActive[pindexFrom->nHeight + 1];
// loop to find the stake modifier later by a selection interval
while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) {
if (!pindexNext) {
// Should never happen
return error("Null pindexNext\n");
}
pindex = pindexNext;
pindexNext = chainActive[pindexNext->nHeight + 1];
if (pindex->GeneratedStakeModifier()) {
nStakeModifierHeight = pindex->nHeight;
nStakeModifierTime = pindex->GetBlockTime();
}
}
nStakeModifier = pindex->nStakeModifier;
return true;
}
uint256 stakeHash(unsigned int nTimeTx, CDataStream ss, unsigned int prevoutIndex, uint256 prevoutHash, unsigned int nTimeBlockFrom)
{
//ariacoin will hash in the transaction hash and the index number in order to make sure each hash is unique
ss << nTimeBlockFrom << prevoutIndex << prevoutHash << nTimeTx;
return Hash(ss.begin(), ss.end());
}
//test hash vs target
bool stakeTargetHit(uint256 hashProofOfStake, int64_t nValueIn, uint256 bnTargetPerCoinDay)
{
//get the stake weight - weight is equal to coin amount
uint256 bnCoinDayWeight = uint256(nValueIn) / 100;
// Now check if proof-of-stake hash meets target protocol
return (uint256(hashProofOfStake) < bnCoinDayWeight * bnTargetPerCoinDay);
}
//instead of looping outside and reinitializing variables many times, we will give a nTimeTx and also search interval so that we can do all the hashing here
bool CheckStakeKernelHash(unsigned int nBits, const CBlock blockFrom, const CTransaction txPrev, const COutPoint prevout, unsigned int& nTimeTx, unsigned int nHashDrift, bool fCheck, uint256& hashProofOfStake, bool fPrintProofOfStake)
{
//assign new variables to make it easier to read
int64_t nValueIn = txPrev.vout[prevout.n].nValue;
unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
if (nTimeTx < nTimeBlockFrom) // Transaction timestamp violation
return error("CheckStakeKernelHash() : nTime violation");
if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
return error("CheckStakeKernelHash() : min age violation - nTimeBlockFrom=%d nStakeMinAge=%d nTimeTx=%d", nTimeBlockFrom, nStakeMinAge, nTimeTx);
//grab difficulty
uint256 bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
//grab stake modifier
uint64_t nStakeModifier = 0;
int nStakeModifierHeight = 0;
int64_t nStakeModifierTime = 0;
if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) {
LogPrintf("CheckStakeKernelHash(): failed to get kernel stake modifier \n");
return false;
}
//create data stream once instead of repeating it in the loop
CDataStream ss(SER_GETHASH, 0);
ss << nStakeModifier;
//if wallet is simply checking to make sure a hash is valid
if (fCheck) {
hashProofOfStake = stakeHash(nTimeTx, ss, prevout.n, prevout.hash, nTimeBlockFrom);
return stakeTargetHit(hashProofOfStake, nValueIn, bnTargetPerCoinDay);
}
bool fSuccess = false;
unsigned int nTryTime = 0;
unsigned int i;
for (i = 0; i < (nHashDrift); i++) //iterate the hashing
{
//hash this iteration
nTryTime = nTimeTx + nHashDrift - i;
hashProofOfStake = stakeHash(nTryTime, ss, prevout.n, prevout.hash, nTimeBlockFrom);
// if stake hash does not meet the target then continue to next iteration
if (!stakeTargetHit(hashProofOfStake, nValueIn, bnTargetPerCoinDay))
continue;
fSuccess = true; // if we make it this far then we have successfully created a stake hash
nTimeTx = nTryTime;
if (fDebug || fPrintProofOfStake) {
LogPrintf("CheckStakeKernelHash() : using modifier %s at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
boost::lexical_cast<std::string>(nStakeModifier).c_str(), nStakeModifierHeight,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nStakeModifierTime).c_str(),
mapBlockIndex[blockFrom.GetHash()]->nHeight,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", blockFrom.GetBlockTime()).c_str());
LogPrintf("CheckStakeKernelHash() : pass protocol=%s modifier=%s nTimeBlockFrom=%u prevoutHash=%s nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
"0.3",
boost::lexical_cast<std::string>(nStakeModifier).c_str(),
nTimeBlockFrom, prevout.hash.ToString().c_str(), nTimeBlockFrom, prevout.n, nTryTime,
hashProofOfStake.ToString().c_str());
}
break;
}
mapHashedBlocks.clear();
mapHashedBlocks[chainActive.Tip()->nHeight] = GetTime(); //store a time stamp of when we last hashed on this block
return fSuccess;
}
// Check kernel hash target and coinstake signature
bool CheckProofOfStake(const CBlock block, uint256& hashProofOfStake)
{
const CTransaction tx = block.vtx[1];
if (!tx.IsCoinStake())
return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
// Kernel (input 0) must match the stake hash target per coin age (nBits)
const CTxIn& txin = tx.vin[0];
// First try finding the previous transaction in database
uint256 hashBlock;
CTransaction txPrev;
if (!GetTransaction(txin.prevout.hash, txPrev, hashBlock, true))
return error("CheckProofOfStake() : INFO: read txPrev failed");
//verify signature and script
if (!VerifyScript(txin.scriptSig, txPrev.vout[txin.prevout.n].scriptPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&tx, 0)))
return error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str());
CBlockIndex* pindex = NULL;
BlockMap::iterator it = mapBlockIndex.find(hashBlock);
if (it != mapBlockIndex.end())
pindex = it->second;
else
return error("CheckProofOfStake() : read block failed");
// Read block header
CBlock blockprev;
if (!ReadBlockFromDisk(blockprev, pindex->GetBlockPos()))
return error("CheckProofOfStake(): INFO: failed to find block");
unsigned int nInterval = 0;
unsigned int nTime = block.nTime;
if (!CheckStakeKernelHash(block.nBits, blockprev, txPrev, txin.prevout, nTime, nInterval, true, hashProofOfStake, fDebug))
return error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s \n", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str()); // may occur during initial download or if behind on block chain sync
return true;
}
// Check whether the coinstake timestamp meets protocol
bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx)
{
// v0.3 protocol
return (nTimeBlock == nTimeTx);
}
// Get stake modifier checksum
unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
{
assert(pindex->pprev || pindex->GetBlockHash() == Params().HashGenesisBlock());
// Hash previous checksum with flags, hashProofOfStake and nStakeModifier
CDataStream ss(SER_GETHASH, 0);
if (pindex->pprev)
ss << pindex->pprev->nStakeModifierChecksum;
ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
uint256 hashChecksum = Hash(ss.begin(), ss.end());
hashChecksum >>= (256 - 32);
return hashChecksum.Get64();
}
// Check stake modifier hard checkpoints
bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (mapStakeModifierCheckpoints.count(nHeight)) {
return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];
}
return true;
}
| [
"like2play@gmail.com"
] | like2play@gmail.com |
35a1bc99e845ff8cea85d4f3e3f1025ca4186f1c | 9971b5d7b41bef496ce1757bacba5aee2f65218c | /task5/tests/00-aplusb/test.cpp | 74136cf852a8631afcda0afc3e48749aaee52ced | [] | no_license | amsilevich/tp_homework | 648185fba8671cc25a361c16677f2483a8f2e988 | 992345fe15f13d53e7e60fe16f967ae6b1f31719 | refs/heads/master | 2022-07-04T18:30:41.729192 | 2020-05-17T20:01:25 | 2020-05-17T20:01:25 | 258,572,668 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66 | cpp | #include <gtest/gtest.h>
TEST(A, B) {
ASSERT_EQ(6, 3 + 3);
}
| [
"amsilevich@gmail.com"
] | amsilevich@gmail.com |
ba91f0ef2abbe482ee34c6288ca3f2a232010112 | cf47614d4c08f3e6e5abe82d041d53b50167cac8 | /CS101_Autumn2020-21/Fibonacci/689_fibonacci.cpp | 43d4a43b668ef8fe894d3f1737bdb6be4d0a29ba | [] | no_license | krishna-raj007/BodhiTree-Annotation | 492d782dffe3744740f48c4c7e6bbf2ee2c0febd | 28a6467038bac7710c4b3e3860a369ca0a6e31bf | refs/heads/master | 2023-02-28T18:23:05.880438 | 2021-02-07T17:55:33 | 2021-02-07T17:55:33 | 299,254,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | #include<simplecpp>
main_program{
long int n, k1=0,k2=1,z,nextTerm=0;
cin>>n>>z;
for(int i=1; i<=n; i++)
{
if(i==1)
{
cout<<k1<<endl;
continue;
}
if(i==2){
cout<<k2<<endl;
continue;
}
nextTerm=(k1+k2)%z;
k1=k2%z;
k2=nextTerm%z;
cout<<nextTerm<<endl;
}
}
| [
"krishna_raj007@yahoo.in"
] | krishna_raj007@yahoo.in |
5738c616b7bc6bb8a5415ba057a5c202a881669c | e73bd3a4d6aec855aaa7f9df65844e8f3bcdc00c | /test/Pot_Test/Potentiometer.h | a81cfc344be2a043e355a3b7d927bfd07957da13 | [] | no_license | linenoise/synferno | da302ed5100cbd0e6aa5d71b56b15e564f0488f4 | 43dac651fbef539d5bda6db3cd7b39433ebf82dd | refs/heads/master | 2021-01-18T22:27:54.314159 | 2018-08-15T21:57:37 | 2018-08-15T21:57:37 | 87,055,793 | 0 | 1 | null | 2018-08-15T21:57:38 | 2017-04-03T09:01:30 | C | UTF-8 | C++ | false | false | 893 | h | #ifndef Potentiometer_h
#define Potentiometer_h
#include <Arduino.h>
#include <Metro.h>
#define POT_PIN1 A0 // A0, specifically
#define POT_PIN2 A1
#define POT_PIN3 A2
#define POT_PIN4 A3
// ~2230 updates per second with FASTADC 0
// ~6220 updates per second with FASTADC 1
// See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1208715493/11
#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
class Potentiometer{
public:
void begin(byte pin, byte sectors=0, word minimum=0, word maximum=1023, byte smoothing=10);
boolean update();
word getValue();
byte getSector();
private:
byte pin, smoothing, sectors;
word maximum, minimum;
unsigned long currentValue;
byte currentSector;
};
#endif
| [
"magister@the-magister.com"
] | magister@the-magister.com |
558df6fec115d7989677e70bb0eb193cb0a65825 | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /components/gwp_asan/client/guarded_page_allocator.cc | b173033550de09c2c4543a43db74953e54363290 | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 7,372 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/gwp_asan/client/guarded_page_allocator.h"
#include "base/bits.h"
#include "base/no_destructor.h"
#include "base/process/process_metrics.h"
#include "base/rand_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "build/build_config.h"
#include "components/crash/core/common/crash_key.h"
#include "components/gwp_asan/common/allocator_state.h"
#include "components/gwp_asan/common/crash_key_name.h"
using base::debug::StackTrace;
namespace gwp_asan {
namespace internal {
// TODO: Delete out-of-line constexpr defininitons once C++17 is in use.
constexpr size_t GuardedPageAllocator::kGpaAllocAlignment;
GuardedPageAllocator::GuardedPageAllocator() {}
void GuardedPageAllocator::Init(size_t num_pages) {
CHECK_GT(num_pages, 0U);
CHECK_LE(num_pages, AllocatorState::kGpaMaxPages);
state_.num_pages = num_pages;
state_.page_size = base::GetPageSize();
CHECK(MapPages());
{
// Obtain this lock exclusively to satisfy the thread-safety annotations,
// there should be no risk of a race here.
base::AutoLock lock(lock_);
free_pages_ = (state_.num_pages == AllocatorState::kGpaMaxPages)
? ~0ULL
: (1ULL << state_.num_pages) - 1;
}
AllocateStackTraces();
}
GuardedPageAllocator::~GuardedPageAllocator() {
if (state_.num_pages) {
UnmapPages();
DeallocateStackTraces();
}
}
void* GuardedPageAllocator::Allocate(size_t size, size_t align) {
if (!size || size > state_.page_size)
return nullptr;
// Default alignment is size's next smallest power-of-two, up to
// kGpaAllocAlignment.
if (!align) {
align =
std::min(size_t{1} << base::bits::Log2Floor(size), kGpaAllocAlignment);
}
CHECK_LE(align, size);
CHECK(base::bits::IsPowerOfTwo(align));
size_t free_slot = ReserveSlot();
if (free_slot == SIZE_MAX)
return nullptr; // All slots are reserved.
uintptr_t free_page = state_.SlotToAddr(free_slot);
MarkPageReadWrite(reinterpret_cast<void*>(free_page));
size_t offset;
if (base::RandInt(0, 1))
// Return right-aligned allocation to detect overflows.
offset = state_.page_size - base::bits::Align(size, align);
else
// Return left-aligned allocation to detect underflows.
offset = 0;
void* alloc = reinterpret_cast<void*>(free_page + offset);
// Initialize slot metadata.
RecordAllocationInSlot(free_slot, size, alloc);
return alloc;
}
void GuardedPageAllocator::Deallocate(void* ptr) {
CHECK(PointerIsMine(ptr));
const uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);
MarkPageInaccessible(reinterpret_cast<void*>(state_.GetPageAddr(addr)));
size_t slot = state_.AddrToSlot(state_.GetPageAddr(addr));
DCHECK_EQ(addr, state_.data[slot].alloc_ptr);
// Check for double free.
if (state_.data[slot].dealloc.trace_addr) {
state_.double_free_detected = true;
*reinterpret_cast<char*>(ptr) = 'X'; // Trigger exception.
__builtin_trap();
}
// Record deallocation stack trace/thread id.
RecordDeallocationInSlot(slot);
FreeSlot(slot);
}
size_t GuardedPageAllocator::GetRequestedSize(const void* ptr) const {
DCHECK(PointerIsMine(ptr));
const uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);
size_t slot = state_.AddrToSlot(state_.GetPageAddr(addr));
DCHECK_EQ(addr, state_.data[slot].alloc_ptr);
return state_.data[slot].alloc_size;
}
// Selects a random slot in O(1) time by rotating the free_pages bitmap by a
// random amount, using an intrinsic to get the least-significant 1-bit after
// the rotation, and then computing the position of the bit before the rotation.
// Picking a random slot is useful for randomizing allocator behavior across
// different runs, so certain bits being more heavily biased is not a concern.
size_t GuardedPageAllocator::ReserveSlot() {
base::AutoLock lock(lock_);
if (!free_pages_)
return SIZE_MAX;
// Disable allocations after a double free is detected so that the double
// freed allocation is not reallocated while the crash handler could be
// concurrently inspecting the metadata.
if (state_.double_free_detected)
return SIZE_MAX;
uint64_t rot = base::RandGenerator(AllocatorState::kGpaMaxPages);
BitMap rotated_bitmap = (free_pages_ << rot) |
(free_pages_ >> (AllocatorState::kGpaMaxPages - rot));
int rotated_selection = CountTrailingZeroBits64(rotated_bitmap);
size_t selection = (rotated_selection - rot + AllocatorState::kGpaMaxPages) %
AllocatorState::kGpaMaxPages;
DCHECK_LT(selection, AllocatorState::kGpaMaxPages);
DCHECK(free_pages_ & (1ULL << selection));
free_pages_ &= ~(1ULL << selection);
return selection;
}
void GuardedPageAllocator::FreeSlot(size_t slot) {
DCHECK_LT(slot, AllocatorState::kGpaMaxPages);
BitMap bit = 1ULL << slot;
base::AutoLock lock(lock_);
DCHECK_EQ((free_pages_ & bit), 0ULL);
free_pages_ |= bit;
}
void GuardedPageAllocator::AllocateStackTraces() {
// new is not used so that we can explicitly call the constructor when we
// want to collect a stack trace.
for (size_t i = 0; i < state_.num_pages; i++) {
alloc_traces[i] =
static_cast<StackTrace*>(malloc(sizeof(*alloc_traces[i])));
CHECK(alloc_traces[i]);
dealloc_traces[i] =
static_cast<StackTrace*>(malloc(sizeof(*dealloc_traces[i])));
CHECK(dealloc_traces[i]);
}
}
void GuardedPageAllocator::DeallocateStackTraces() {
for (size_t i = 0; i < state_.num_pages; i++) {
DestructStackTrace(i);
free(alloc_traces[i]);
alloc_traces[i] = nullptr;
free(dealloc_traces[i]);
dealloc_traces[i] = nullptr;
}
}
void GuardedPageAllocator::DestructStackTrace(size_t slot) {
// Destruct previous allocation/deallocation traces. The constructor was only
// called if trace_addr is non-null.
if (state_.data[slot].alloc.trace_addr)
alloc_traces[slot]->~StackTrace();
if (state_.data[slot].dealloc.trace_addr)
dealloc_traces[slot]->~StackTrace();
}
void GuardedPageAllocator::RecordAllocationInSlot(size_t slot,
size_t size,
void* ptr) {
state_.data[slot].alloc_size = size;
state_.data[slot].alloc_ptr = reinterpret_cast<uintptr_t>(ptr);
state_.data[slot].alloc.tid = base::PlatformThread::CurrentId();
new (alloc_traces[slot]) StackTrace();
state_.data[slot].alloc.trace_addr = reinterpret_cast<uintptr_t>(
alloc_traces[slot]->Addresses(&state_.data[slot].alloc.trace_len));
state_.data[slot].dealloc.tid = base::kInvalidThreadId;
state_.data[slot].dealloc.trace_addr = 0;
state_.data[slot].dealloc.trace_len = 0;
}
void GuardedPageAllocator::RecordDeallocationInSlot(size_t slot) {
state_.data[slot].dealloc.tid = base::PlatformThread::CurrentId();
new (dealloc_traces[slot]) StackTrace();
state_.data[slot].dealloc.trace_addr = reinterpret_cast<uintptr_t>(
dealloc_traces[slot]->Addresses(&state_.data[slot].dealloc.trace_len));
}
uintptr_t GuardedPageAllocator::GetCrashKeyAddress() const {
return reinterpret_cast<uintptr_t>(&state_);
}
} // namespace internal
} // namespace gwp_asan
| [
"artem@brave.com"
] | artem@brave.com |
2df9635af9ebe1dfa329b926d6fdaadefffc4bc1 | 22eaf0ae92d5b522bf61f8cab0501757a2f9ee59 | /chrome/browser/enterprise/reporting/report_request_queue_generator.cc | a90a2cc5db7a382c8f467c001fd2fbde61ae26e8 | [
"BSD-3-Clause"
] | permissive | fz112400/chromium | 285200b3691e1f43e0653a2e20bd64bd18b70246 | b8c6444fbfead99b92e5419bf5c81cf7813673c3 | refs/heads/master | 2022-11-17T14:06:57.306265 | 2020-07-15T15:43:48 | 2020-07-15T15:43:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,197 | cc | // Copyright 2019 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/enterprise/reporting/report_request_queue_generator.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/metrics/histogram_functions.h"
namespace enterprise_reporting {
namespace {
const size_t kMaximumReportSize =
5000000; // The report size limitation is 5mb.
constexpr char kRequestCountMetricsName[] =
"Enterprise.CloudReportingRequestCount";
constexpr char kRequestSizeMetricsName[] =
"Enterprise.CloudReportingRequestSize";
constexpr char kBasicRequestSizeMetricsName[] =
"Enterprise.CloudReportingBasicRequestSize";
// Because server only stores 20 profiles for each report and when report is
// separated into requests, there is at least one profile per request. It means
// server will truncate the report when there are more than 20 requests. Actions
// are needed if there are many reports exceed this limitation.
const int kRequestCountMetricMaxValue = 21;
} // namespace
ReportRequestQueueGenerator::ReportRequestQueueGenerator(
ReportingDelegateFactory* delegate_factory)
: maximum_report_size_(kMaximumReportSize),
profile_report_generator_(delegate_factory) {
#if defined(OS_CHROMEOS)
// For Chrome OS, policy information needn't be uploaded to DM server.
profile_report_generator_.set_policies_enabled(false);
#endif
}
ReportRequestQueueGenerator::~ReportRequestQueueGenerator() = default;
size_t ReportRequestQueueGenerator::GetMaximumReportSizeForTesting() const {
return maximum_report_size_;
}
void ReportRequestQueueGenerator::SetMaximumReportSizeForTesting(
size_t maximum_report_size) {
maximum_report_size_ = maximum_report_size;
}
ReportRequestQueueGenerator::ReportRequests
ReportRequestQueueGenerator::Generate(const ReportRequest& basic_request) {
ReportRequests requests;
size_t basic_request_size = basic_request.ByteSizeLong();
base::UmaHistogramMemoryKB(kBasicRequestSizeMetricsName,
basic_request_size / 1024);
if (basic_request_size <= maximum_report_size_) {
requests.push(std::make_unique<ReportRequest>(basic_request));
int profile_infos_size =
basic_request.browser_report().chrome_user_profile_infos_size();
for (int index = 0; index < profile_infos_size; index++) {
GenerateProfileReportWithIndex(basic_request, index, &requests);
}
base::UmaHistogramMemoryKB(kRequestSizeMetricsName,
requests.back()->ByteSizeLong() / 1024);
}
base::UmaHistogramExactLinear(kRequestCountMetricsName, requests.size(),
kRequestCountMetricMaxValue);
return requests;
}
void ReportRequestQueueGenerator::GenerateProfileReportWithIndex(
const ReportRequest& basic_request,
int profile_index,
ReportRequests* requests) {
DCHECK_LT(profile_index,
basic_request.browser_report().chrome_user_profile_infos_size());
size_t basic_request_size = basic_request.ByteSizeLong();
auto basic_profile =
basic_request.browser_report().chrome_user_profile_infos(profile_index);
auto profile_report = profile_report_generator_.MaybeGenerate(
base::FilePath::FromUTF8Unsafe(basic_profile.id()), basic_profile.name());
// Return if Profile is not loaded and there is no full report.
if (!profile_report)
return;
// Use size diff to calculate estimated request size after full profile report
// is added. There are still few bytes difference but close enough.
size_t profile_report_incremental_size =
profile_report->ByteSizeLong() - basic_profile.ByteSizeLong();
size_t current_request_size = requests->back()->ByteSizeLong();
if (current_request_size + profile_report_incremental_size <=
maximum_report_size_) {
// The new full Profile report can be appended into the current request.
requests->back()
->mutable_browser_report()
->mutable_chrome_user_profile_infos(profile_index)
->Swap(profile_report.get());
} else if (basic_request_size + profile_report_incremental_size <=
maximum_report_size_) {
// The new full Profile report is too big to be appended into the current
// request, move it to the next request if possible. Record metrics for the
// current request's size.
base::UmaHistogramMemoryKB(kRequestSizeMetricsName,
requests->back()->ByteSizeLong() / 1024);
requests->push(std::make_unique<ReportRequest>(basic_request));
requests->back()
->mutable_browser_report()
->mutable_chrome_user_profile_infos(profile_index)
->Swap(profile_report.get());
} else {
// The new full Profile report is too big to be uploaded, skip this
// Profile report. But we still add the report size into metrics so
// that we could understand the situation better.
base::UmaHistogramMemoryKB(
kRequestSizeMetricsName,
(basic_request_size + profile_report_incremental_size) / 1024);
}
}
} // namespace enterprise_reporting
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
7162e6dcd5340235ea000fd4a23592e8256b9fac | 299ba54b3b463cc122860cc7f376a3ff6699b2a3 | /smldr/cpp/idt.cpp | fd56b5e8cc2721ee8f9e6e346654d1b55e5326ca | [] | no_license | rameshg87/osmosys | becba9ea8081d18e0299c8a3da12fb81a62fde2c | 11cb72792390cf4640380866584008922fc1928d | refs/heads/master | 2021-01-10T05:00:55.927942 | 2016-03-03T13:34:49 | 2016-03-03T13:36:01 | 53,052,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,478 | cpp | /********************************************************************************
PART OF OSMOSYS OPERATING SYSTEM; CODE WRITTEN BY TEAM OSMOSYS
v1.2
********************************************************************************/
#include <idt.h>
#include <video.h>
#include <common.h>
struct idt_entry idt_entries [256];
extern "C" void timerhandler ();
extern "C" void keyboardhandler ();
extern "C" void commonhandler ();
extern oses os[];
extern int current_option;
int timer=0;
bool is_timer_active;
extern int current_option;
extern int oscount;
extern void print_options ();
extern void bootosmosys (int);
extern void chainload_os (int);
#define UP_ARROW 0x48
#define DOWN_ARROW 0x50
#define ENTER_KEY 0x1C
extern "C" void irq0 ();
void idt_install ()
{
irqremap ();
//setup descriptor table
idt_setup ();
//load the idtr register
loadidt ();
}
void exception_handler ()
{
putstring ("Exception encountered - Unable to proceed\n");
}
extern "C" void timer_handler ()
{
if (is_timer_active == true)
{
timer --;
if (timer == 0)
{
if (os[current_option].isosmosys == true)
{
outportb(0x20, 0x20);
bootosmosys (os[current_option].partindex);
}
else
{
outportb(0x20, 0x20);
chainload_os (os[current_option].partindex);
}
}
print_options ();
}
outportb(0x20, 0x20);
}
extern "C" void keyboard ()
{
int scancode = inportb (0x60);
is_timer_active = false;
if (!(scancode & 0x80))
{
if (scancode == DOWN_ARROW)
{
current_option++;
if (current_option == oscount)
current_option = 0;
print_options ();
}
else if (scancode == UP_ARROW)
{
current_option--;
if (current_option == -1)
current_option = oscount-1;
print_options ();
}
else if (scancode == ENTER_KEY)
{
if (os[current_option].isosmosys == true)
{
outportb(0x20, 0x20);
bootosmosys (os[current_option].partindex);
}
else
{
outportb(0x20, 0x20);
chainload_os (os[current_option].partindex);
}
}
}
outportb(0x20, 0x20);
}
extern "C" void common ()
{
outportb (0x20,0x20);
outportb (0xa0,0x20);
}
void fill_idt_entry (struct idt_entry &anentry,unsigned int base)
{
// fill idt entry given the base
anentry.baselow = ((unsigned int)(base)) & 0xFFFF;
anentry.basehigh = 0xFFFF & (((unsigned int)(base)) >> 16);
// segment selector is the code segment for the kernel
anentry.selector = 0x08;
// flags
anentry.flags = 0x8e;
anentry.always0 = 0;
}
void idt_setup ()
{
int i;
for (i=0;i<32;i++)
fill_idt_entry (idt_entries[i],(unsigned int)&exception_handler);
for (i=0x70;i<0x78;i++)
fill_idt_entry (idt_entries[i],(unsigned int)&commonhandler);
fill_idt_entry (idt_entries[8],(unsigned int)&timerhandler);
fill_idt_entry (idt_entries[9],(unsigned int)&keyboardhandler);
}
void irqremap()
{
/* ICW1 - port 0x20 is master pic and port 0xa0 is slave pic */
outportb(0x20,0x11);
outportb(0xA0,0x11);
/* ICW2 - port 0x21 is master pic and port 0xa1 is slave pic
remapping is done here */
outportb(0x21,0x08);
outportb(0xA1,0x70);
/* ICW3 select slave pin for master & set ID for slave*/
outportb(0x21,0x04);
outportb(0xA1,0x02);
/* ICW4 - set 8086 mode */
outportb(0x21,0x01);
outportb(0xA1,0x01);
/* Stop Initialization */
outportb(0x21,0x0);
outportb(0xA1,0x0);
}
| [
"rameshg87@gmail.com"
] | rameshg87@gmail.com |
befc08a9aac8c74374afa60ae4c048e76b8c3973 | 96e7347db30d3ae35f2df119a18472cf5b251fa2 | /Classes/Native/mscorlib_System_Array_InternalEnumerator_1_gen2202160161.h | cca87495a6274df1c75947bdf6c8a854dcaabb04 | [] | no_license | Henry0285/abcwriting | 04b111887489d9255fd2697a4ea8d9971dc17d89 | ed2e4da72fbbad85d9e0e9d912e73ddd33bc91ec | refs/heads/master | 2021-01-20T14:16:48.025648 | 2017-05-08T06:00:06 | 2017-05-08T06:00:06 | 90,583,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,470 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Array
struct Il2CppArray;
#include "mscorlib_System_ValueType4028081426.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array/InternalEnumerator`1<System.Security.Policy.CodeConnectAccess>
struct InternalEnumerator_1_t2202160161
{
public:
// System.Array System.Array/InternalEnumerator`1::array
Il2CppArray * ___array_0;
// System.Int32 System.Array/InternalEnumerator`1::idx
int32_t ___idx_1;
public:
inline static int32_t get_offset_of_array_0() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t2202160161, ___array_0)); }
inline Il2CppArray * get_array_0() const { return ___array_0; }
inline Il2CppArray ** get_address_of_array_0() { return &___array_0; }
inline void set_array_0(Il2CppArray * value)
{
___array_0 = value;
Il2CppCodeGenWriteBarrier(&___array_0, value);
}
inline static int32_t get_offset_of_idx_1() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t2202160161, ___idx_1)); }
inline int32_t get_idx_1() const { return ___idx_1; }
inline int32_t* get_address_of_idx_1() { return &___idx_1; }
inline void set_idx_1(int32_t value)
{
___idx_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"phamnguyentruc@yahoo.com"
] | phamnguyentruc@yahoo.com |
14b2c2e7a4ec18e2a98062b75040c3045a8709d9 | d213f2a47aa902f8b2f208850e131ab3e34ad17b | /Game1/PickupDef.cpp | 86505ce409b95477f2e231ba3f4b1a960bbee756 | [] | no_license | ntaylorbishop/HGAM_Roguelike | 0f653bcd596b4e062db89c99ac2060cd1ee9857c | 668c80f2171c5788543bddf04044b28170a72048 | refs/heads/master | 2020-04-26T09:57:11.557294 | 2015-03-25T22:16:13 | 2015-03-25T22:16:13 | 29,994,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cpp | #include "PickupDef.h"
//STRUCTORS
PickupDef::PickupDef() {
this->tile = 0;
this->name = name;
this->desc = "NULL";
this->type = type;
this->useEffect = [](){};
this->removeEffect = [](){};
}
PickupDef::PickupDef(int tile, string name, int type, function<void()> useEffect) {
this->tile = tile;
this->name = name;
this->desc = "NULL";
this->type = type;
this->useEffect = useEffect;
this->removeEffect = [](){};
}
PickupDef::PickupDef(int tile, string name, string desc, int type, function<void()> useEffect, function<void()> removeEffect) {
this->tile = tile;
this->name = name;
this->desc = desc;
this->type = type;
this->useEffect = useEffect;
this->removeEffect = removeEffect;
}
//GETTERS / SETTERS
int PickupDef::getTile() {
return tile;
}
string PickupDef::getName() {
return name;
}
string PickupDef::getDESC() {
return desc;
}
int PickupDef::getType() {
return type;
} | [
"ntaylorbishop@gmail.com"
] | ntaylorbishop@gmail.com |
9b137876e9c885099e29b02838b0b4a89766ab03 | 47dad1897990394883f2c16b0904e4cdae3e054c | /base/src/sgpp/base/operation/hash/OperationEvalHessianModBsplineNaive.cpp | b4648d84ac2673cc8b518e72cc025f9fae524b11 | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause"
] | permissive | QianWanghhu/SGpp | 430207e3f533eb96d57540b00475d303b0d955e5 | c36a95127d0ec833d4f45b8ed44ad3ffe482ae64 | refs/heads/master | 2020-09-20T03:37:26.170177 | 2019-11-26T10:43:02 | 2019-11-26T10:43:02 | 224,367,076 | 2 | 0 | NOASSERTION | 2019-11-27T07:08:00 | 2019-11-27T07:07:59 | null | UTF-8 | C++ | false | false | 5,046 | cpp | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#include <sgpp/globaldef.hpp>
#include <sgpp/base/operation/hash/OperationEvalHessianModBsplineNaive.hpp>
#include <vector>
namespace sgpp {
namespace base {
double OperationEvalHessianModBsplineNaive::evalHessian(const DataVector& alpha,
const DataVector& point,
DataVector& gradient,
DataMatrix& hessian) {
const size_t n = storage.getSize();
const size_t d = storage.getDimension();
double result = 0.0;
pointInUnitCube = point;
storage.getBoundingBox()->transformPointToUnitCube(pointInUnitCube);
for (size_t t = 0; t < d; t++) {
innerDerivative[t] = 1.0 / storage.getBoundingBox()->getIntervalWidth(t);
}
gradient.resize(d);
gradient.setAll(0.0);
hessian = DataMatrix(d, d);
hessian.setAll(0.0);
DataVector curGradient(d);
DataMatrix curHessian(d, d);
for (size_t i = 0; i < n; i++) {
const GridPoint& gp = storage[i];
double curValue = 1.0;
curGradient.setAll(alpha[i]);
curHessian.setAll(alpha[i]);
for (size_t t = 0; t < d; t++) {
const double val1d = base.eval(gp.getLevel(t), gp.getIndex(t), pointInUnitCube[t]);
const double dx1d = base.evalDx(gp.getLevel(t), gp.getIndex(t), pointInUnitCube[t]) *
innerDerivative[t];
const double dxdx1d = base.evalDxDx(gp.getLevel(t), gp.getIndex(t), pointInUnitCube[t]) *
innerDerivative[t] * innerDerivative[t];
curValue *= val1d;
for (size_t t2 = 0; t2 < d; t2++) {
if (t2 == t) {
curGradient[t2] *= dx1d;
for (size_t t3 = 0; t3 < d; t3++) {
if (t3 == t) {
curHessian(t2, t3) *= dxdx1d;
} else {
curHessian(t2, t3) *= dx1d;
}
}
} else {
curGradient[t2] *= val1d;
for (size_t t3 = 0; t3 < d; t3++) {
if (t3 == t) {
curHessian(t2, t3) *= dx1d;
} else {
curHessian(t2, t3) *= val1d;
}
}
}
}
}
result += alpha[i] * curValue;
gradient.add(curGradient);
hessian.add(curHessian);
}
return result;
}
void OperationEvalHessianModBsplineNaive::evalHessian(const DataMatrix& alpha,
const DataVector& point,
DataVector& value,
DataMatrix& gradient,
std::vector<DataMatrix>& hessian) {
const size_t n = storage.getSize();
const size_t d = storage.getDimension();
const size_t m = alpha.getNcols();
pointInUnitCube = point;
storage.getBoundingBox()->transformPointToUnitCube(pointInUnitCube);
for (size_t t = 0; t < d; t++) {
innerDerivative[t] = 1.0 / storage.getBoundingBox()->getIntervalWidth(t);
}
value.resize(m);
value.setAll(0.0);
gradient.resize(m, d);
gradient.setAll(0.0);
if (hessian.size() != m) {
hessian.resize(m);
}
for (size_t j = 0; j < m; j++) {
hessian[j].resize(d, d);
hessian[j].setAll(0.0);
}
DataVector curGradient(d);
DataMatrix curHessian(d, d);
for (size_t i = 0; i < n; i++) {
const GridPoint& gp = storage[i];
double curValue = 1.0;
curGradient.setAll(1.0);
curHessian.setAll(1.0);
for (size_t t = 0; t < d; t++) {
const double val1d = base.eval(gp.getLevel(t), gp.getIndex(t), pointInUnitCube[t]);
const double dx1d = base.evalDx(gp.getLevel(t), gp.getIndex(t), pointInUnitCube[t]) *
innerDerivative[t];
const double dxdx1d = base.evalDxDx(gp.getLevel(t), gp.getIndex(t), pointInUnitCube[t]) *
innerDerivative[t] * innerDerivative[t];
curValue *= val1d;
for (size_t t2 = 0; t2 < d; t2++) {
if (t2 == t) {
curGradient[t2] *= dx1d;
for (size_t t3 = 0; t3 < d; t3++) {
if (t3 == t) {
curHessian(t2, t3) *= dxdx1d;
} else {
curHessian(t2, t3) *= dx1d;
}
}
} else {
curGradient[t2] *= val1d;
for (size_t t3 = 0; t3 < d; t3++) {
if (t3 == t) {
curHessian(t2, t3) *= dx1d;
} else {
curHessian(t2, t3) *= val1d;
}
}
}
}
}
for (size_t j = 0; j < m; j++) {
value[j] += alpha(i, j) * curValue;
for (size_t t = 0; t < d; t++) {
gradient(j, t) += alpha(i, j) * curGradient[t];
for (size_t t2 = 0; t2 < d; t2++) {
hessian[j](t, t2) += alpha(i, j) * curHessian(t, t2);
}
}
}
}
}
} // namespace base
} // namespace sgpp
| [
"julian.valentin@ipvs.uni-stuttgart.de"
] | julian.valentin@ipvs.uni-stuttgart.de |
b1f90e6e8ad21f70ff52031a37891752060fb4d2 | b152993f856e9598e67d046e6243350dcd622abe | /chrome/browser/media/router/discovery/access_code/access_code_cast_pref_updater.h | 02130646ca2cc736e28d730f726c0a49eefe9ed2 | [
"BSD-3-Clause"
] | permissive | monad-one/chromium | 10e4a585fbd2b66b55d5afcba72c50a872708238 | 691b5c9cfa2a4fc38643509932e62438dc3a0d54 | refs/heads/main | 2023-05-14T07:36:48.032727 | 2023-05-10T13:47:48 | 2023-05-10T13:47:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,553 | h | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_ACCESS_CODE_ACCESS_CODE_CAST_PREF_UPDATER_H_
#define CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_ACCESS_CODE_ACCESS_CODE_CAST_PREF_UPDATER_H_
#include "base/time/time.h"
#include "base/values.h"
#include "components/media_router/common/discovery/media_sink_internal.h"
#include "components/media_router/common/media_sink.h"
namespace media_router {
// An interface used by both LaCros and other desktop platforms for pref
// updating in AccessCodeCasting.
class AccessCodeCastPrefUpdater {
public:
AccessCodeCastPrefUpdater() = default;
AccessCodeCastPrefUpdater(const AccessCodeCastPrefUpdater&) = delete;
AccessCodeCastPrefUpdater& operator=(const AccessCodeCastPrefUpdater&) =
delete;
virtual ~AccessCodeCastPrefUpdater();
// Sets the key for the given |sink| id with the actual |sink| itself. This
// function will overwrite a sink id if it already exists. If ip_endpoints
// already exist with the given |sink| id, those entries will be removed from
// the pref service.
virtual void UpdateDevicesDict(const MediaSinkInternal& sink) = 0;
// Sets the key for the |sink_id| with the time it is added. This is
// calculated at the time of the functions calling. If the |sink_id| already
// exist, then update the value of that |sink_id| with a new time.
virtual void UpdateDeviceAddedTimeDict(const MediaSink::Id sink_id) = 0;
// Returns a the device dictionary from the pref service.
virtual const base::Value::Dict& GetDevicesDict() = 0;
// Returns a nullptr if the device Added dictionary does not exist in the
// pref service for some reason.
virtual const base::Value::Dict& GetDeviceAddedTimeDict() = 0;
// Gets a list of all sink ids currently stored in the pref service.
const base::Value::List GetSinkIdsFromDevicesDict();
// If found, it returns a pointer to the element. Otherwise it returns
// nullptr.
const base::Value* GetMediaSinkInternalValueBySinkId(
const MediaSink::Id sink_id);
// If found and a valid time value, returns the time of Addeds.
absl::optional<base::Time> GetDeviceAddedTime(const MediaSink::Id sink_id);
// Removes the given |sink_id| from all instances in the devices dictionary
// stored in the pref service. Nothing occurs if the |sink_id| was not there
// in the first place.
virtual void RemoveSinkIdFromDevicesDict(const MediaSink::Id sink_id) = 0;
// Removes the given |sink_id| from all instances in the device Added
// dictionary stored in the pref service. Nothing occurs if the |sink_id| was
// not there in the first place.
virtual void RemoveSinkIdFromDeviceAddedTimeDict(
const MediaSink::Id sink_id) = 0;
// Returns a list of media sink id's of stored media sinks whose ip endpoints
// are identical to the given ip_endpoint. If no existing ip endpoints are
// found, the list will be empty.
std::vector<MediaSink::Id> GetMatchingIPEndPoints(
net::IPEndPoint ip_endpoint);
virtual void ClearDevicesDict() = 0;
virtual void ClearDeviceAddedTimeDict() = 0;
// Sets the key for the given |sink| id with the actual |sink| itself. This
// function will overwrite a sink id if it already exists.
virtual void UpdateDevicesDictForTest(const MediaSinkInternal& sink) = 0;
};
} // namespace media_router
#endif // CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_ACCESS_CODE_ACCESS_CODE_CAST_PREF_UPDATER_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
1b3040159fef9f82b63ebbedd02e5ca493c94bb0 | f3526165a28143e2f69e2fda1cdeffd09c235eb8 | /heaptype.h | 17741d0ff7c0008d85078451342b1fdff5cb354d | [] | no_license | mrbrownstone07/Health-assistant | 915635c1b79c44139e753114b4a1f690bfac45e7 | c7c01cb9cd0e0fd45bf3864a94e78d8fffbe1273 | refs/heads/master | 2020-04-08T02:02:05.612698 | 2018-11-24T09:22:36 | 2018-11-24T09:22:36 | 158,919,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | h | #ifndef HEAPTYPE_H_INCLUDED
#define HEAPTYPE_H_INCLUDED
template<class ItemType>
struct heaptype
{
void ReheapDown(int root,int bottom);
void Reheap(int root,int bottom);
ItemType*elements;
int numElements;
};
#endif // HEAPTYPE_H_INCLUDED
| [
"mahdi.mad07@gmail.com"
] | mahdi.mad07@gmail.com |
b6db94b6de3b3ee1156c1cccda7c6171c0c8a5a9 | ca71a8028ae57cac5e8f9b10fa0db3333efec086 | /ACC sharedmemory exposer/SDK/ACC_WDG_SinglePlayerLowerPanel_parameters.hpp | d02ae8776f5489b21a6769b799d7d43126ab88bc | [] | no_license | Sparten/ACC | 42d08b17854329c245d9543e5184888d119251c1 | 3ee1e5c032dcd508e5913539feb575f42d74365e | refs/heads/master | 2020-03-28T20:47:48.649504 | 2018-10-19T20:47:39 | 2018-10-19T20:47:39 | 149,102,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | hpp | #pragma once
// Assetto Corsa Competizione (0.1.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ACC_WDG_SinglePlayerLowerPanel_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function WDG_SinglePlayerLowerPanel.WDG_SinglePlayerLowerPanel_C.BP_MouseOver
struct UWDG_SinglePlayerLowerPanel_C_BP_MouseOver_Params
{
};
// Function WDG_SinglePlayerLowerPanel.WDG_SinglePlayerLowerPanel_C.BP_MouseLeave
struct UWDG_SinglePlayerLowerPanel_C_BP_MouseLeave_Params
{
};
// Function WDG_SinglePlayerLowerPanel.WDG_SinglePlayerLowerPanel_C.ExecuteUbergraph_WDG_SinglePlayerLowerPanel
struct UWDG_SinglePlayerLowerPanel_C_ExecuteUbergraph_WDG_SinglePlayerLowerPanel_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sportcorp@hotmail.com"
] | sportcorp@hotmail.com |
7f88bac9704b2cc2020fe4bca8230f67a63a46af | 5670418126e79fa4eff199dfbda340727ad30ada | /map/chunk.h | 9e8faa4cc6b1592390352996b880ecb9e6bc3ccb | [] | no_license | wokste/steamdiggerengine | 1a8be37598f9d50a6015af35624428fcbae43b08 | d0e79a94d8dc660d25011e344cac4d3cea246928 | refs/heads/master | 2021-01-17T09:37:55.707891 | 2013-10-20T09:10:09 | 2013-10-20T09:10:09 | 12,185,012 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | h | /*
The MIT License (MIT)
Copyright (c) 2013, Steven Wokke
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 "mapnode.h"
class MapGenerator;
class Chunk{
public:
static constexpr int width = 16; // a power of 2
static constexpr int widthMask = width - 1;
static constexpr int height = 16; // a power of 2
static constexpr int heightMask = height - 1;
MapNode nodes[width][height];
Chunk(const MapGenerator& generator, const Vector2i& topLeft);
void render(const sf::Color& skyColor, const Vector2i& topLeft, int focussedLayer) const;
};
// == Constraints ==
static_assert(!(Chunk::width & Chunk::widthMask), "Chunk::width must be a power of 2");
static_assert(!(Chunk::height & Chunk::heightMask), "Chunk::height must be a power of 2");
| [
"wokste@gmail.com"
] | wokste@gmail.com |
1d0885e2353ea226f6c4242252e9a512130b520f | a55cec32c0191f3f99752749f8323a517be46638 | /ProfessionalC++/Destructors/DestructorHeapExamples.cpp | 2d2aed264879f3316804b4746a585da2ffa418c2 | [
"Apache-2.0"
] | permissive | zzragida/CppExamples | e0b0d1609b2e485cbac22e0878e00cc8ebce6a94 | d627b097efc04209aa4012f7b7f9d82858da3f2d | refs/heads/master | 2021-01-18T15:06:57.286097 | 2016-03-08T00:23:31 | 2016-03-08T00:23:31 | 49,173,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | #include <iostream>
#include "SpreadsheetCell.h"
using namespace std;
int main()
{
SpreadsheetCell* cellPtr1 = new SpreadsheetCell(5);
SpreadsheetCell* cellPtr2 = new SpreadsheetCell(6);
cout << "cellPtr1: " << cellPtr1->getValue() << endl;
delete cellPtr1;
cellPtr1 = nullptr;
return 0;
}
| [
"zzragida@gmail.com"
] | zzragida@gmail.com |
13c7d125a6e74237b7b8f0eecd1c48c60c5f44af | b819c29719ecb14440dab9d5cbc49d9901fc2d04 | /Client/Code/ElevatorBaseShader.cpp | 9ea9eb21d6f2d4fefd2b2919a0d401d3c7754106 | [] | no_license | Underdog-113/3D_portfolio | d338f49d518702b191e590dc22166c9f28c08b14 | 6b877ff5272bea2e6d2a2bd53e63b6ee4728cd9c | refs/heads/develop | 2023-07-07T20:30:00.759582 | 2021-07-27T06:01:52 | 2021-07-27T06:01:52 | 371,051,333 | 0 | 1 | null | 2021-06-13T14:30:32 | 2021-05-26T13:52:07 | C++ | UTF-8 | C++ | false | false | 918 | cpp | #include "stdafx.h"
#include "ElevatorBaseShader.h"
CElevatorBaseShader::CElevatorBaseShader()
{
}
CElevatorBaseShader::~CElevatorBaseShader()
{
}
Engine::CShader * CElevatorBaseShader::Create(void)
{
CElevatorBaseShader* pInstance = new CElevatorBaseShader;
pInstance->Awake();
return pInstance;
}
void CElevatorBaseShader::Free(void)
{
__super::Free();
}
void CElevatorBaseShader::Awake(void)
{
__super::Awake();
Engine::CRenderTargetManager* pRTM = Engine::CRenderTargetManager::GetInstance();
m_vRenderTargets[0] = pRTM->FindRenderTarget(L"Target_Albedo");
m_vRenderTargets[1] = pRTM->FindRenderTarget(L"Target_Normal");
m_vRenderTargets[2] = pRTM->FindRenderTarget(L"Target_Depth");
m_vRenderTargets[3] = pRTM->FindRenderTarget(L"Target_Emissive");
}
void CElevatorBaseShader::SetUpConstantTable(SP(Engine::CGraphicsC) spGC)
{
__super::SetUpConstantTable(spGC);
SetupWorldViewProj(spGC);
}
| [
"yjcm1214@gmail.com"
] | yjcm1214@gmail.com |
3e1f98c12a3d6197142b13d2746b274fa01f96aa | 33e52bacdb655210831a2fbb33cd868dd4215fab | /Card.h | 2bd879cb706233b1c14b055a362429514828faeb | [] | no_license | gabesaleh17/PokerGame | 9a6373898f0509475c57e109af428181cd47c4c0 | fac8a2cc6778ec7dedce71f76b91131cb98a06d0 | refs/heads/master | 2022-07-10T00:42:33.200630 | 2020-05-01T01:11:55 | 2020-05-01T01:11:55 | 260,352,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | h | //
// Card.h
// Poker
//
// Created by Gabe Saleh on 4/27/20.
// Copyright © 2020 Gabe Saleh. All rights reserved.
//
#ifndef Card_h
#define Card_h
#include <map>
#include <string>
#include <iostream>
#include <cmath>
enum SuitType {Hearts = 0, Diamonds = 1, Spades = 2, Clubs = 3};
enum ValueType {ace = 0, two = 1, three = 2, four = 3, five = 4, six = 5, seven = 6, eight = 7, nine = 8, ten = 9, jack = 11, queen = 12, king = 13};
class Card
{
public:
Card();
//getters
SuitType getSuit();
ValueType getValue();
//setters
void setSuit(SuitType suit);
void setValue(ValueType value);
private:
SuitType m_suit;
ValueType m_value;
};
#endif /* Card_h */
| [
"noreply@github.com"
] | noreply@github.com |
f2548cd445d5b59817041d23444f91c4d2980b7f | f04a5a0ff2c9eb4e84b27f47c20ebfe5bddbaee6 | /Inc/AIState.h | ee27058b985bb263ec584e2547591660bf916b50 | [] | no_license | mattrudder/AckZombies | 20e5d2e814af4904bfbd0917b3e2a166927d88b7 | dda83eb258393b269ef8c206b90334d111c30bb3 | refs/heads/master | 2021-01-19T14:57:24.440727 | 2012-08-15T16:31:01 | 2012-08-15T16:31:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,930 | h | /**
* @file AIState.h
* @author Jonathan "Awesome" Zimmer
* @date Created March 28, 2006
*
* This file contains the definition of the CAIState class.
*/
#ifndef _AISTATE_H_
#define _AISTATE_H_
// Local Includes
#include "Timer.h"
// Forward Declarations
class CAIEntity;
class CCharacter;
/**
* Abstract base class for interface to define behaviors of AI entities
*
* @author Jonathan "Awesome" Zimmer
* @date Created March 28, 2006
* @date Modified May 30, 2006
*/
class CAIState
{
public:
//! Defines the individual AI state types
enum EAIStateTypes
{
AIS_PATHPLAN, //! Path Planning using best first
AIS_PATHFOLLOW, //! Path Following using stored nodes
AIS_FOLLOWLEADER, //! Following a leader
AIS_ZOMBIEATTACK, //! Zombie Citizen attack state
AIS_GASEOUSFOLLOW, //! Gaseous Clay path following
AIS_GASEOUSATTACK, //! Gaseous Clay attack state
AIS_ACIDICFOLLOW, //! Acidic Ice Cream Man path following
AIS_ACIDICATTACK, //! Acidic Ice Cream Man attack state
AIS_QBFOLLOW, //! Quarterback Zombie path following
AIS_QBRANGEATTACK, //! Quarterback Zombie throws a flamming football
AIS_QBMELEEATTACK, //! Quarterback Zombie charges
AIS_STRAIGHTTOGOAL, //! Sends the enemy straight to the closest goal
AIS_SPAWN, //! Moves the enemy for below ground to above ground
AIS_MAX,
};
private:
//! The type of state this state is
EAIStateTypes m_eStateType;
protected:
/**
* Set the state type
*
* @date Created March 28, 2006
* @param[in] eType the type to set this state to
*/
inline void setStateType(EAIStateTypes eType) { m_eStateType = eType; }
public:
virtual ~CAIState() {}
/**
* Overload to implement the desired behavior of the state
*
* @date Created March 28, 2006
* @param[in] poAIEntity pointer to the AI the state is working on
* @param[in] poCharacter pointer to the character this AI is contained
* (this pointer)
*/
virtual void update(CAIEntity* poAIEntity, CCharacter* poCharacter) = 0;
/**
* must be called when the state is entered
*
* @date Created April 13, 2006
* @param[in] poAIEntity pointer to the AI the state is working on
* @param[in] poCharacter pointer to the character this AI is contained
* (this pointer)
*/
virtual void enter(CAIEntity* poAIEntity, CCharacter* poCharacter) = 0;
/**
* must be called when the state is exited
*
* @date Created April 13, 2006
* @param[in] poAIEntity pointer to the AI the state is working on
* @param[in] poCharacter pointer to the character this AI is contained
* (this pointer)
*/
virtual void exit(CAIEntity* poAIEntity, CCharacter* poCharacter) = 0;
/**
* Get the state type
*
* @date Created March 28, 2006
* @return The type of this state
*/
inline EAIStateTypes getState(void) { return m_eStateType; }
};
#endif /*_AISTATE_H_*/ | [
"matt@mattrudder.com"
] | matt@mattrudder.com |
97c842875f0b9f5f4480779e5abc6cb0499c9a68 | 2889cbd28b745699330908efe98da35156aced31 | /数据结构/algorithm-master/06 串/字符串与自动机/字符串的堆储存.cpp | fc5eb31ea9d5ce96924758bf09963f4e16c4badc | [] | no_license | zhangchunbao515/Test | 76972a8f230f60759e49a5548c7c6bbf9a8817bc | 067f9c13bf34466eea9842ebd1ccf7b3c7147123 | refs/heads/master | 2022-02-16T21:50:37.993834 | 2019-09-11T13:32:29 | 2019-09-11T13:32:29 | 116,463,136 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,795 | cpp | #include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef int status;
#define OK 1
#define ERROR 0
// 串的堆储存
typedef struct
{
char *base;
int lenth;
}string;
int lenth(char *s)
{
int len = 0;
while (*s != '\0')
{
len++;
s++;
}
return len;
}
status strcopy(string *s, char *re)
{
// 算法,销毁原来的,然后建个新的,再放进来
char *cur;
if (lenth(re) <= 0) return ERROR;
// 如果有,就释放掉
if (s->base) free(s->base);
// 重新分配大小
s->lenth = lenth(re);
s->base = (char *)malloc((s->lenth+1) * sizeof(char));
if (!s->base) return ERROR;
cur = s->base;
while (*re != '\0') *cur++ = *re++;
*cur = '\0'; // 封口
return OK;
}
status init(string *s)
{
s->base = NULL;
s->lenth = 0;
return OK;
}
status strshow(string s)
{
char *cur;
if (s.lenth <= 0) return ERROR;
// for (i=0; i<s.lenth; i++) 也是可以的
for (cur=s.base; *cur!='\0'; cur++)
{
printf("%c", *cur);
}
printf("\n");
return OK;
}
status strcompare(string s, string t)
{
int i;
for (i=0; i<s.lenth && i<t.lenth; i++)
{
if (s.base[i] != t.base[i])
return s.base[i] - t.base[i];
}
// 如果有一个串的长度是 0
return s.lenth - t.lenth;
}
status strclear(string *s)
{
if (s->base) free(s->base);
s->lenth = 0;
return OK;
}
status strback(string s, int pos, int len, string *back)
{
int i;
int now = 0;
int end;
// 把 back 销毁了,再放新的
// abcd
if (pos >= 1 && len >= 0 && pos+len <= s.lenth+1)
{
if (back->base) strclear(back);
back->base = (char *)malloc((len+2)*sizeof(char));
if (!back->base) return ERROR;
back->lenth = len;
pos--; // 位序比下标多了 1
end = pos + len;
for (i=pos; i<end; i++)
{
back->base[now++] = s.base[i];
}
back->base[now] = '\0';
return OK;
}
else return ERROR;
}
status strcatch(string s, string t)
{
// 算法:原基础上重新扩展 s 的大小,把 t 放进来
int now = 0;
int i;
if (t.lenth <= 0) return ERROR;
s.lenth += t.lenth;
s.base = (char *)realloc(s.base, (s.lenth+1)*sizeof(char));
if (!s.base) exit(0);
for (i=s.lenth-t.lenth; i<s.lenth; i++)
{
s.base[i] = t.base[now++];
}
s.base[i] = '\0';
return OK;
}
int main(void)
{
string s1, s2;
init(&s1); // 初始化
init(&s2);
strcopy(&s1, "abcdefg"); // 串复制
strshow(s1);
printf("长度:%d\n", s1.lenth);
strcopy(&s2, s1.base); // 串遍历
strshow(s2);
strcatch(s2, s1); // 串连接
strshow(s2);
strback(s1, 4, 4, &s2); // 串截取
strshow(s2);
// 串比较
strcopy(&s2, "bbcdefg");
if (strcompare(s1, s2) > 0) printf("s1 > s2\n");
else if (strcompare(s1, s2) < 0) printf("s1 < s2\n");
else if (strcompare(s1, s2) == 0) printf("s1 = s2\n");
strclear(&s1); // 释放
strclear(&s2);
return 0;
} | [
"zhangchunbao515@163.com"
] | zhangchunbao515@163.com |
dc3621c227376cb14dede8d75c5ebecb3dd40ff8 | 81e71315f2f9e78704b29a5688ba2889928483bb | /include/crgui/crSelectNodeENVisitor.h | b57edc5f8ebd8b6e81a097ea9b8904d30a9d88ec | [] | no_license | Creature3D/Creature3DApi | 2c95c1c0089e75ad4a8e760366d0dd2d11564389 | b284e6db7e0d8e957295fb9207e39623529cdb4d | refs/heads/master | 2022-11-13T07:19:58.678696 | 2019-07-06T05:48:10 | 2019-07-06T05:48:10 | 274,064,341 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,743 | h | /* Creature3D - Online Game Engine, Copyright (C) 2005 吴财华(26756325@qq.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#ifndef CRGUI_CRHISTORY_H
#define CRGUI_CRHISTORY_H 1
#include <CRCore\ref_ptr.h>
#include <CRGUI\crElementNodeVisitor.h>
#include <CRGUI\crElementNode.h>
#include <CRCore\crVector2.h>
#include <CRCore\crVector4.h>
#include <vector>
namespace CRGUI {
class CRGUI_EXPORT crSelectNodeENVisitor : public crElementNodeVisitor
{
public:
crSelectNodeENVisitor(int x, int y);
crSelectNodeENVisitor(CRCore::crVector2i &point);
crSelectNodeENVisitor(int left, int right, int top, int bottom);
crSelectNodeENVisitor(CRCore::crVector4i &rect);
virtual ~crSelectNodeENVisitor();
virtual void apply(crElementNode& enode);
enum Flag
{
POINTSEL,
RECTSEL,
RECTINTERSECT
};
void setFlag(Flag flg){ m_flag = flg; }
protected:
/** prevent unwanted copy operator.*/
crSelectNodeENVisitor& operator = (const crSelectNodeENVisitor&) { return *this; }
CRCore::crVector2i m_point;//点选
CRCore::crVector4i m_rect;//框选left top right buttom
Flag m_flag;
};
}
#endif | [
"wucaihua@86aba9cf-fb85-4101-ade8-2f98c1f5b361"
] | wucaihua@86aba9cf-fb85-4101-ade8-2f98c1f5b361 |
c54c0feb645606a6093e704cb03639e872c58ea6 | edebf3a71db527182a434067d080672746bc2ef2 | /Step/ShapeData.cpp | 8499d1333193682ab19eebcdbc4949c19bd1ddc0 | [
"BSD-3-Clause"
] | permissive | DejavuLeo/PyCAD | e537529919ec71b8d68d05a9161d818ee0f351ca | 2fa91958ca34e645aeb99a0a423fb026fc34b5f8 | refs/heads/master | 2023-09-05T11:26:36.640291 | 2021-11-18T12:19:58 | 2021-11-18T12:19:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,242 | cpp | // ShapeData.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "ShapeData.h"
#include "Solid.h"
#include "strconv.h"
CShapeData::CShapeData(): m_xml_element("")
{
m_id = -1;
m_solid_type = SOLID_TYPE_UNKNOWN;
m_visible = true;
}
CShapeData::CShapeData(CShape* shape): m_xml_element("")
{
m_id = shape->m_id;
m_title = Ttc(shape->m_title.c_str());
m_title_made_from_id = shape->m_title_made_from_id;
m_visible = shape->m_visible;
m_solid_type = SOLID_TYPE_UNKNOWN;
if(shape->GetType() == CSolid::m_type)m_solid_type = ((CSolid*)shape)->GetSolidType();
shape->SetXMLElement(&m_xml_element);
for(HeeksObj* object = shape->m_faces->GetFirstChild(); object; object = shape->m_faces->GetNextChild())
{
m_face_ids.push_back(object->m_id);
}
for(HeeksObj* object = shape->m_edges->GetFirstChild(); object; object = shape->m_edges->GetNextChild())
{
m_edge_ids.push_back(object->m_id);
}
for(HeeksObj* object = shape->m_vertices->GetFirstChild(); object; object = shape->m_vertices->GetNextChild())
{
m_vertex_ids.push_back(object->m_id);
}
}
void CShapeData::SetShape(CShape* shape, bool apply_id)
{
if(apply_id && (m_id != -1))shape->SetID(m_id);
if(m_title.length() > 0)shape->m_title = Ctt(m_title.c_str());
shape->m_title_made_from_id = m_title_made_from_id;
shape->m_visible = m_visible;
shape->SetFromXMLElement(&m_xml_element);
{
std::list<int>::iterator It = m_face_ids.begin();
for(HeeksObj* object = shape->m_faces->GetFirstChild(); object && It != m_face_ids.end(); object = shape->m_faces->GetNextChild(), It++)
{
object->SetID(*It);
}
}
{
std::list<int>::iterator It = m_edge_ids.begin();
for(HeeksObj* object = shape->m_edges->GetFirstChild(); object && It != m_edge_ids.end(); object = shape->m_edges->GetNextChild(), It++)
{
object->SetID(*It);
}
}
{
std::list<int>::iterator It = m_vertex_ids.begin();
for(HeeksObj* object = shape->m_vertices->GetFirstChild(); object && It != m_vertex_ids.end(); object = shape->m_vertices->GetNextChild(), It++)
{
object->SetID(*It);
}
}
}
| [
"danheeks@gmail.com"
] | danheeks@gmail.com |
8dc3bbbfbf86d230db5c60331c0ccbfb0c75a554 | e8f4a45897a2691073211faa2927379069869325 | /pre-midterm/bst.cpp | 89a3a774c1328644b02462757ab85d37ba4f92eb | [] | no_license | TulebaevTemirlan/ADS2020 | d58c96be882c293a27fca391a00ec5bebf31ea73 | c9728c063a6eb31cf5f9ef64523b0c1530faba2b | refs/heads/master | 2021-02-09T23:18:22.855945 | 2020-09-16T14:04:25 | 2020-09-16T14:04:25 | 244,333,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,680 | cpp | #include <iostream>
using namespace std;
class Node{
public:
int data;
Node *left, *right;
Node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
class BST{
public:
Node *root;
BST(){
this->root = NULL;
}
Node* insert(Node* root,int data){
if(root == NULL){
return new Node(data);
}
else if(root->data > data){
root->left = insert(root->left, data);
}
else if(root->data < data){
root->right = insert(root->right, data);
}
return root;
}
Node* find_max(Node* node){
node = node->left;
while(node->right != NULL){
node = node->right;
}
return node;
}
Node* find_min(Node* node){
node = node->right;
while(node->left != NULL){
node = node->left;
}
return node;
}
void print(Node* node){
if(node == NULL)
return;
print(node->left);
cout <<node->data << " ";
print(node->right);
}
};
int main(){
BST *bst = new BST();
bst->root = bst->insert(bst->root,25);
bst->root = bst->insert(bst->root,50);
bst->root = bst->insert(bst->root,45);
bst->root = bst->insert(bst->root,56);
bst->root = bst->insert(bst->root,17);
bst->root = bst->insert(bst->root,2);
bst->root = bst->insert(bst->root,20);
bst->root = bst->insert(bst->root,5);
cout << bst->find_max(bst->root)->data << endl;
cout << bst->find_min(bst->root)->data << endl;
bst->print(bst->root);
} | [
"47266010+TulebaevTemirlan@users.noreply.github.com"
] | 47266010+TulebaevTemirlan@users.noreply.github.com |
e876abc01fdb340e0a799ff6283ab9d52f82a8eb | dee25a9d518640f21148900cd16af45d24ffcf2d | /ジョイスティックプログラム/joystick/joystick.ino | 3807b777e6c14fa12c5e3d1173889cab4833440a | [] | no_license | shingokawaue/arduinoSketch | 49ff218c38818bb23363db136d252e7a19521c96 | 9c89856edcf0e2846982d1a36b6ee2beb1f56c58 | refs/heads/master | 2020-07-24T05:13:41.085476 | 2019-09-11T13:20:15 | 2019-09-11T13:20:15 | 207,811,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,177 | ino | #include "Joystick.h"
//可変抵抗をつなげるpin
const int x_pin = A0;
const int y_pin = A1;
//L3ボタン(11ボタン)に該当するジョイスティック押し込み
const int L3 = 10;
//可変抵抗の値
int x_value = 0;
int y_value = 0;
//AJLクラスオブジェクト
Joystick_ Joystick;
void setup() {
// put your setup code here, to run once:
//AJLの初期化
Joystick.begin(true);
Joystick.setXAxisRange(267,771);//519が中間値になるように設定
Joystick.setYAxisRange(262,766);//514が中間値になるように設定
//L3に該当するボタン
Joystick.setButton(L3,0);
}
void loop() {
// put your main code here, to run repeatedly:
//ジョイスティックの可変抵抗値読み取り
x_value = analogRead(x_pin);//norm 519 MAX 771(right) min 251(left) push 1023
y_value = analogRead(y_pin);//norm 514 MAX 778(under) min 244(top)
if(x_value != 1023){
//L3ボタン解除
Joystick.releaseButton(L3);
//ジョイスティック値設定
Joystick.setXAxis(x_value);
Joystick.setYAxis(y_value);
}else{
//L3ボタン押下
Joystick.pressButton(L3);
}
delay(50);
}
| [
"singu222@yahoo.co.jp"
] | singu222@yahoo.co.jp |
a1ad1466126fa883c6c25f9dee80e25e33c45854 | 5b6e799b87623ff72581fc461734f5c6b303590f | /Test/MainTest.cpp | 38a5a552f154547bf750ce84ce2362a7ec67fb39 | [] | no_license | yumingqiao/CSE231_Project | 11d9d080e1a6ec30a0ea51d85672d004cfb1c4a1 | 6d0120e705612f61a64b75c9ce5736a4e22dba14 | refs/heads/master | 2022-01-11T16:46:06.208658 | 2019-01-23T23:59:34 | 2019-01-23T23:59:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 243 | cpp | #include <iostream>
int foo(volatile unsigned a) {
volatile unsigned x = 10;
if (a > 5)
x = x + 5;
else
x = x + 50;
return x+a;
}
int main() {
foo (0);
std::cerr << "==================== \n";
foo (100);
return 0;
}
| [
"qym316@gmail.com"
] | qym316@gmail.com |
dbdc9d2b17f04497f4b3c1a7f170aac2f856baf8 | b775857ef7568befda885d4785c1634a64ec1d05 | /4_textures/GLwindow.h | 729c7f378bb268520c047683e9ef6de7996f63d7 | [] | no_license | chen1180/QT_opengl_test | 4eb24a93101ba05171ffa5f16554a643d0a786c0 | 7fbd620209cfba8900701ca7fb65d7d42c15a11e | refs/heads/master | 2020-08-03T07:33:48.006935 | 2019-10-06T18:37:42 | 2019-10-06T18:37:42 | 211,670,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | h | #ifndef GLWINDOW_H
#define GLWINDOW_H
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include<QOpenGLShader>
#include<QOpenGLShaderProgram>
#include<QOpenGLTexture>
#include<QString>
#include<QTime>
class MyGLwidget:public QOpenGLWidget,protected QOpenGLFunctions
{
private:
QTime timer;
QOpenGLShader *m_VertexShader;
QOpenGLShader *m_FragmentShader;
QOpenGLShaderProgram *m_Program;
QOpenGLTexture *textureID;
GLuint VertexArrayID;
GLuint vertexbuffer;
// This will identify our color buffer
GLuint uvbuffer;
GLuint programID;
protected:
GLuint LoadShaders(QString vertexShaderFile,QString fragmentShaderFile);
void initializeGL();
void paintGL();
void loadGLTextures();
};
#endif // GLWINDOW_H
| [
"35698504+chen1180@users.noreply.github.com"
] | 35698504+chen1180@users.noreply.github.com |
eaade4f9631b4a05157bce1ccdfe2009e715696f | 6f1efe2a7b73bab69597884fa09fd332346f020a | /angel3/AngelCore/lib.cpp | 39e42e1314d4e2b9de450ecc31f6429ee2155ddf | [] | no_license | johnconnorgdream/ANGEL | 86c516b68dad6b877ec0dbcbfb3823b273c4f13b | 3f0247df36263dc96b0be2b16febf7f6d880d678 | refs/heads/master | 2023-08-31T14:49:57.956225 | 2023-08-26T03:47:53 | 2023-08-26T03:47:53 | 203,399,895 | 4 | 2 | null | null | null | null | GB18030 | C++ | false | false | 8,948 | cpp | #include <stdlib.h>
#include <time.h>
#include "parse.h"
#include "lib.h"
#include "hash.h"
#include "execute.h"
#include "compilerutil.h"
#include "util.h"
#include "shell.h"
#include "amem.h"
#include "../Extension/initext.h"
//这个模块不能出现具体的类型
//这种动态添加常量会导致
object_set global_func_map,array_func_map,bytes_func_map,
string_func_map,set_func_map,dict_func_map,regular_func_map;
extern linkcollection global_scope,global_current_scope;
/*
系统库函数
*/
object systype(object o)
{
return (object)CONST(gettypedesc(o));
}
object sysset(object init)
{
object_set ret = initset();
if(ISNOTYPE(init))//表示此时是默认参数
return (object)ret;
else if(ISLIST(init))
{
translisttoset(ret, GETLIST(init));
}
else if(ISRANGE(init))
{
transrangetoset(ret,GETRANGE(init));
}
else
{
angel_error("function[list] argument 1 must be integer");
return GETNULL;
}
return (object)ret;
}
object syslist(object o,object init)
{
ARG_CHECK(o,INT,"list",1)
if(ISNOTYPE(init))//表示此时是默认参数
init = INTCONST(0);
object_list res = initarray(GETINT(o));
for(int i = 0; i<res->alloc_size; i++)
{
addlist(res,init);
}
return (object)res;
}
object sysprint(object o)
{
char *buf;
if(o->type!=STR)
{
_print(o);
}
else //格式化输出字符串
{
char *print = tonative(GETSTR(o));
angel_out(print);
free(print);
}
return GETNULL;
}
object sysprintl(object o)
{
//涉及到io操作的不要用锁
//critical_enter();
sysprint(o);
angel_out("\n");
//critical_leave();
return GETNULL;
}
object sysscan()
{
char s[read_base_size];
scanf("%s",s);
return (object)initstring(s);
}
object sysid(object o)
{
return (object)initinteger((long)o);
}
object sysaddr(object valuename, object funname, object o)
{
linkcollection link;
ARG_CHECK(valuename,STR,"addr",1);
char *value = tonative(GETSTR(valuename));
if(!ISNOTYPE(funname))
{
char *funn = tonative(GETSTR(funname));
if(!ISSTR(funname))
{
angel_error("addr函数的第二个参数必须是字符串类型!");
return GETNULL;
}
fun f;
if(!ISNOTYPE(o))
f = getobjmemfun(o,funn);
else
f = getglobalfun(funn);
link = f->local_scope;
free(funn);
}
else
{
link = global_scope;
}
object_list ret = initarray();
linkcollection head = link;
for(linkcollection p = link->next; p != head; p = p->next)
{
object_set map = (object_set)p->data;
if(!map) continue ;
int offset;
if(-1 != (offset = getoffset(map,value)))
_addlist(ret,(object)initinteger(offset));
}
free(value);
return (object)ret;
}
object sysheap()
{
object_dict dict = initdictionary();
_adddict(dict,(object)CONST("data"),(object)initfloat((double)get_data_heap()->free_size / get_data_heap()->total_size));
_adddict(dict,(object)CONST("object"),(object)initfloat((double)get_object_heap()->free_size / get_object_heap()->total_size));
return (object)dict;
}
object sysref(object o)
{
return (object)initinteger(o->refcount);
}
object syshash(object o)
{
return (object)initinteger(globalhash(o));
}
object sysregular(object s)
{
ARG_CHECK(s,STR,"regular",1);
object_regular res = are_compile((wchar *)GETSTR(s)->s);
return (object)res;
}
//系统函数不打算用类的形式提供,所以需要考虑系统资源表示数目问题
angel_buildin_func angel_build_in_def[] =
{
{"type",systype,1,0,0},
{"list",syslist,2,1,0},
{"set",sysset,1,1,0},
{"print",sysprint,1,0,0},
{"printl",sysprintl,1,0,0},
{"scan",sysscan,0,0,0},
{"id",sysid,1,0,0},
{"addr",sysaddr,3,2,0},
{"heap",sysheap,0,0,0},
{"ref",sysref,1,0,0},
{"hash",syshash,1,0,0},
{"regular",sysregular,1,0,0},
/*
文件操作
*/
{"fopen",sysfopen,2,0,0},
{"fread",sysfread,1,0,0},
{"fgets",sysfgets,1,0,0},
{"fwrite",sysfwrite,1,0,0},
{"fclose",sysfclose,1,0,0},
{"finfo",sysfinfo,1,0,0},
{"fls",sysfls,1,0,0},
/*
格式化解析
*/
{"parse",sysparse,2,0,0},
/*
时间类
*/
{"clock",sysclock,1,1,0},
{"sleep",syssleep,2,1,0},
/*
线程相关
*/
{"startthread",sysstartthread,4,2,0},
/*
网络相关
*/
{"netname",sysnetname,1,1,0},
{"netaddr",sysnetaddr, 2,2,0},
{"socket",syssocket, 1,0,0},
{"bind",sysbind, 2,0,0},
{"listen",syslisten,2,1,0},
{"accept",sysaccept,2,0,0},
{"connect",sysconnect,2,0,0},
{"recv",sysrecv,2,0,0},
{"send",syssend,2,0,0},
{"sclose",syssclose,1,0,0},
{"socketopt",syssocketopt,2,1,0},
{NULL,NULL,0,0}
};
/*
成员库函数
*/
angel_buildin_func angel_array_func_def[] =
{
{"size",syssize_list,1,0,0},
{"add",sysadd_list,2,0,0},
{"extend",sysextend_list,2,0,0},
{"pop",syspop_list,1,0,0},
{NULL,NULL,0,0}
};
angel_buildin_func angel_set_func_def[] =
{
{"size",syssize_set,1,0,0},
{"add",sysadd_set,2,0,0},
{"isexist",sysisexist_set,2,0,0},
{"remove",sysremove_set,2,0,0},
{NULL,NULL,0,0}
};
angel_buildin_func angel_dict_func_def[] =
{
{"size",syssize_dict,1,0,0},
{"iskey",sysiskey_dict,2,0,0},
{"keys",syskeys_dict,1,0,0},
{NULL,NULL,0,0}
};
angel_buildin_func angel_string_func_def[] =
{
{"size",syssize_string,1,0,0},
{"bytes",sysbytes_string,1,0,0},
{"join",sysjoin_string,2,0,0},
{"upper",sysupper_string,1,0,0},
{"lower",syslower_string,1,0,0},
{"find",sysfind_string,3,1,0},
{"findall",sysfindall_string,3,1,0},
{"match",sysmatch_string,3,1,0},
{"tonum",sysnum_string,1,0,0},
{NULL,NULL,0,0}
};
angel_buildin_func angel_bytes_func_def[] =
{
{"size",syssize_bytes,1,0,0},
{"str",sysstr_bytes,1,0,0},
{NULL,NULL,0,0}
};
angel_buildin_func angel_regular_func_def[] =
{
{"code",syscode_regular,1,0,0},
{NULL,NULL,0,0}
};
void build_sys_func_map(object_set lib_function_map,angel_buildin_func lib_fun[])
{
int i=0;
angel_buildin_func func = lib_fun[i];
while(func.name)
{
if(!addmap(lib_function_map,func.name,i++))
{
angel_error("编译出错:系统内置函数定义重复");
return ;
}
func = lib_fun[i];
}
}
void init_lib_func_map()
{
initexttype();
global_func_map = init_perpetual_set();
bytes_func_map = init_perpetual_set();
string_func_map = init_perpetual_set();
array_func_map = init_perpetual_set();
set_func_map = init_perpetual_set();
dict_func_map = init_perpetual_set();
regular_func_map = init_perpetual_set();
build_sys_func_map(global_func_map,angel_build_in_def);
build_sys_func_map(array_func_map,angel_array_func_def);
build_sys_func_map(set_func_map,angel_set_func_def);
build_sys_func_map(dict_func_map,angel_dict_func_def);
build_sys_func_map(string_func_map,angel_string_func_def);
build_sys_func_map(bytes_func_map,angel_bytes_func_def);
build_sys_func_map(regular_func_map,angel_regular_func_def);
}
int issysfunbyname(char *funname)
{
int i=0;
return -1;
}
int _issysfun(fun f,object_set lib_function_map)
{
int offset = getoffset(lib_function_map,f->name);
if(offset == -1)
return 0;
angel_buildin_func fun = angel_build_in_def[offset];
if(f->paracount - f->default_paracount <= fun.argcount && fun.argcount <= f->paracount)
return 1;
return 0;
}
int issysfun(fun f)
{
return _issysfun(f,global_func_map);
}
int issyscall(char *funname,int count,angel_buildin_func libfun[],object_set lib_function_map)
{
int offset = getoffset(lib_function_map,funname);
angel_buildin_func fun = libfun[offset];
if(count == -1) //表示此时只是向获取同名库函数
return offset;
if(offset == -1)
return -1;
if(isparamvalid(fun.argcount,fun.argdefaultcount,count))
return offset;
return -1;
}
int isglobalsyscall(char *funname,int count)
{
return issyscall(funname,count,angel_build_in_def,global_func_map);
}
angel_buildin_func *getglobalsyscall(char *funname,int count)
{
int index = isglobalsyscall(funname,count);
if(index == -1)
return NULL;
return &angel_build_in_def[index];
}
angel_buildin_func *getsysmembercall(object o,char *funname,int count)
{
angel_buildin_func *witch;
object_set map;
switch(o->type)
{
case BYTES:
witch = angel_bytes_func_def;
map = bytes_func_map;
break ;
case STR:
witch = angel_string_func_def;
map = string_func_map;
break ;
case LIST:
witch = angel_array_func_def;
map = array_func_map;
break ;
case SET:
witch = angel_set_func_def;
map = set_func_map;
break ;
case DICT:
witch = angel_dict_func_def;
map = dict_func_map;
break ;
case REGULAR:
witch = angel_regular_func_def;
map = regular_func_map;
break ;
default:
angel_error("目前调试阶段还不支持一般类型的成员函数!");
return NULL;
}
int index = issyscall(funname,count,witch,map);
if(index == -1)
return NULL;
return &witch[index];
}
int checkrangeparam(object range,int size,int *res)
{
int begin,end;
if(ISNOTYPE(range))
{
begin = 0;
end = size;
}
else if(ISRANGE(range))
{
begin = GETRANGE(range)->begin > 0 ? GETRANGE(range)->begin : 0;
end = GETRANGE(range)->end < size ? GETRANGE(range)->end : size;
}
else
{
return 0;
}
res[0] = begin;
res[1] = end;
return 1;
} | [
"johnconnorgdream@gmail.com"
] | johnconnorgdream@gmail.com |
fce3b9caff302287435f9881e796260c5ed33d5f | 62407f38e4dd4efca34bf264949bcd42f5ee6164 | /apps/myApps/myTUIOExample/src/Ball.cpp | d9173fdde6576c406a15dbffb50bd51497fb0144 | [] | no_license | YoonSung/openframeworks | a1802b1ea031e79c1db9e851139077e3f7960854 | 0799cca8149e228a05f93a520a0aa3579466d948 | refs/heads/master | 2016-09-06T12:47:32.062741 | 2014-09-06T07:59:49 | 2014-09-06T07:59:49 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 3,257 | cpp | #include "ofMain.h"
#include "Ball.h"
#include <stdlib.h>
#include <math.h>
Ball::Ball(std::array<Ball*, BALL_NUMBER>* ballList, unsigned int idx, float x, float y)
{
// tuio에서 받은 x, y값은 화면에 대한 백분율값이므로
// 화면 크기만큼을 곱해서 해당하는 위치의 픽셀값을 구함
m_Position.x = x * WINDOW_WIDTH;
m_Position.y = y * WINDOW_HEIGHT;
// 맨 처음에 생성될 때 ball의 크기
m_Radius = 50.0f;
// 생성될 때는 움직이지 않음 (터치 이벤트가 종료되면 이동)
m_Velocity.x = 0.0f;
m_Velocity.y = 0.0f;
m_BallList = ballList;
m_Idx = idx;
// 터치 이벤트가 유지되는 동안 ball의 색을 변화시키기 위해서 사용되는
// 색 리스트 생성
m_colorList[0].r = 30;
m_colorList[0].g = 153;
m_colorList[0].b = 197;
m_colorList[1].r = 196;
m_colorList[1].g = 15;
m_colorList[1].b = 132;
m_colorList[2].r = 204;
m_colorList[2].g = 232;
m_colorList[2].b = 36;
m_colorList[3].r = 78;
m_colorList[3].g = 183;
m_colorList[3].b = 153;
m_colorList[4].r = 255;
m_colorList[4].g = 102;
m_colorList[4].b = 0;
m_ColorIdx = 0;
m_IsChanging = false;
}
Ball::~Ball(void)
{
}
void Ball::init()
{
// 터치 이벤트가 종료될 때까지 크기와 색 변화를 주기위한 flag 설정
m_IsChanging = true;
}
void Ball::setVelocity()
{
// 임의의 방향으로 속도 부여
m_Velocity.x = static_cast<float>(rand() ) / (RAND_MAX / 2) - 1.0f;
m_Velocity.y = static_cast<float>(rand() ) / (RAND_MAX / 2) - 1.0f;
}
void Ball::update()
{
// 만약 아직 터치 이벤트가 종료되지 않으며 ball의 속성을 변경시킴
if (m_IsChanging)
changeBallProperties();
// 현재 속도만큼 화면에서 이동
m_Position += m_Velocity;
}
void Ball::draw()
{
// 화면에 ball을 그림
// 이때 ball의 색은 현재 ball의 m_ColorIdx에 해당하는 색으로 선택
// m_ColorIdx는 float형이지만 강제캐스팅을 통해서 소숫점 값은 버리고 계산 - 색 변화 속도와 관련
ofSetColor(m_colorList[static_cast<unsigned int>(m_ColorIdx) % COLOR_NUMBER]);
ofCircle(m_Position.x, m_Position.y, m_Radius);
}
void Ball::changeBallProperties()
{
// ball의 크기 증가
m_Radius += 0.5;
// ball의 색 변화
// idx를 0.1씩 증가시키는 이유는 너무 빠른 색 변화를 막기 위함
// 1씩 증가시키면 ball의 색이 별 먹은 마리오처럼 보임
m_ColorIdx += 0.1f;
}
void Ball::stopIncreasing()
{
m_IsChanging = false;
}
void Ball::checkBoundary()
{
// ball의 왼쪽 끄트머리가 화면 왼쪽 을 넘어가는지 확인
// 만약 넘어가는 상황이면 x축 방향의 운동 방향을 반대로 바꾸고
// ball의 위치는 화면 왼쪽 끝으로 설정
if (m_Position.x - m_Radius < 0)
{
m_Velocity.x *= -1;
m_Position.x = m_Radius;
}
// 위와 같은 작업을 나머지 화면 모서리에 대해서도 진행
else if (m_Position.x + m_Radius > WINDOW_WIDTH)
{
m_Velocity.x *= -1;
m_Position.x = WINDOW_WIDTH - m_Radius;
}
if (m_Position.y - m_Radius < 0)
{
m_Velocity.y *= -1;
m_Position.y = m_Radius;
}
else if (m_Position.y + m_Radius > WINDOW_HEIGHT)
{
m_Velocity.y *= -1;
m_Position.y = WINDOW_HEIGHT - m_Radius;
}
} | [
"lvev9925@naver.com"
] | lvev9925@naver.com |
90ec670b7058266c2b3e79d13152d784f3d7afb4 | ea99f10cdcf7ebfb77f52850c35ff0528f231800 | /src/ofApp.cpp | 7626deb60eac1ca7995f375f28ea9e84515c82e2 | [] | no_license | m0rya/FractalObj3D | 76abca7e84a63d6ff36ca609c8267a4255d96ee5 | f4a4190e33c548bd5a83a5e7d19e3c0eedc94818 | refs/heads/master | 2021-01-18T23:16:09.645977 | 2017-04-24T17:53:24 | 2017-04-24T17:53:24 | 86,727,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,041 | cpp | #include "ofApp.h"
int num_recursion = 3;
RectDivision3D rD(600, 30, 400, num_recursion);
Koch3D koch3d(num_recursion, 300);
makeStl stl("outputFile.stl");
ofVec3f point[3];
ofVec3f lightPos;
pythagorasTree3D pyTree(100, 5, &stl);
Superposition sp(3, 100, 50);
HexFractal hf(5, 100);
truncatedTetrahedron tt(200);
Triakis trks(200);
Tetrakis ttrks(200);
//GUI
int theme = 9;
int drawMode = 3;
GUI_Koch3D gui_koch(koch3d);
GUI_pythagorasTree3D gui_pyTree(pyTree);
GUI_Superposition gui_sp(sp);
GUI_HexFractal gui_hf(hf);
GUI_truncatedTetrahedron gui_tt(tt);
GUI_Triakis gui_trks(trks);
GUI_Tetrakis gui_ttrks(ttrks);
GUIBase *guiArray[] = {&gui_koch, &gui_pyTree, &gui_sp, &gui_hf, &gui_tt, &gui_trks, &gui_ttrks};
ofxUISuperCanvas *fractalList;
ofxUIDropDownList *ddl;
//Picture
ofImage myImage;
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
ofBackground(0);
ofEnableDepthTest();
ofEnableSmoothing();
ofSetFrameRate(24);
//lighting
pointlight.setSpotlight();
pointlight.setDirectional();
pointlight.setAmbientColor(ofFloatColor(0.5, 0.2, 0.2, 1.0));
pointlight.setDiffuseColor(ofFloatColor(.86, .85, .55));
pointlight.setSpecularColor(ofFloatColor(1.f, 1.f, 1.f));
lightPos = ofVec3f(-40, 60, 600);
pointlight.setPosition(lightPos);
pointlight.enable();
anotherLight.setDirectional();
anotherLight.setAmbientColor(ofFloatColor(0.5, 0.2, 0.2, 1.0));
anotherLight.setDiffuseColor(ofFloatColor(.36, .35, .35));
anotherLight.setSpecularColor(ofFloatColor(.5f, .5f, .5f));
anotherLight.setPosition(-1*lightPos);
anotherLight.enable();
//setting for Koch3D
koch3d.setNoiseForTopPoint(true);
koch3d.setStlFile(&stl);
koch3d.setTypeOfObject("octa");
//setting for pythagoras Tree
pyTree.initRecursion();
//seting for Superposition
sp.calcMesh();
//sp.setStlFile(&stl);
//setting for HexFractal
hf.initRecursion();
hf.setStlFile(&stl);
//TT
tt.calcMesh();
tt.setStl(&stl);
//trks
trks.setStl(&stl);
//ttrks
ttrks.setStl(&stl);
//GUI ddl
fractalList = new ofxUISuperCanvas("Fractal List");
fractalList->addSpacer();
vector<string> names;
names.push_back("Koch3D");
names.push_back("PythagorasTree3D");
names.push_back("Superposition");
names.push_back("HexFractal");
names.push_back("TruncatedTetrahedron");
names.push_back("Triakis");
names.push_back("Tetrakis");
fractalList->setWidgetFontSize(OFX_UI_FONT_SMALL);
ddl = fractalList->addDropDownList("Fractal List", names);
ddl->setColorPadded(ofColor(0));
ddl->setAutoClose(true);
ddl->setShowCurrentSelected(true);
fractalList->autoSizeToFitWidgets();
ofAddListener(fractalList->newGUIEvent, this, &ofApp::guiEvent_ddl);
fractalList->setVisible(false);
fractalList->setTheme(theme);
for(int i=0; i<sizeof(guiArray)/sizeof(guiArray[0]); i++){
guiArray[i]->setGUI();
}
/*
//exp
exp.setup(ofGetWidth(), ofGetHeight(), 24);
exp.setOutputDir("out");
exp.setOverwriteSequence(true);
exp.setAutoExit(true);
//exp.startExport();
*/
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
//exp.begin();
ofBackground(0);
ofEnableDepthTest();
ofEnableLighting();
pointlight.enable();
//anotherLight.enable();
cam.begin();
ofSetColor(ofColor(255));
//ofDrawSphere(lightPos, 10);
//ofDrawSphere(-1*lightPos, 10);
//tree.draw();
//test.draw();
//rD.draw();
if(!guiArray[drawMode]->gui->isEnabled())
guiArray[drawMode]->gui->enable();
guiArray[drawMode]->draw();
//cout << drawMode << endl;
cam.end();
/*
exp.end();
exp.draw(0, 0);
*/
}
//--------------------------------------------------------------
void ofApp::exit(){
delete fractalList;
}
void ofApp::guiEvent_ddl(ofxUIEventArgs &e){
string name = e.widget->getName();
if(name == "Fractal List"){
ofxUIDropDownList *ddllist = (ofxUIDropDownList *)e.widget;
vector<ofxUIWidget *> &selected = ddllist->getSelected();
if(selected.size() == 1){
if(selected[0]->getName() == "Koch3D"){
guiArray[drawMode]->gui->disable();
drawMode = 0;
}else if(selected[0]->getName() == "PythagorasTree3D"){
guiArray[drawMode]->gui->disable();
drawMode = 1;
}else if(selected[0]->getName() == "Superposition"){
guiArray[drawMode]->gui->disable();
drawMode = 2;
}else if(selected[0]->getName() == "HexFractal"){
guiArray[drawMode]->gui->disable();
drawMode = 3;
}else if(selected[0]->getName() == "TruncatedTetrahedron"){
guiArray[drawMode]->gui->disable();
drawMode = 4;
}else if(selected[0]->getName() == "Triakis"){
guiArray[drawMode]->gui->disable();
drawMode = 5;
}else if(selected[0]->getName() == "Tetrakis"){
guiArray[drawMode]->gui->disable();
drawMode = 6;
}
}
}
}
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
if(key == OF_KEY_UP){
num_recursion += 1;
//test.setNumRecursion(num_recursion);
//rD.setNumRecursion(num_recursion);
pyTree.setNumRecursion(num_recursion);
}else if(key == OF_KEY_DOWN){
num_recursion -= 1;
//test.setNumRecursion(num_recursion);
//rD.setNumRecursion(num_recursion);
pyTree.setNumRecursion(num_recursion);
}else if(key == 'a'){
lightPos.x += 20;
}else if(key == 'z'){
lightPos.x -= 20;
}else if(key == 's'){
lightPos.y += 20;
}else if(key == 'x'){
lightPos.y -= 20;
}else if(key == 'd'){
lightPos.z += 20;
}else if(key == 'c'){
lightPos.z -= 20;
}else if(key == 'o'){
koch3d.outputStlFile();
pyTree.outputStl();
}else if(key == 't'){
myImage.grabScreen(0, 0, ofGetWidth(), ofGetHeight());
string imgName = ofToString(ofGetFrameNum());
imgName += ".png";
myImage.saveImage(imgName, OF_IMAGE_QUALITY_BEST);
}else if(key == '1'){
exp.startExport();
}
pointlight.setPosition(lightPos);
cout << lightPos << endl;
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
if(!fractalList->isHit(x, y)){
fractalList->setVisible(false);
}
if(button == 2){
fractalList->setPosition(x,y);
fractalList->setVisible(true);
}
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| [
"s14512rt@sfc.keio.ac.jp"
] | s14512rt@sfc.keio.ac.jp |
e0eeb2d1cb5ed9c56462cf30dbc343a40005d8a7 | 332a2299cc77116246e874a22cf1743a802159da | /ext/box2d/include/Collision/Shapes/b2CircleShape.h | 11c192a83e7e3826ac556362e390486d8c995bff | [] | no_license | beardface/wii-physics | 07dcb22395bf0307b6c5eb862637f27a0fff453d | d7826fecfdcffa0dfc5529fd3ff067d83f681ab5 | refs/heads/master | 2021-08-19T17:15:54.709814 | 2017-11-27T02:05:15 | 2017-11-27T02:05:15 | 112,114,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,432 | 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_CIRCLE_SHAPE_H
#define B2_CIRCLE_SHAPE_H
#include "b2Shape.h"
/// This structure is used to build circle shapes.
struct b2CircleDef : public b2ShapeDef
{
b2CircleDef()
{
type = e_circleShape;
localPosition.SetZero();
radius = 1.0f;
}
b2Vec2 localPosition;
float32 radius;
};
/// A circle shape.
class b2CircleShape : public b2Shape
{
public:
/// @see b2Shape::TestPoint
bool TestPoint(const b2XForm& transform, const b2Vec2& p) const;
/// @see b2Shape::TestSegment
b2SegmentCollide TestSegment( const b2XForm& transform,
float32* lambda,
b2Vec2* normal,
const b2Segment& segment,
float32 maxLambda) const;
/// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2XForm& transform) const;
/// @see b2Shape::ComputeSweptAABB
void ComputeSweptAABB( b2AABB* aabb,
const b2XForm& transform1,
const b2XForm& transform2) const;
/// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData) const;
/// Get the local position of this circle in its parent body.
const b2Vec2& GetLocalPosition() const;
/// Get the radius of this circle.
float32 GetRadius() const;
private:
friend class b2Shape;
b2CircleShape(const b2ShapeDef* def);
void UpdateSweepRadius(const b2Vec2& center);
// Local position in parent body
b2Vec2 m_localPosition;
float32 m_radius;
};
inline const b2Vec2& b2CircleShape::GetLocalPosition() const
{
return m_localPosition;
}
inline float32 b2CircleShape::GetRadius() const
{
return m_radius;
}
#endif
| [
"justin.hawkins@gmail.com"
] | justin.hawkins@gmail.com |
4f7b1ebc2f06ea45e7d58a9c1b53e297568c963d | b323b51b80458413e43a736960988491d12fec59 | /SoulKnight/Classes/MovingActor/Buff.h | c6e4c2444b629307bce006bf1594c7c00ba26a79 | [] | no_license | Shankfizz/Roguelike-teamwork | 03f153a6ed9978c7f3d06e99a6e84b7242012b3b | 9c245208285adfeafa9af97ff5a059b919b17b08 | refs/heads/master | 2022-11-05T08:54:33.973059 | 2020-06-21T14:29:52 | 2020-06-21T14:29:52 | 263,800,751 | 0 | 0 | null | 2020-05-14T03:01:14 | 2020-05-14T03:01:13 | null | GB18030 | C++ | false | false | 889 | h | #pragma once
#ifndef __BUFF_H__
#define __BUFF_H__
#include "cocos2d.h"
USING_NS_CC;
enum BuffType
{
VERTIGO, //眩晕
FROZEN, //冰冻
BURN, //灼烧
POISON, //中毒
SPEEDUP, //加速
SPEEDDOWN //减速
};
//捡药瓶可归于buff类中
class Buff :public cocos2d::Sprite
{
//CC_SYNTHESIZE(int, hp, HP);
//CC_SYNTHESIZE(float, buffMoveSpeed, BuffMoveSpeed);
CC_SYNTHESIZE(int, hp, HP); //血瓶效果,烧伤,中毒
CC_SYNTHESIZE(int, mp, MP); //魔瓶效果 能量药瓶效果
CC_SYNTHESIZE(float, buffMoveSpeed, BuffMoveSpeed); //移动速度效果 增益/减益 ,冰冻,眩晕
CC_SYNTHESIZE(float, duration, Duration); //持续时间
CC_SYNTHESIZE(float, beginTime, BeginTime); //开始时间
CC_SYNTHESIZE(float, endTime, EndTime); //结束时间
};
#endif // !__BUFF_H__
| [
"realsad@126.com"
] | realsad@126.com |
66ca573826d4e6f44011c43cd84ea38383df69f7 | 56bb77bed7acd71e0fd57163d9acd21e3c7d3849 | /Notes/CStrings/CStrings1.cpp | 0aae98ea2e05fa5533512869b3c8897b8352bd30 | [] | no_license | Zachary-Rust/ZacharyRust-CSCI20-Fall2017 | e2cf71c93a13c199032f92289167fff027d9c497 | a8cd015ce6ad0315361d43d6955944f5ed40e268 | refs/heads/master | 2021-01-19T18:22:23.396644 | 2017-12-13T01:11:52 | 2017-12-13T01:11:52 | 101,127,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | cpp | #include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char name[20] = "Jane";
} | [
"zrust001@student.butte.edu"
] | zrust001@student.butte.edu |
4437b7d9d37cbd30eed783458355f57fd3a31084 | e095c6b8f3d7c8aeac9628ceb9f776f37811ea36 | /HandlerMC/ManualDlg.cpp | 28ff328a721b1dde015ee021a479e84ec22ddb97 | [] | no_license | dangquang95/Handler_MC_SS | 3dc16ba78ef594d16ca18a802db26ccffad201bd | c70a78878ecd102b3fb627cf156d9998eb04b21d | refs/heads/master | 2022-11-25T11:46:42.045391 | 2020-07-28T02:49:19 | 2020-07-28T02:49:19 | 283,078,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,381 | cpp | // ManualDlg.cpp : implementation file
//
#include "stdafx.h"
#include "HandlerMC.h"
#include "ManualDlg.h"
#include "afxdialogex.h"
#define SetON 200
#define SetOFF 10
// ManualDlg dialog
IMPLEMENT_DYNAMIC(ManualDlg, CDialogEx)
ManualDlg::ManualDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_MANUAL_MAIN_FORM, pParent)
{
}
ManualDlg::~ManualDlg()
{
}
void ManualDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_FORWARD_CHECK, m_ReadyForwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_BACKWARD_CHECK, m_ReadyBackwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK, m_AlignForwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD_CHECK, m_AlignBackwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK2, m_StackForwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD_CHECK2, m_StackBackwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK3, m_RotationForwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD_CHECK3, m_RotationBackwardLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK4, m_ConveyorRunLoading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_FORWARD_CHECK4, m_ReadyForwardLoading2);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_FORWARD_CHECK5, m_ReadyBackwardLoading2);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_FORWARD_CHECK2, m_ReadyForwardUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_BACKWARD_CHECK4, m_ReadForwardUnloading2);////
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_BACKWARD_CHECK2, m_ReadyBackwardUnloading);//
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_BACKWARD_CHECK5, m_ReadBackwardUnloading2);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK5, m_AlingnForwardUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD_CHECK4, m_AlineBackWardUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK6, m_StackForwardUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD_CHECK5, m_StackBackwardUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK7, m_RotationForwardUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD_CHECK6, m_RotationBackwardUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK8, m_ConveyorRunUnloading);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_READY_BACKWARD_CHECK3, m_Tool1RobotUp);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK9, m_VaccumTool1RobotOn);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD_CHECK8, m_Tool2RobotUp);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK11, m_VaccumTool2RobotOn);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK13, m_Tool3RobotUp);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK18, m_Tool4RobotUp);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK14, m_VaccumTool3RobotOn);
DDX_Control(pDX, IDB_WORKTRAY_LOADER_ALIGN_FORWARD_CHECK19, m_VaccumTool4RobotOn);
DDX_Control(pDX, IDB_SENSOR_FORWARD_1, m_SensorForward1);
DDX_Control(pDX, IDB_SENSOR_FORWARD_2, m_SensorForward2);
DDX_Control(pDX, IDB_SENSOR_FORWARD_3, m_SensorForward3);
DDX_Control(pDX, IDB_SENSOR_FORWARD_4, m_SensorForward4);
DDX_Control(pDX, IDB_SENSOR_BACKWARD_1, m_SensorBackward1);
DDX_Control(pDX, IDB_SENSOR_BACKWARD_2, m_SensorBackward2);
DDX_Control(pDX, IDB_SENSOR_BACKWARD_3, m_SensorBackward3);
DDX_Control(pDX, IDB_SENSOR_BACKWARD_4, m_SensorBackward4);
DDX_Control(pDX, IDB_SENSOR_UP_1, m_SensorUp1);
DDX_Control(pDX, IDB_SENSOR_UP_2, m_SensorUp2);
DDX_Control(pDX, IDB_SENSOR_UP_3, m_SensorUp3);
DDX_Control(pDX, IDB_SENSOR_UP_4, m_SensorUp4);
DDX_Control(pDX, IDB_SENSOR_VACCUM_1, m_SensorVaccum1);
DDX_Control(pDX, IDB_SENSOR_VACCUM_2, m_SensorVaccum2);
DDX_Control(pDX, IDB_SENSOR_VACCUM_3, m_SensorVaccum3);
DDX_Control(pDX, IDB_SENSOR_VACCUM_4, m_SensorVaccum4);
}
BEGIN_MESSAGE_MAP(ManualDlg, CDialogEx)
ON_WM_SIZE()
ON_WM_TIMER()
END_MESSAGE_MAP()
// ManualDlg message handlers
BOOL ManualDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
SaveControlPosition();
SetTimer(1, 50, NULL);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void ManualDlg::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
ChangeControlPosition();
}
void ManualDlg::SaveControlPosition()
{
CRect rect;
TCHAR sz[256];
GetClientRect(rect);
m_PositionArray.Add(rect);
CWnd* pWnd = GetTopWindow();
pWnd->GetWindowText(sz, 256);
pWnd->GetWindowRect(rect);
ScreenToClient(rect);
m_PositionArray.Add(rect);
CWnd* tmpWnd = pWnd->GetNextWindow(GW_HWNDNEXT);
while (tmpWnd != NULL)
{
tmpWnd->GetWindowText(sz, 256);
tmpWnd->GetWindowRect(rect);
ScreenToClient(rect);
m_PositionArray.Add(rect);
tmpWnd = tmpWnd->GetNextWindow(GW_HWNDNEXT);
}
}
void ManualDlg::ChangeControlPosition()
{
if (m_PositionArray.GetSize() <= 0)
return;
CRect rect, rect_org;
int i = 0;
rect_org = m_PositionArray.GetAt(i);
i++;
GetClientRect(rect);
double dXRatio = ((double)rect.Width()) / ((double)rect_org.Width());
double dYRatio = ((double)rect.Height()) / ((double)rect_org.Height());
CWnd* pWnd = GetTopWindow();
rect = m_PositionArray.GetAt(i);
i++;
pWnd->MoveWindow((int)(rect.left*dXRatio), (int)(rect.top*dYRatio),
(int)(rect.Width()*dXRatio), (int)(rect.Height()*dYRatio));
CWnd* tmpWnd = pWnd->GetNextWindow(GW_HWNDNEXT);
while (tmpWnd != NULL)
{
rect = m_PositionArray.GetAt(i);
i++;
tmpWnd->MoveWindow((int)(rect.left*dXRatio), (int)(rect.top*dYRatio),
(int)(rect.Width()*dXRatio), (int)(rect.Height()*dYRatio));
tmpWnd = tmpWnd->GetNextWindow(GW_HWNDNEXT);
}
}BEGIN_EVENTSINK_MAP(ManualDlg, CDialogEx)
ON_EVENT(ManualDlg, IDB_INPUT_CHECK, DISPID_CLICK, ManualDlg::ClickInputCheck, VTS_NONE)
ON_EVENT(ManualDlg, IDB_OUTPUT_CHECK, DISPID_CLICK, ManualDlg::ClickOutputCheck, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_READY_FORWARD, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderReadyForward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_READY_BACKWARD, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderReadyBackward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ALIGN_FORWARD, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderAlignForward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderAlignBackward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_STACK_FORWARD, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderStackForward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_STACK_BACKWARD2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderStackBackward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ROTATION_FORWARD, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderRotationForward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ROTATION_BACKWARD, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderRotationBackward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_CONVEYOR_RUN, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderConveyorRun, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_CONVEYOR_STOP, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderConveyorStop, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_READY_FORWARD2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderReadyForward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_READY_BACKWARD2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderReadyBackward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ALIGN_FORWARD2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderAlignForward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ALIGN_BACKWARD3, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderAlignBackward3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_STACK_FORWARD2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderStackForward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_STACK_BACKWARD3, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderStackBackward3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ROTATION_FORWARD2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderRotationForward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_ROTATION_BACKWARD3, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderRotationBackward3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_CONVEYOR_RUN2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderConveyorRun2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_WORKTRAY_LOADER_CONVEYOR_STOP2, DISPID_CLICK, ManualDlg::ClickWorktrayLoaderConveyorStop2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_OPEN_DOOR_FONT_RIGHT, DISPID_CLICK, ManualDlg::ClickOpenDoorFontRight, VTS_NONE)
ON_EVENT(ManualDlg, IDB_CLOSE_DOOR_FRONT_RIGHT, DISPID_CLICK, ManualDlg::ClickCloseDoorFrontRight, VTS_NONE)
ON_EVENT(ManualDlg, IDB_OPEN_DOOR_FRONT_LEFT, DISPID_CLICK, ManualDlg::ClickOpenDoorFrontLeft, VTS_NONE)
ON_EVENT(ManualDlg, IDB_CLOSE_DOOR_FRONT_LEFT, DISPID_CLICK, ManualDlg::ClickCloseDoorFrontLeft, VTS_NONE)
ON_EVENT(ManualDlg, IDB_OPEN_DOOR_SIDE_RIGHT, DISPID_CLICK, ManualDlg::ClickOpenDoorSideRight, VTS_NONE)
ON_EVENT(ManualDlg, IDB_CLOSE_DOOR_SIDE_RIGHT, DISPID_CLICK, ManualDlg::ClickCloseDoorSideRight, VTS_NONE)
ON_EVENT(ManualDlg, IDB_OPEN_DOOR_SIDE_LEFT, DISPID_CLICK, ManualDlg::ClickOpenDoorSideLeft, VTS_NONE)
ON_EVENT(ManualDlg, IDB_CLOSE_DOOR_SIDE_LEFT, DISPID_CLICK, ManualDlg::ClickCloseDoorSideLeft, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL1_ROBOT_DOWN, DISPID_CLICK, ManualDlg::ClickTool1RobotDown, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL1_ROBOT_UP, DISPID_CLICK, ManualDlg::ClickTool1RobotUp, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL1_ROBOT_ON, DISPID_CLICK, ManualDlg::ClickVaccumTool1RobotOn, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL1_ROBOT_OFF, DISPID_CLICK, ManualDlg::ClickVaccumTool1RobotOff, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL2_ROBOT_DOWN, DISPID_CLICK, ManualDlg::ClickTool2RobotDown, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL2_ROBOT_UP, DISPID_CLICK, ManualDlg::ClickTool2RobotUp, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL2_ROBOT_ON, DISPID_CLICK, ManualDlg::ClickVaccumTool2RobotOn, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL2_ROBOT_OFF, DISPID_CLICK, ManualDlg::ClickVaccumTool2RobotOff, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL3_ROBOT_DOWN, DISPID_CLICK, ManualDlg::ClickTool3RobotDown, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL3_ROBOT_UP, DISPID_CLICK, ManualDlg::ClickTool3RobotUp, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL3_ROBOT_ON, DISPID_CLICK, ManualDlg::ClickVaccumTool3RobotOn, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL3_ROBOT_OFF, DISPID_CLICK, ManualDlg::ClickVaccumTool3RobotOff, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL4_ROBOT_DOWN, DISPID_CLICK, ManualDlg::ClickTool4RobotDown, VTS_NONE)
ON_EVENT(ManualDlg, IDB_TOOL4_ROBOT_UP, DISPID_CLICK, ManualDlg::ClickTool4RobotUp, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL4_ROBOT_ON, DISPID_CLICK, ManualDlg::ClickVaccumTool4RobotOn, VTS_NONE)
ON_EVENT(ManualDlg, IDB_VACCUM_TOOL4_ROBOT_OFF, DISPID_CLICK, ManualDlg::ClickVaccumTool4RobotOff, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_FORWARD_1, DISPID_CLICK, ManualDlg::ClickSocketForward1, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_BACKWARD_1, DISPID_CLICK, ManualDlg::ClickSocketBackward1, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_UP_1, DISPID_CLICK, ManualDlg::ClickSocketUp1, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_DOWN_1, DISPID_CLICK, ManualDlg::ClickSocketDown1, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_ON_1, DISPID_CLICK, ManualDlg::ClickSocketVaccumOn1, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_OFF_1, DISPID_CLICK, ManualDlg::ClickSocketVaccumOff1, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_FORWARD_2, DISPID_CLICK, ManualDlg::ClickSocketForward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_BACKWARD_2, DISPID_CLICK, ManualDlg::ClickSocketBackward2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_UP_2, DISPID_CLICK, ManualDlg::ClickSocketUp2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_DOWN_2, DISPID_CLICK, ManualDlg::ClickSocketDown2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_ON_2, DISPID_CLICK, ManualDlg::ClickSocketVaccumOn2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_OFF_2, DISPID_CLICK, ManualDlg::ClickSocketVaccumOff2, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_FORWARD_3, DISPID_CLICK, ManualDlg::ClickSocketForward3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_BACKWARD_3, DISPID_CLICK, ManualDlg::ClickSocketBackward3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_UP_3, DISPID_CLICK, ManualDlg::ClickSocketUp3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_DOWN_3, DISPID_CLICK, ManualDlg::ClickSocketDown3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_ON_3, DISPID_CLICK, ManualDlg::ClickSocketVaccumOn3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_OFF_3, DISPID_CLICK, ManualDlg::ClickSocketVaccumOff3, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_FORWARD_4, DISPID_CLICK, ManualDlg::ClickSocketForward4, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_BACKWARD_4, DISPID_CLICK, ManualDlg::ClickSocketBackward4, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_UP_4, DISPID_CLICK, ManualDlg::ClickSocketUp4, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_DOWN_4, DISPID_CLICK, ManualDlg::ClickSocketDown4, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_ON_4, DISPID_CLICK, ManualDlg::ClickSocketVaccumOn4, VTS_NONE)
ON_EVENT(ManualDlg, IDB_SOCKET_VACCUM_OFF_4, DISPID_CLICK, ManualDlg::ClickSocketVaccumOff4, VTS_NONE)
ON_EVENT(ManualDlg, IDB_OPEN_DOOR_AFTER, DISPID_CLICK, ManualDlg::ClickOpenDoorAfter, VTS_NONE)
ON_EVENT(ManualDlg, IDB_CLOSE_DOOR_AFTER, DISPID_CLICK, ManualDlg::ClickCloseDoorAfter, VTS_NONE)
ON_EVENT(ManualDlg, IDB_ALINE_FORWARD, DISPID_CLICK, ManualDlg::ClickAlineForward, VTS_NONE)
ON_EVENT(ManualDlg, IDB_ALINE_BACKWARD, DISPID_CLICK, ManualDlg::ClickAlineBackward, VTS_NONE)
END_EVENTSINK_MAP()
void ManualDlg::OnTimer(UINT_PTR nIDEvent)
{
switch (nIDEvent)
{
case 1:
ViewSensor();
break;
default:
break;
}
CDialogEx::OnTimer(nIDEvent);
}
void ManualDlg::ViewSensor()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
//Loading
if (pDoc->ReadInput(SSXL_Do_Tray_Loading_Out_Trai)) m_ReadyForwardLoading.SetBackColor(SetON); else m_ReadyForwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Do_Tray_Loading_In_Trai)) m_ReadyBackwardLoading.SetBackColor(SetON); else m_ReadyBackwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Do_Tray_Loading_In_Phai)) m_ReadyBackwardLoading2.SetBackColor(SetON); else m_ReadyBackwardLoading2.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Do_Tray_Loading_Out_Phai)) m_ReadyForwardLoading2.SetBackColor(SetON); else m_ReadyForwardLoading2.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_AlineTray_Loading_Out)) m_AlignForwardLoading.SetBackColor(SetON); else m_AlignForwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_AlineTray_Loading_In)) m_AlignBackwardLoading.SetBackColor(SetON); else m_AlignBackwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Chan_Tray_Loading_Nam)) m_RotationForwardLoading.SetBackColor(SetON); else m_RotationForwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Chan_Tray_Loading_Dung)) m_RotationBackwardLoading.SetBackColor(SetON); else m_RotationBackwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Aline_FW)) m_StackForwardLoading.SetBackColor(SetON); else m_StackForwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Aline_BW)) m_StackBackwardLoading.SetBackColor(SetON); else m_StackBackwardLoading.SetBackColor(SetOFF);
if (pDoc->ReadOutput(Conveyor_Loading)) m_ConveyorRunLoading.SetBackColor(SetON); else m_ConveyorRunLoading.SetBackColor(SetOFF);
//Unloading
//if (pDoc->ReadInput(SSXL_Do_Tray_Unloading_Out_Trai)) m_ReadyForwardUnloading.SetBackColor(SetON); else m_ReadyForwardUnloading.SetBackColor(SetOFF);
// (pDoc->ReadInput(SSXL_Do_Tray_Unloading_In_Trai)) m_ReadyBackwardUnloading.SetBackColor(SetON); else m_ReadyBackwardUnloading.SetBackColor(SetOFF);
//if (pDoc->ReadInput(SSXL_Do_Tray_Unloading_In_Phai)) m_ReadBackwardUnloading2.SetBackColor(SetON); else m_ReadBackwardUnloading2.SetBackColor(SetOFF);
//if (pDoc->ReadInput(SSXL_Do_Tray_Unloading_Out_Phai)) m_ReadForwardUnloading2.SetBackColor(SetON); else m_ReadForwardUnloading2.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_AlineTray_Unloading_Out)) m_AlingnForwardUnloading.SetBackColor(SetON); else m_AlingnForwardUnloading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_AlineTray_Unloading_In)) m_AlineBackWardUnloading.SetBackColor(SetON); else m_AlineBackWardUnloading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Chan_Tray_Unloading_Nam)) m_RotationForwardUnloading.SetBackColor(SetON); else m_RotationForwardUnloading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Chan_Tray_Unloading_Dung)) m_RotationBackwardUnloading.SetBackColor(SetON); else m_RotationBackwardUnloading.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Chot_Stack_Unloading_Out)) m_StackForwardUnloading.SetBackColor(SetON); else m_StackForwardUnloading.SetBackColor(SetOFF);
if (pDoc->ReadInput(Safety_Door_After)) m_StackBackwardUnloading.SetBackColor(SetON); else m_StackBackwardUnloading.SetBackColor(SetOFF);
if (pDoc->ReadOutput(Conveyor_Unloading)) m_ConveyorRunUnloading.SetBackColor(SetON); else m_ConveyorRunUnloading.SetBackColor(SetOFF);
//Robot
if (pDoc->ReadInput(SSXL_Tool1_RobotUp)) m_Tool1RobotUp.SetBackColor(SetON); else m_Tool1RobotUp.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Tool2_RobotUp)) m_Tool2RobotUp.SetBackColor(SetON); else m_Tool2RobotUp.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Tool3_RobotUp)) m_Tool3RobotUp.SetBackColor(SetON); else m_Tool3RobotUp.SetBackColor(SetOFF);
if (pDoc->ReadInput(SSXL_Tool4_RobotUp)) m_Tool4RobotUp.SetBackColor(SetON); else m_Tool4RobotUp.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Tool1_Robot)) m_VaccumTool1RobotOn.SetBackColor(SetON); else m_VaccumTool1RobotOn.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Tool2_Robot)) m_VaccumTool2RobotOn.SetBackColor(SetON); else m_VaccumTool2RobotOn.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Tool3_Robot)) m_VaccumTool3RobotOn.SetBackColor(SetON); else m_VaccumTool3RobotOn.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Tool4_Robot)) m_VaccumTool4RobotOn.SetBackColor(SetON); else m_VaccumTool4RobotOn.SetBackColor(SetOFF);
//Socket
if (pDoc->ReadInput(Socket1_Fw)) m_SensorForward1.SetBackColor(SetON); else m_SensorForward1.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket2_Fw)) m_SensorForward2.SetBackColor(SetON); else m_SensorForward2.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket3_Fw)) m_SensorForward3.SetBackColor(SetON); else m_SensorForward3.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket4_Fw)) m_SensorForward4.SetBackColor(SetON); else m_SensorForward4.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket1_Rv)) m_SensorBackward1.SetBackColor(SetON); else m_SensorBackward1.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket2_Rv)) m_SensorBackward2.SetBackColor(SetON); else m_SensorBackward2.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket3_Rv)) m_SensorBackward3.SetBackColor(SetON); else m_SensorBackward3.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket4_Rv)) m_SensorBackward4.SetBackColor(SetON); else m_SensorBackward4.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket1_Up)) m_SensorUp1.SetBackColor(SetON); else m_SensorUp1.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket2_Up)) m_SensorUp2.SetBackColor(SetON); else m_SensorUp2.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket3_Up)) m_SensorUp3.SetBackColor(SetON); else m_SensorUp3.SetBackColor(SetOFF);
if (pDoc->ReadInput(Socket4_Up)) m_SensorUp4.SetBackColor(SetON); else m_SensorUp4.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Socket_1)) m_SensorVaccum1.SetBackColor(SetON); else m_SensorVaccum1.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Socket_2)) m_SensorVaccum2.SetBackColor(SetON); else m_SensorVaccum2.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Socket_3)) m_SensorVaccum3.SetBackColor(SetON); else m_SensorVaccum3.SetBackColor(SetOFF);
if (pDoc->ReadInput(Vaccum_Socket_4)) m_SensorVaccum4.SetBackColor(SetON); else m_SensorVaccum4.SetBackColor(SetOFF);
}
void ManualDlg::ClickInputCheck()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->FlagInOut = TRUE;
DlgInput ViewDlg;
ViewDlg.DoModal();
}
void ManualDlg::ClickOutputCheck()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->FlagInOut = FALSE;
DlgInput ViewDlg;
ViewDlg.DoModal();
}
void ManualDlg::ClickWorktrayLoaderReadyForward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhDoTrayLoadingOn();
}
void ManualDlg::ClickWorktrayLoaderReadyBackward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhDoTrayLoadingOff();
}
void ManualDlg::ClickWorktrayLoaderAlignForward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhAlineTrayLoadingOn();
}
void ManualDlg::ClickWorktrayLoaderAlignBackward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhAlineTrayLoadingOff();
}
void ManualDlg::ClickWorktrayLoaderStackForward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhChotTrayLoadingOn();
}
void ManualDlg::ClickWorktrayLoaderStackBackward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhChotTrayLoadingOff();
}
void ManualDlg::ClickWorktrayLoaderRotationForward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ChanTrayLoadingOn();
}
void ManualDlg::ClickWorktrayLoaderRotationBackward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ChanTrayLoadingOff();
}
void ManualDlg::ClickWorktrayLoaderConveyorRun()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ConveyorLoadingOn();
}
void ManualDlg::ClickWorktrayLoaderConveyorStop()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ConveyorLoadingOff();
}
//
void ManualDlg::ClickWorktrayLoaderReadyForward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhDoTrayUnloadingOn();
}
void ManualDlg::ClickWorktrayLoaderReadyBackward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhDoTrayUnloadingOff();
}
void ManualDlg::ClickWorktrayLoaderAlignForward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhAlineTrayUnloadingOn();
}
void ManualDlg::ClickWorktrayLoaderAlignBackward3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhAlineTrayUnloadingOff();
}
void ManualDlg::ClickWorktrayLoaderStackForward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhChotTrayUnloadingOn();
}
void ManualDlg::ClickWorktrayLoaderStackBackward3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhChotTrayUnloadingOff();
}
void ManualDlg::ClickWorktrayLoaderRotationForward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ChanTrayUnloadingOn();
}
void ManualDlg::ClickWorktrayLoaderRotationBackward3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ChanTrayUnloadingOff();
}
void ManualDlg::ClickWorktrayLoaderConveyorRun2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ConveyorUnloadingOn();
}
void ManualDlg::ClickWorktrayLoaderConveyorStop2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->ConveyorUnloadingOff();
}
void ManualDlg::ClickOpenDoorFontRight()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorFrontRightOn();
}
void ManualDlg::ClickCloseDoorFrontRight()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorFrontRightOff();
}
void ManualDlg::ClickOpenDoorFrontLeft()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorFrontLeftOn();
}
void ManualDlg::ClickCloseDoorFrontLeft()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorFrontLeftOff();
}
void ManualDlg::ClickOpenDoorSideRight()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorSideRightOn();
}
void ManualDlg::ClickCloseDoorSideRight()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorsideRightOff();
}
void ManualDlg::ClickOpenDoorSideLeft()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorSideLeftOn();
}
void ManualDlg::ClickCloseDoorSideLeft()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorsideLeftOff();
}
//Tool Robot
//Tool 1
void ManualDlg::ClickTool1RobotDown()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool1On();
}
void ManualDlg::ClickTool1RobotUp()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool1Off();
}
void ManualDlg::ClickVaccumTool1RobotOn()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool1On();
}
void ManualDlg::ClickVaccumTool1RobotOff()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool1Off();
}
//Tool 2
void ManualDlg::ClickTool2RobotDown()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool2On();
}
void ManualDlg::ClickTool2RobotUp()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool2Off();
}
void ManualDlg::ClickVaccumTool2RobotOn()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool2On();
}
void ManualDlg::ClickVaccumTool2RobotOff()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool2Off();
}
//Tool 3
void ManualDlg::ClickTool3RobotDown()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool3On();
}
void ManualDlg::ClickTool3RobotUp()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool3Off();
}
void ManualDlg::ClickVaccumTool3RobotOn()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool3On();
}
void ManualDlg::ClickVaccumTool3RobotOff()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool3Off();
}
//Tool 4
void ManualDlg::ClickTool4RobotDown()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool4On();
}
void ManualDlg::ClickTool4RobotUp()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhTool4Off();
}
void ManualDlg::ClickVaccumTool4RobotOn()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool4On();
}
void ManualDlg::ClickVaccumTool4RobotOff()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumTool4Off();
}
//Socket 1
void ManualDlg::ClickSocketForward1()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_1))
{
AfxMessageBox("Cylinder Up 1 On");
return;
}
pDoc->XilanhSocket1ForWard();
}
void ManualDlg::ClickSocketBackward1()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_1))
{
AfxMessageBox("Cylinder Up 1 On");
return;
}
pDoc->XilanhSocket1BackWard();
}
void ManualDlg::ClickSocketUp1()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket1Up();
}
void ManualDlg::ClickSocketDown1()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket1Down();
}
void ManualDlg::ClickSocketVaccumOn1()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket1On();
}
void ManualDlg::ClickSocketVaccumOff1()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket1Off();
}
//Socket 2
void ManualDlg::ClickSocketForward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_2))
{
AfxMessageBox("Cylinder Up 2 On");
return;
}
pDoc->XilanhSocket2ForWard();
}
void ManualDlg::ClickSocketBackward2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_2))
{
AfxMessageBox("Cylinder Up 2 On");
return;
}
pDoc->XilanhSocket2BackWard();
}
void ManualDlg::ClickSocketUp2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket2Up();
}
void ManualDlg::ClickSocketDown2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket2Down();
}
void ManualDlg::ClickSocketVaccumOn2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket2On();
}
void ManualDlg::ClickSocketVaccumOff2()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket2Off();
}
//Socket 3
void ManualDlg::ClickSocketForward3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_3))
{
AfxMessageBox("Cylinder Up 3 On");
return;
}
pDoc->XilanhSocket3ForWard();
}
void ManualDlg::ClickSocketBackward3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_3))
{
AfxMessageBox("Cylinder Up 3 On");
return;
}
pDoc->XilanhSocket3BackWard();
}
void ManualDlg::ClickSocketUp3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket3Up();
}
void ManualDlg::ClickSocketDown3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket3Down();
}
void ManualDlg::ClickSocketVaccumOn3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket3On();
}
void ManualDlg::ClickSocketVaccumOff3()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket3Off();
}
//Socket 4
void ManualDlg::ClickSocketForward4()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_4))
{
AfxMessageBox("Cylinder Up 4 On");
return;
}
pDoc->XilanhSocket4ForWard();
}
void ManualDlg::ClickSocketBackward4()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
if (pDoc->Motion.ReadOuput(Socket_UP_4))
{
AfxMessageBox("Cylinder Up 4 On");
return;
}
pDoc->XilanhSocket4BackWard();
}
void ManualDlg::ClickSocketUp4()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket4Up();
}
void ManualDlg::ClickSocketDown4()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhSocket4Down();
}
void ManualDlg::ClickSocketVaccumOn4()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket4On();
}
void ManualDlg::ClickSocketVaccumOff4()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->VaccumSocket4Off();
}
void ManualDlg::ClickOpenDoorAfter()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->OpenDoorAfter();
}
void ManualDlg::ClickCloseDoorAfter()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->CloseDoorAfter();
}
void ManualDlg::ClickAlineForward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhAlineOn();
}
void ManualDlg::ClickAlineBackward()
{
CMainFrame * pFrm = (CMainFrame *)(AfxGetApp()->m_pMainWnd);
CHandlerMCDoc * pDoc = (CHandlerMCDoc *)pFrm->GetActiveDocument();
pDoc->XilanhAlineOff();
}
| [
"quang.ledang95@gmail.com"
] | quang.ledang95@gmail.com |
a4fa1921538a4e92a329b6f2073b27468008f59e | d11cc9d69f95c970ecef69545a308b43a2c7a526 | /include/Space.hpp | 36ec365027c7499e1f09477d1d8ac6bf584672ea | [] | no_license | T-h-a-d/FinalProject | c88351eae76c39890746604c37eeba1428f4d5e7 | 9f05f7c933dd98cef5fc4b42150bd4ce8a81e055 | refs/heads/master | 2021-03-27T19:30:39.700841 | 2018-03-10T20:32:18 | 2018-03-10T20:32:18 | 112,686,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,821 | hpp | /********************************************************************************************
** Final Project: Jail Escape
** Thad Sauter
** 12/5/17
** Description: Header file for the Space class. This class contains 4 member variables,
** right, left, top, and bottom which are Space pointers and correspond to the adjacent
** Spaces to the current Space. These Space pointers will be used to connect different
** types of Space into a 2-d like structure. The Space class also has a member variable,
** name, to keep track of the name of the space. The Space class has member functions to,
** get the name of a space, set an adjacent space, get an adjacent space, print room
** options for the player and get the choice, randomly move the guard. The Space class also
** has virtual member functions to check if a player is done_digging (overriden by Jail_Cell),
** check if a certain item is needed to enter a Space, print text about the item needed to
** enter a Space, get the name of the item needed to enter the Space, and inspect a room.
** The class also has a virtual destructor.
*********************************************************************************************/
#ifndef SPACE_HPP
#define SPACE_HPP
#include <iostream>
#include "Menu.hpp"
#include <cstdlib>
class Person;
class Space
{
protected:
Space* right;
Space* left;
Space* top;
Space* bottom;
std::string name;
public:
std::string get_name();
void set_adjacent_spaces(std::string, Space*);
Space* get_adjacent_space(std::string);
std::string room_options_player();
std::string room_options_guard();
virtual bool done_digging();
virtual bool item_needed() = 0;
virtual void print_item_needed() = 0;
virtual std::string get_name_of_item_needed() = 0;
virtual void inspect_room(Person*) = 0;
virtual ~Space();
};
#endif | [
"thadsauter@gmail.com"
] | thadsauter@gmail.com |
18e99f11898be6955cd3aba3e973d56f583fa676 | 9b4f4ad42b82800c65f12ae507d2eece02935ff6 | /src/Net/MIBReader.cpp | 2db2f766ee2d3df5326ed56c0a51082e134f7595 | [] | no_license | github188/SClass | f5ef01247a8bcf98d64c54ee383cad901adf9630 | ca1b7efa6181f78d6f01a6129c81f0a9dd80770b | refs/heads/main | 2023-07-03T01:25:53.067293 | 2021-08-06T18:19:22 | 2021-08-06T18:19:22 | 393,572,232 | 0 | 1 | null | 2021-08-07T03:57:17 | 2021-08-07T03:57:16 | null | UTF-8 | C++ | false | false | 5,794 | cpp | #include "Stdafx.h"
#include "Net/MIBReader.h"
#include "Text/CharUtil.h"
Bool Net::MIBReader::ReadLineInner(Text::StringBuilderUTF8 *sb)
{
UOSInt initSize = sb->GetLength();
if (!this->reader->ReadLine(sb, 512))
{
return false;
}
UOSInt i;
UOSInt j;
UOSInt k;
if (this->escapeType == ET_MULTILINE_COMMENT)
{
i = sb->IndexOf((const UTF8Char*)"*/", initSize);
if (i == INVALID_INDEX)
{
sb->TrimToLength(initSize);
return true;
}
sb->RemoveChars(initSize, (UOSInt)i + 2 - initSize);
this->escapeType = ET_NONE;
}
else if (this->escapeType == ET_STRING)
{
i = sb->IndexOf((const UTF8Char*)"\"", initSize);
if (i == INVALID_INDEX)
{
return true;
}
initSize = i + 1;
this->escapeType = ET_NONE;
}
while (true)
{
i = sb->IndexOf((const UTF8Char*)"--", initSize);
j = sb->IndexOf((const UTF8Char*)"/*", initSize);
k = sb->IndexOf((const UTF8Char*)"\"", initSize);
if (i == INVALID_INDEX && j == INVALID_INDEX && k == INVALID_INDEX)
{
break;
}
if (i != INVALID_INDEX && (j == INVALID_INDEX || j > i) && (k == INVALID_INDEX || k > i))
{
UOSInt j = sb->IndexOf((const UTF8Char*)"--", i + 2);
if (j != INVALID_INDEX)
{
sb->RemoveChars(i, (j - i + 2));
initSize = i;
}
else
{
sb->TrimToLength(i);
break;
}
}
else if (j != INVALID_INDEX && (k == INVALID_INDEX || k > j))
{
i = sb->IndexOf((const UTF8Char*)"*/", j + 2);
if (i != INVALID_INDEX)
{
sb->RemoveChars(j, (i - j + 2));
}
else
{
sb->TrimToLength(j);
this->escapeType = ET_MULTILINE_COMMENT;
break;
}
}
else
{
i = sb->IndexOf((const UTF8Char*)"\"", k + 1);
if (i != INVALID_INDEX)
{
initSize = i + 1;
}
else
{
this->escapeType = ET_STRING;
break;
}
}
}
sb->TrimRight();
return true;
}
Bool Net::MIBReader::ReadWord(Text::StringBuilderUTF *sb, Bool move)
{
while (this->currOfst >= this->sbLine->GetCharCnt())
{
this->sbLine->ClearStr();
if (!ReadLineInner(this->sbLine))
{
return false;
}
this->sbLine->Trim();
this->currOfst = 0;
}
UTF8Char *sptr = this->sbLine->ToString();
while (Text::CharUtil::IsWS(&sptr[this->currOfst]))
{
this->currOfst++;
}
if (sptr[this->currOfst] == '{')
{
UOSInt level = 0;
UOSInt i = this->currOfst;
while (true)
{
if (sptr[i] == 0)
{
this->sbLine->AppendChar(' ', 1);
if (!ReadLineInner(this->sbLine))
{
return false;
}
sptr = this->sbLine->ToString();
}
else if (sptr[i] == '{')
{
level++;
i++;
}
else if (sptr[i] == '}')
{
level--;
i++;
if (level == 0)
{
sb->AppendC(&sptr[this->currOfst], i - this->currOfst);
if (move)
{
this->currOfst = i;
}
return true;
}
}
else
{
i++;
}
}
}
else if (sptr[this->currOfst] == ':' && sptr[this->currOfst + 1] == ':' && sptr[this->currOfst + 2] == '=')
{
sb->Append((const UTF8Char*)"::=");
if (move)
{
this->currOfst += 3;
}
return true;
}
else if (Text::CharUtil::IsAlphaNumeric(sptr[this->currOfst]))
{
UOSInt i = this->currOfst;
if (Text::StrStartsWith(&sptr[this->currOfst], (const UTF8Char*)"OCTET STRING") && !Text::CharUtil::IsAlphaNumeric(sptr[this->currOfst + 12]))
{
i += 12;
}
else if (Text::StrStartsWith(&sptr[this->currOfst], (const UTF8Char*)"OBJECT IDENTIFIER") && !Text::CharUtil::IsAlphaNumeric(sptr[this->currOfst + 17]))
{
i += 17;
}
else
{
while (Text::CharUtil::IsAlphaNumeric(sptr[i]) || sptr[i] == '-' || sptr[i] == '_')
{
i++;
}
}
sb->AppendC(&sptr[this->currOfst], i - this->currOfst);
if (move)
{
this->currOfst = i;
}
return true;
}
else if (sptr[this->currOfst] == ',' || sptr[this->currOfst] == ';')
{
sb->AppendChar(sptr[this->currOfst], 1);
if (move)
{
this->currOfst++;
}
return true;
}
else if (sptr[this->currOfst] == '(')
{
UOSInt level = 0;
UOSInt i = this->currOfst;
while (true)
{
if (sptr[i] == 0)
{
this->sbLine->AppendChar(' ', 1);
if (!ReadLineInner(this->sbLine))
{
return false;
}
sptr = this->sbLine->ToString();
}
else if (sptr[i] == '(')
{
level++;
i++;
}
else if (sptr[i] == ')')
{
level--;
i++;
if (level == 0)
{
sb->AppendC(&sptr[this->currOfst], i - this->currOfst);
if (move)
{
this->currOfst = i;
}
return true;
}
}
else
{
i++;
}
}
}
else if (sptr[this->currOfst] == '"')
{
UOSInt i;
while (true)
{
i = Text::StrIndexOf(&sptr[this->currOfst + 1], '"');
if (i != INVALID_INDEX)
{
break;
}
reader->GetLastLineBreak(this->sbLine);
if (!ReadLineInner(this->sbLine))
{
return false;
}
sptr = this->sbLine->ToString();
}
sb->AppendC(&sptr[this->currOfst], i + 2);
this->currOfst += i + 2;
return true;
}
else
{
return false;
}
}
Net::MIBReader::MIBReader(IO::Stream *stm)
{
NEW_CLASS(this->reader, Text::UTF8Reader(stm));
NEW_CLASS(this->sbLine, Text::StringBuilderUTF8());
this->currOfst = 0;
this->escapeType = ET_NONE;
}
Net::MIBReader::~MIBReader()
{
DEL_CLASS(this->sbLine);
DEL_CLASS(this->reader);
}
Bool Net::MIBReader::PeekWord(Text::StringBuilderUTF *sb)
{
return ReadWord(sb, false);
}
Bool Net::MIBReader::NextWord(Text::StringBuilderUTF *sb)
{
return ReadWord(sb, true);
}
Bool Net::MIBReader::ReadLine(Text::StringBuilderUTF8 *sb)
{
if (this->currOfst >= this->sbLine->GetCharCnt())
{
return ReadLineInner(sb);
}
else
{
sb->Append(this->sbLine->ToString() + this->currOfst);
this->currOfst = this->sbLine->GetCharCnt();
return true;
}
}
Bool Net::MIBReader::GetLastLineBreak(Text::StringBuilderUTF *sb)
{
return this->reader->GetLastLineBreak(sb);
}
| [
"sswroom@yahoo.com"
] | sswroom@yahoo.com |
1dde16267dc305e55095c46452da4f395cbef8c5 | 8d3058071e938db57dfd43daa236151778fd0557 | /SMTPServer/stdafx.cpp | 7664e357b37467e647ddda7a0e393d595afd41fb | [] | no_license | 0237/SMTPServer | 75d3254f3b8c326372d370890b28cd7f3a7b41c8 | dff5b87592d22571a0482f4676621465ac0e749b | refs/heads/master | 2021-01-12T05:52:40.592697 | 2018-03-29T16:01:12 | 2018-03-29T16:01:12 | 77,226,678 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 165 | cpp |
// stdafx.cpp : 只包括标准包含文件的源文件
// SMTPServer.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"xd_yang@outlook.com"
] | xd_yang@outlook.com |
efa9bbab96c8d176173fccc9c64018016b82dbe4 | 2fa5c8d10d597fe1d590542596994fdbd016fddc | /dataset/simulation_experiment/Type2/T2_1/10/Base2.cpp | 9c98e5cf0a84e737a850d6b1faa233e60ff0e853 | [] | no_license | guoliang72/colllectivePR | 715ea332a147e115ac30326a013e19d80f4638a1 | f9223e1d1aaa34ac377e75994c02c69033cd0d7f | refs/heads/master | 2020-04-24T06:55:28.611842 | 2019-02-22T11:31:27 | 2019-02-22T11:31:27 | 171,782,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 392 | cpp | #include <stdio.h>
int main(){
int i;
int n;
double a;
double sum;
sum=0;
scanf("%d",&n);
for(i=0;i<n;i=i+1){
scanf("%lf",&a);
if(a<100){
n=0;
}else if(a>=100 && a<200){
a=0.1*sum;
}else if(a>=200 && a<500){
a=0.3*a;
}else if(a>=500){
a=0.5*a;
}
sum=sum+a;
}
printf("%.2lf\n",sum);
return 0;
}
| [
"guoliang72@qq.com"
] | guoliang72@qq.com |
0e1bec1748b5efb2b86382e4de2cfebaee28d77a | 3d643e50e304d3ffd3f697905e441556be377cfc | /ios/versioned-react-native/ABI36_0_0/ReactNative/ReactCommon/fabric/core/events/ABI36_0_0EventBeatBasedExecutor.cpp | bebc499c4521ee6375f10d363913f0e2ab0fb673 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | Qdigital/expo | 326c5c1c0167295c173f2388f078a2f1e73835c9 | 8865a523d754b2332ffb512096da4998c18c9822 | refs/heads/master | 2023-07-07T18:37:39.814195 | 2020-02-18T23:28:20 | 2020-02-18T23:28:20 | 241,549,344 | 1 | 0 | MIT | 2023-07-06T14:55:15 | 2020-02-19T06:28:39 | null | UTF-8 | C++ | false | false | 1,704 | cpp | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cassert>
#include "ABI36_0_0EventBeatBasedExecutor.h"
namespace ABI36_0_0facebook {
namespace ABI36_0_0React {
using Mode = EventBeatBasedExecutor::Mode;
EventBeatBasedExecutor::EventBeatBasedExecutor(
std::unique_ptr<EventBeat> eventBeat)
: eventBeat_(std::move(eventBeat)) {
eventBeat_->setBeatCallback(
std::bind(&EventBeatBasedExecutor::onBeat, this, true));
eventBeat_->setFailCallback(
std::bind(&EventBeatBasedExecutor::onBeat, this, false));
}
void EventBeatBasedExecutor::operator()(Routine routine, Mode mode) const {
if (mode == Mode::Asynchronous) {
execute({
/* .routine = */ std::move(routine),
});
return;
}
std::mutex mutex;
mutex.lock();
execute({
/* .routine = */ std::move(routine),
/* .callback = */ [&mutex]() { mutex.unlock(); },
});
mutex.lock();
}
void EventBeatBasedExecutor::execute(Task task) const {
{
std::lock_guard<std::mutex> lock(mutex_);
tasks_.push_back(std::move(task));
}
eventBeat_->request();
eventBeat_->induce();
}
void EventBeatBasedExecutor::onBeat(bool success) const {
std::vector<Task> tasks;
{
std::lock_guard<std::mutex> lock(mutex_);
if (tasks_.size() == 0) {
return;
}
tasks = std::move(tasks_);
tasks_.clear();
}
for (const auto task : tasks) {
if (success) {
task.routine();
}
if (task.callback) {
task.callback();
}
}
}
} // namespace ABI36_0_0React
} // namespace ABI36_0_0facebook
| [
"esamelson@users.noreply.github.com"
] | esamelson@users.noreply.github.com |
b0350bb5a7cd092f78a83d3a2997bb9767e76b4b | 1ae40287c5705f341886bbb5cc9e9e9cfba073f7 | /Osmium/SDK/FN_B_Rifle_Sniper_Athena_classes.hpp | 4e493ea78ceec43d5c6866be13888e642fa175b6 | [] | no_license | NeoniteDev/Osmium | 183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0 | aec854e60beca3c6804f18f21b6a0a0549e8fbf6 | refs/heads/master | 2023-07-05T16:40:30.662392 | 2023-06-28T23:17:42 | 2023-06-28T23:17:42 | 340,056,499 | 14 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 665 | hpp | #pragma once
// Fortnite (4.5-CL-4159770) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass B_Rifle_Sniper_Athena.B_Rifle_Sniper_Athena_C
// 0x0000 (0x0F0C - 0x0F0C)
class AB_Rifle_Sniper_Athena_C : public AB_Rifle_Generic_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass B_Rifle_Sniper_Athena.B_Rifle_Sniper_Athena_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"kareemolim@gmail.com"
] | kareemolim@gmail.com |
dc050a22c94328ac7666cf132a0aa31438e6bf1a | 6dac43ccd5b393d3c987d7949140e78e922a6dab | /Section_9_Pointers/4_Strings_and_pointers_of_chars/Solutions/exercise2.cpp | 2093ad1715a090f13554149a3786c2a75686c557 | [
"MIT"
] | permissive | m-lyon/LearningCPlusPlus | 6639058cdb19a3884510393162669642900d97c0 | 33d413e8ccc24c345bb9b26cb554fd8552ebbffc | refs/heads/master | 2022-12-24T23:40:45.151832 | 2020-10-07T21:38:31 | 2020-10-07T21:38:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | #include <iostream>
using namespace std;
int main ()
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 26; i++)
cout << alphabet[i];
return 0;
}
| [
"matthewlyon18@gmail.com"
] | matthewlyon18@gmail.com |
6e2f6298c6fc3323eadbcd24feb6a26b86a595a7 | 0f57a88aa425a9e0dd92854e68c216777c5440e4 | /geometry/test/meshcat_test.cc | 33cdb25e885e90b3ad1d1c51d570d8b2592ba3e2 | [
"BSD-3-Clause"
] | permissive | ankurshkl877/drake | 1f4e2ffff4b1535535a98773c94391af61dceb44 | 82d8460973cd39defac2b6cee5d696a860237973 | refs/heads/master | 2023-04-06T04:52:08.335025 | 2023-03-16T22:49:40 | 2023-03-16T22:49:40 | 42,181,822 | 0 | 0 | null | 2015-09-09T14:00:21 | 2015-09-09T14:00:21 | null | UTF-8 | C++ | false | false | 36,661 | cc | #include "drake/geometry/meshcat.h"
#include <cstdlib>
#include <thread>
#include <drake_vendor/msgpack.hpp>
#include <fmt/format.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/find_resource.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/geometry/meshcat_types.h"
namespace drake {
namespace geometry {
namespace {
using Eigen::Vector3d;
using math::RigidTransformd;
using math::RotationMatrixd;
using testing::ElementsAre;
using ::testing::HasSubstr;
// A small wrapper around std::system to ensure correct argument passing.
int SystemCall(const std::vector<std::string>& argv) {
std::string command;
for (const std::string& arg : argv) {
// Note: Can't use ASSERT_THAT inside this subroutine.
EXPECT_THAT(arg, ::testing::Not(HasSubstr("'")));
command += fmt::format("'{}' ", arg);
}
return std::system(command.c_str());
}
// Calls a python helper program to send and receive websocket messages(s)
// to/from the given Meshcat instance.
//
// @param send_json Message to send, as a json string.
// @param expect_num_messages Expected number of messages to receive.
// @param expect_json Expected content of the final message, as a json string.
// @param expect_success Whether to insist that the python helper finished and
// the expected_json (if given) was actually received.
void CheckWebsocketCommand(
const Meshcat& meshcat,
std::optional<std::string> send_json,
std::optional<int> expect_num_messages,
std::optional<std::string> expect_json,
bool expect_success = true) {
std::vector<std::string> argv;
argv.push_back(FindResourceOrThrow(
"drake/geometry/meshcat_websocket_client"));
// Even when this unit test is itself running under valgrind, we don't want to
// instrument the helper process. Our valgrind configuration recognizes this
// argument and skips instrumentation of the child process.
argv.push_back("--disable-drake-valgrind-tracing");
argv.push_back(fmt::format("--ws_url={}", meshcat.ws_url()));
if (send_json) {
DRAKE_DEMAND(!send_json->empty());
argv.push_back(fmt::format("--send_message={}", std::move(*send_json)));
}
if (expect_num_messages) {
argv.push_back(fmt::format("--expect_num_messages={}",
*expect_num_messages));
}
if (expect_json) {
DRAKE_DEMAND(!expect_json->empty());
argv.push_back(fmt::format("--expect_message={}", std::move(*expect_json)));
}
argv.push_back(fmt::format("--expect_success={}",
expect_success ? "1" : "0"));
const int exit_code = SystemCall(argv);
if (expect_success) {
EXPECT_EQ(exit_code, 0);
}
}
GTEST_TEST(MeshcatTest, TestHttp) {
Meshcat meshcat;
// Note: The server doesn't respect all requests; unfortunately we can't use
// curl --head and wget --spider nor curl --range to avoid downloading the
// full file.
EXPECT_EQ(SystemCall({"/usr/bin/curl", "-o", "/dev/null", "--silent",
meshcat.web_url() + "/index.html"}),
0);
EXPECT_EQ(SystemCall({"/usr/bin/curl", "-o", "/dev/null", "--silent",
meshcat.web_url() + "/meshcat.js"}),
0);
EXPECT_EQ(SystemCall({"/usr/bin/curl", "-o", "/dev/null", "--silent",
meshcat.web_url() + "/favicon.ico"}),
0);
EXPECT_EQ(SystemCall({"/usr/bin/curl", "-o", "/dev/null", "--silent",
meshcat.web_url() + "/no-such-file"}),
0);
}
GTEST_TEST(MeshcatTest, ConstructMultiple) {
Meshcat meshcat;
Meshcat meshcat2;
EXPECT_THAT(meshcat.web_url(), HasSubstr("http://localhost:"));
EXPECT_THAT(meshcat.ws_url(), HasSubstr("ws://localhost:"));
EXPECT_THAT(meshcat2.web_url(), HasSubstr("http://localhost:"));
EXPECT_THAT(meshcat2.ws_url(), HasSubstr("ws://localhost:"));
EXPECT_NE(meshcat.web_url(), meshcat2.web_url());
}
GTEST_TEST(MeshcatTest, Ports) {
Meshcat meshcat(7050);
EXPECT_EQ(meshcat.port(), 7050);
// Can't open the same port twice.
DRAKE_EXPECT_THROWS_MESSAGE(Meshcat(7050),
"Meshcat failed to open a websocket port.");
// The default constructor gets a default port.
Meshcat m3;
EXPECT_GE(m3.port(), 7000);
EXPECT_LE(m3.port(), 7099);
}
// Use a basic web_url_pattern to affect web_url() and ws_url(). The pattern
// parameter only affects those URLs getters, not the server's bind behavior.
GTEST_TEST(MeshcatTest, CustomHttp) {
const std::string pattern = "http://127.0.0.254:{port}";
const Meshcat meshcat({"", std::nullopt, pattern});
const std::string port = std::to_string(meshcat.port());
EXPECT_EQ(meshcat.web_url(), "http://127.0.0.254:" + port);
EXPECT_EQ(meshcat.ws_url(), "ws://127.0.0.254:" + port);
}
// Check a web_url_pattern that does not use any substitutions.
GTEST_TEST(MeshcatTest, CustomNoPort) {
const std::string pattern = "http://example.ngrok.io";
const Meshcat meshcat({"", std::nullopt, pattern});
EXPECT_EQ(meshcat.web_url(), "http://example.ngrok.io");
EXPECT_EQ(meshcat.ws_url(), "ws://example.ngrok.io");
}
// Check a web_url_pattern that uses https instead of http.
GTEST_TEST(MeshcatTest, CustomHttps) {
const std::string pattern = "https://localhost:{port}";
const Meshcat meshcat({"", std::nullopt, pattern});
const std::string port = std::to_string(meshcat.port());
EXPECT_EQ(meshcat.web_url(), "https://localhost:" + port);
EXPECT_EQ(meshcat.ws_url(), "wss://localhost:" + port);
}
// Check that binding to the don't-care host "" does not crash.
// It should display as "localhost".
GTEST_TEST(MeshcatTest, CustomDefaultInterface) {
const Meshcat meshcat({""});
const std::string port = std::to_string(meshcat.port());
EXPECT_EQ(meshcat.web_url(), "http://localhost:" + port);
}
// Check that binding to "*" (as mentioned in Params docs) does not crash.
// It should display as "localhost".
GTEST_TEST(MeshcatTest, CustomAllInterfaces) {
const Meshcat meshcat({"*"});
const std::string port = std::to_string(meshcat.port());
EXPECT_EQ(meshcat.web_url(), "http://localhost:" + port);
}
// Check that binding to an IP does not crash.
GTEST_TEST(MeshcatTest, CustomNumericInterface) {
const Meshcat meshcat({"127.0.0.1"});
const std::string port = std::to_string(meshcat.port());
EXPECT_EQ(meshcat.web_url(), "http://127.0.0.1:" + port);
}
// Check that binding to a malformed value does crash.
GTEST_TEST(MeshcatTest, BadCustomInterface) {
DRAKE_EXPECT_THROWS_MESSAGE(Meshcat({"----"}), ".*failed to open.*");
}
GTEST_TEST(MeshcatTest, MalformedCustom) {
// Using a non-existent substitution is detected immediately.
DRAKE_EXPECT_THROWS_MESSAGE(
Meshcat({"", std::nullopt, "http://localhost:{portnum}"}),
".*argument.*");
// Only http or https are allowed.
DRAKE_EXPECT_THROWS_MESSAGE(
Meshcat({"", std::nullopt, "file:///tmp"}),
".*web_url_pattern.*http.*");
}
// Checks that unparsable messages are ignored.
GTEST_TEST(MeshcatTest, UnparseableMessageIgnored) {
auto dut = std::make_unique<Meshcat>();
// Send an unparsable message; don't expect a reply.
const char* const message = "0";
const bool expect_success = false;
CheckWebsocketCommand(*dut, message, {}, {}, expect_success);
// Pause to allow the websocket thread to run.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// The object can be destroyed with neither errors nor sanitizer leaks.
EXPECT_NO_THROW(dut.reset());
}
// Checks that parseable messages with unknown semantics are ignored.
GTEST_TEST(MeshcatTest, UnknownEventIgnored) {
auto dut = std::make_unique<Meshcat>();
// Send a syntactically well-formed UserInterfaceEvent to tickle the
// stack, but don't expect a reply.
const char* const message = R"""({
"type": "no_such_type",
"name": "no_such_name"
})""";
const bool expect_success = false;
CheckWebsocketCommand(*dut, message, {}, {}, expect_success);
// Pause to allow the websocket thread to run.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// The object can be destroyed with neither errors nor sanitizer leaks.
EXPECT_NO_THROW(dut.reset());
}
class MeshcatFaultTest : public testing::TestWithParam<int> {};
// Checks that a problem with the worker thread eventually ends up as an
// exception on the main thread.
TEST_P(MeshcatFaultTest, WorkerThreadFault) {
const int fault_number = GetParam();
auto dut = std::make_unique<Meshcat>();
// Cause the websocket thread to fail.
EXPECT_NO_THROW(dut->InjectWebsocketThreadFault(fault_number));
// Keep checking an accessor function until the websocket fault is detected
// and is converted into an exception on the main thread. Here we should be
// able to call *any* function and have it report the fault; we use web_url
// out of simplicity, and rely the impl() function in the cc file to prove
// that every public function is preceded by a ThrowIfWebsocketThreadExited.
auto checker = [&dut]() {
for (int i = 0; i < 10; ++i) {
// Send a syntactically well-formed UserInterfaceEvent to tickle the
// stack, but don't expect a reply.
const char* const message = R"""({
"type": "no_such_type",
"name": "no_such_name"
})""";
const bool expect_success = false;
CheckWebsocketCommand(*dut, message, {}, {}, expect_success);
// Poll the accessor function.
dut->web_url();
// Pause to allow the websocket thread to run.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
};
DRAKE_EXPECT_THROWS_MESSAGE(checker(), ".*thread exited.*");
// The object can be destroyed with neither errors nor sanitizer leaks.
EXPECT_NO_THROW(dut.reset());
}
INSTANTIATE_TEST_SUITE_P(AllFaults, MeshcatFaultTest,
testing::Range(0, Meshcat::kMaxFaultNumber + 1));
GTEST_TEST(MeshcatTest, NumActive) {
Meshcat meshcat;
EXPECT_EQ(meshcat.GetNumActiveConnections(), 0);
}
// The correctness of this is established with meshcat_manual_test. Here we
// simply aim to provide code coverage for CI (e.g., no segfaults).
GTEST_TEST(MeshcatTest, SetObjectWithShape) {
Meshcat meshcat;
EXPECT_TRUE(meshcat.GetPackedObject("sphere").empty());
meshcat.SetObject("sphere", Sphere(.25), Rgba(1.0, 0, 0, 1));
EXPECT_FALSE(meshcat.GetPackedObject("sphere").empty());
meshcat.SetObject("cylinder", Cylinder(.25, .5), Rgba(0.0, 1.0, 0, 1));
EXPECT_FALSE(meshcat.GetPackedObject("cylinder").empty());
// HalfSpaces are not supported yet; this should only log a warning.
meshcat.SetObject("halfspace", HalfSpace());
EXPECT_TRUE(meshcat.GetPackedObject("halfspace").empty());
meshcat.SetObject("box", Box(.25, .25, .5), Rgba(0, 0, 1, 1));
EXPECT_FALSE(meshcat.GetPackedObject("box").empty());
meshcat.SetObject("ellipsoid", Ellipsoid(.25, .25, .5), Rgba(1., 0, 1, 1));
EXPECT_FALSE(meshcat.GetPackedObject("ellipsoid").empty());
meshcat.SetObject("capsule", Capsule(.25, .5));
EXPECT_FALSE(meshcat.GetPackedObject("capsule").empty());
meshcat.SetObject(
"mesh", Mesh(FindResourceOrThrow(
"drake/geometry/render/test/meshes/box.obj"),
.25));
EXPECT_FALSE(meshcat.GetPackedObject("mesh").empty());
meshcat.SetObject(
"convex", Convex(FindResourceOrThrow(
"drake/geometry/render/test/meshes/box.obj"),
.25));
EXPECT_FALSE(meshcat.GetPackedObject("convex").empty());
// Bad filename (no extension). Should only log a warning.
meshcat.SetObject("bad", Mesh("test"));
EXPECT_TRUE(meshcat.GetPackedObject("bad").empty());
// Bad filename (file doesn't exist). Should only log a warning.
meshcat.SetObject("bad", Mesh("test.obj"));
EXPECT_TRUE(meshcat.GetPackedObject("bad").empty());
}
GTEST_TEST(MeshcatTest, SetObjectWithPointCloud) {
Meshcat meshcat;
perception::PointCloud cloud(5);
// clang-format off
cloud.mutable_xyzs().transpose() <<
1, 2, 3,
10, 20, 30,
100, 200, 300,
4, 5, 6,
40, 50, 60;
// clang-format on
meshcat.SetObject("cloud", cloud);
EXPECT_FALSE(meshcat.GetPackedObject("cloud").empty());
perception::PointCloud rgb_cloud(
5, perception::pc_flags::kXYZs | perception::pc_flags::kRGBs);
rgb_cloud.mutable_xyzs() = cloud.xyzs();
// clang-format off
rgb_cloud.mutable_rgbs() <<
1, 2, 3,
10, 20, 30,
100, 200, 255,
4, 5, 6,
40, 50, 60;
// clang-format on
meshcat.SetObject("rgb_cloud", rgb_cloud);
EXPECT_FALSE(meshcat.GetPackedObject("rgb_cloud").empty());
}
GTEST_TEST(MeshcatTest, SetObjectWithTriangleSurfaceMesh) {
Meshcat meshcat;
const int face_data[2][3] = {{0, 1, 2}, {2, 3, 0}};
std::vector<SurfaceTriangle> faces;
for (int f = 0; f < 2; ++f) faces.emplace_back(face_data[f]);
const Eigen::Vector3d vertex_data[4] = {
{0, 0, 0}, {0.5, 0, 0}, {0.5, 0.5, 0}, {0, 0.5, 0.5}};
std::vector<Eigen::Vector3d> vertices;
for (int v = 0; v < 4; ++v) vertices.emplace_back(vertex_data[v]);
TriangleSurfaceMesh<double> surface_mesh(
std::move(faces), std::move(vertices));
meshcat.SetObject("triangle_mesh", surface_mesh, Rgba(.9, 0, .9, 1.0));
EXPECT_FALSE(meshcat.GetPackedObject("triangle_mesh").empty());
meshcat.SetObject("triangle_mesh_wireframe", surface_mesh,
Rgba(.9, 0, .9, 1.0), true, 5.0);
EXPECT_FALSE(meshcat.GetPackedObject("triangle_mesh_wireframe").empty());
}
GTEST_TEST(MeshcatTest, PlotSurface) {
Meshcat meshcat;
constexpr int nx = 15, ny = 11;
Eigen::MatrixXd X =
RowVector<double, nx>::LinSpaced(0, 1).replicate<ny, 1>();
Eigen::MatrixXd Y =
Vector<double, ny>::LinSpaced(0, 1).replicate<1, nx>();
// z = y*sin(5*x)
Eigen::MatrixXd Z = (Y.array() * (5*X.array()).sin()).matrix();
// Wireframe = false.
meshcat.PlotSurface("plot_surface", X, Y, Z, Rgba(0, 0, .9, 1.0), false);
EXPECT_FALSE(meshcat.GetPackedObject("plot_surface").empty());
// Wireframe = true.
meshcat.PlotSurface("plot_surface_wireframe", X, Y, Z, Rgba(0, 0, .9, 1.0),
true);
EXPECT_FALSE(meshcat.GetPackedObject("plot_surface_wireframe").empty());
}
GTEST_TEST(MeshcatTest, SetLine) {
Meshcat meshcat;
Eigen::Matrix3Xd vertices(3, 200);
Eigen::RowVectorXd t = Eigen::RowVectorXd::LinSpaced(200, 0, 10 * M_PI);
vertices << .25 * t.array().sin(), .25 * t.array().cos(), t / (10 * M_PI);
meshcat.SetLine("line", vertices, 3.0, Rgba(0, 0, 1, 1));
EXPECT_FALSE(meshcat.GetPackedObject("line").empty());
Eigen::Matrix3Xd start(3, 4), end(3, 4);
// clang-format off
start << -.1, -.1, .1, .1,
-.1, .1, -.1, .1,
0, 0, 0, 0;
// clang-format on
end = start;
end.row(2) = Eigen::RowVector4d::Ones();
meshcat.SetLineSegments("line_segments", start, end, 5.0, Rgba(0, 1, 0, 1));
EXPECT_FALSE(meshcat.GetPackedObject("line_segments").empty());
// Throws if start.cols() != end.cols().
EXPECT_THROW(
meshcat.SetLineSegments("bad_segments", Eigen::Matrix3Xd::Identity(3, 4),
Eigen::Matrix3Xd::Identity(3, 3)),
std::exception);
}
GTEST_TEST(MeshcatTest, SetTriangleMesh) {
Meshcat meshcat;
// Populate the vertices/faces transposed, for easier Eigen initialization.
Eigen::MatrixXd vertices(4, 3);
Eigen::MatrixXi faces(2, 3);
// clang-format off
vertices << 0, 0, 0,
1, 0, 0,
1, 0, 1,
0, 0, 1;
faces << 0, 1, 2,
3, 0, 2;
// clang-format on
meshcat.SetTriangleMesh("triangle_mesh", vertices.transpose(),
faces.transpose(), Rgba(1, 0, 0, 1), true, 5.0);
EXPECT_FALSE(meshcat.GetPackedObject("triangle_mesh").empty());
}
GTEST_TEST(MeshcatTest, SetTransform) {
Meshcat meshcat;
EXPECT_FALSE(meshcat.HasPath("frame"));
EXPECT_TRUE(meshcat.GetPackedTransform("frame").empty());
const RigidTransformd X_ParentPath{math::RollPitchYawd(.5, .26, -3),
Vector3d{.9, -2., .12}};
meshcat.SetTransform("frame", X_ParentPath);
std::string transform = meshcat.GetPackedTransform("frame");
msgpack::object_handle oh =
msgpack::unpack(transform.data(), transform.size());
auto data = oh.get().as<internal::SetTransformData>();
EXPECT_EQ(data.type, "set_transform");
EXPECT_EQ(data.path, "/drake/frame");
Eigen::Map<Eigen::Matrix4d> matrix(data.matrix);
EXPECT_TRUE(CompareMatrices(matrix, X_ParentPath.GetAsMatrix4()));
}
GTEST_TEST(MeshcatTest, SetTransformWithMatrix) {
Meshcat meshcat;
EXPECT_FALSE(meshcat.HasPath("frame"));
EXPECT_TRUE(meshcat.GetPackedTransform("frame").empty());
Eigen::Matrix4d matrix;
// clang-format off
matrix << 1, 2, 3, 4,
5, 6, 7, 8,
-1, -2, -3, -4,
-5, -6, -7, -8;
// clang-format on
meshcat.SetTransform("frame", matrix);
std::string transform = meshcat.GetPackedTransform("frame");
msgpack::object_handle oh =
msgpack::unpack(transform.data(), transform.size());
auto data = oh.get().as<internal::SetTransformData>();
EXPECT_EQ(data.type, "set_transform");
EXPECT_EQ(data.path, "/drake/frame");
Eigen::Map<Eigen::Matrix4d> actual(data.matrix);
EXPECT_TRUE(CompareMatrices(matrix, actual));
}
GTEST_TEST(MeshcatTest, Delete) {
Meshcat meshcat;
// Ok to delete an empty tree.
meshcat.Delete();
EXPECT_FALSE(meshcat.HasPath(""));
EXPECT_FALSE(meshcat.HasPath("frame"));
meshcat.SetTransform("frame", RigidTransformd{});
EXPECT_TRUE(meshcat.HasPath(""));
EXPECT_TRUE(meshcat.HasPath("frame"));
EXPECT_TRUE(meshcat.HasPath("/drake/frame"));
// Deleting a random string does nothing.
meshcat.Delete("bad");
EXPECT_TRUE(meshcat.HasPath("frame"));
meshcat.Delete("frame");
EXPECT_FALSE(meshcat.HasPath("frame"));
// Deleting a parent directory deletes all children.
meshcat.SetTransform("test/frame", RigidTransformd{});
meshcat.SetTransform("test/frame2", RigidTransformd{});
meshcat.SetTransform("test/another/frame", RigidTransformd{});
EXPECT_TRUE(meshcat.HasPath("test/frame"));
EXPECT_TRUE(meshcat.HasPath("test/frame2"));
EXPECT_TRUE(meshcat.HasPath("test/another/frame"));
meshcat.Delete("test");
EXPECT_FALSE(meshcat.HasPath("test/frame"));
EXPECT_FALSE(meshcat.HasPath("test/frame2"));
EXPECT_FALSE(meshcat.HasPath("test/another/frame"));
EXPECT_TRUE(meshcat.HasPath("/drake"));
// Deleting the empty string deletes the prefix.
meshcat.SetTransform("test/frame", RigidTransformd{});
meshcat.SetTransform("test/frame2", RigidTransformd{});
meshcat.SetTransform("test/another/frame", RigidTransformd{});
EXPECT_TRUE(meshcat.HasPath("test/frame"));
EXPECT_TRUE(meshcat.HasPath("test/frame2"));
EXPECT_TRUE(meshcat.HasPath("test/another/frame"));
meshcat.Delete();
EXPECT_FALSE(meshcat.HasPath("test/frame"));
EXPECT_FALSE(meshcat.HasPath("test/frame2"));
EXPECT_FALSE(meshcat.HasPath("test/another/frame"));
EXPECT_FALSE(meshcat.HasPath("/drake"));
}
// Tests three methods of SceneTreeElement:
// - SceneTreeElement::operator[]() is used in Meshcat::Set*(). We'll use
// SetTransform() here.
// - SceneTreeElement::Find() is used in Meshcat::HasPath() and
// Meshcat::GetPacked*(). We'll use HasPath() to test.
// - SceneTreeElement::Delete() is used in Meshat::Delete().
// All of them also run through WebSocketPublisher::FullPath().
GTEST_TEST(MeshcatTest, Paths) {
Meshcat meshcat;
// Absolute paths.
meshcat.SetTransform("/foo/frame", RigidTransformd{});
EXPECT_TRUE(meshcat.HasPath("/foo/frame"));
meshcat.Delete("/foo/frame");
EXPECT_FALSE(meshcat.HasPath("/foo/frame"));
// Absolute paths with strange spellings.
meshcat.SetTransform("///bar///frame///", RigidTransformd{});
EXPECT_TRUE(meshcat.HasPath("//bar//frame//"));
EXPECT_TRUE(meshcat.HasPath("/bar/frame"));
meshcat.Delete("////bar//frame///");
EXPECT_FALSE(meshcat.HasPath("/bar/frame"));
// Relative paths.
meshcat.SetTransform("frame", RigidTransformd{});
EXPECT_TRUE(meshcat.HasPath("frame"));
EXPECT_TRUE(meshcat.HasPath("/drake/frame"));
// Relative paths with strange spellings.
meshcat.SetTransform("bar///frame///", RigidTransformd{});
EXPECT_TRUE(meshcat.HasPath("bar//frame//"));
EXPECT_TRUE(meshcat.HasPath("/drake/bar/frame"));
meshcat.Delete("bar//frame//");
EXPECT_FALSE(meshcat.HasPath("bar/frame"));
EXPECT_FALSE(meshcat.HasPath("/drake/bar/frame"));
}
GTEST_TEST(MeshcatTest, SetPropertyBool) {
Meshcat meshcat;
EXPECT_FALSE(meshcat.HasPath("/Grid"));
EXPECT_TRUE(meshcat.GetPackedProperty("/Grid", "visible").empty());
meshcat.SetProperty("/Grid", "visible", false);
EXPECT_TRUE(meshcat.HasPath("/Grid"));
std::string property = meshcat.GetPackedProperty("/Grid", "visible");
msgpack::object_handle oh = msgpack::unpack(property.data(), property.size());
auto data = oh.get().as<internal::SetPropertyData<bool>>();
EXPECT_EQ(data.type, "set_property");
EXPECT_EQ(data.path, "/Grid");
EXPECT_EQ(data.property, "visible");
EXPECT_FALSE(data.value);
}
GTEST_TEST(MeshcatTest, SetPropertyDouble) {
Meshcat meshcat;
EXPECT_FALSE(meshcat.HasPath("/Cameras/default/rotated/<object>"));
EXPECT_TRUE(
meshcat.GetPackedProperty("/Cameras/default/rotated/<object>", "zoom")
.empty());
meshcat.SetProperty("/Cameras/default/rotated/<object>", "zoom", 2.0);
EXPECT_TRUE(meshcat.HasPath("/Cameras/default/rotated/<object>"));
std::string property =
meshcat.GetPackedProperty("/Cameras/default/rotated/<object>", "zoom");
msgpack::object_handle oh = msgpack::unpack(property.data(), property.size());
auto data = oh.get().as<internal::SetPropertyData<double>>();
EXPECT_EQ(data.type, "set_property");
EXPECT_EQ(data.path, "/Cameras/default/rotated/<object>");
EXPECT_EQ(data.property, "zoom");
EXPECT_EQ(data.value, 2.0);
}
GTEST_TEST(MeshcatTest, Buttons) {
Meshcat meshcat;
// Asking for clicks prior to adding is an error.
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetButtonClicks("alice"),
"Meshcat does not have any button named alice.");
// A new button starts out unclicked.
meshcat.AddButton("alice");
EXPECT_EQ(meshcat.GetButtonClicks("alice"), 0);
// Clicking the button increases the count.
CheckWebsocketCommand(meshcat, R"""({
"type": "button",
"name": "alice"
})""", {}, {});
EXPECT_EQ(meshcat.GetButtonClicks("alice"), 1);
// Adding using an existing button name resets its count.
meshcat.AddButton("alice");
EXPECT_EQ(meshcat.GetButtonClicks("alice"), 0);
// Clicking the button increases the count again.
CheckWebsocketCommand(meshcat, R"""({
"type": "button",
"name": "alice"
})""", {}, {});
EXPECT_EQ(meshcat.GetButtonClicks("alice"), 1);
// Removing the button then asking for clicks is an error.
meshcat.DeleteButton("alice");
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetButtonClicks("alice"),
"Meshcat does not have any button named alice.");
// Removing a non-existent button is an error.
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.DeleteButton("alice"),
"Meshcat does not have any button named alice.");
// Adding the button anew starts with a zero count again.
meshcat.AddButton("alice");
EXPECT_EQ(meshcat.GetButtonClicks("alice"), 0);
// Buttons are removed when deleting all controls.
meshcat.AddButton("bob");
meshcat.DeleteAddedControls();
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetButtonClicks("alice"),
"Meshcat does not have any button named alice.");
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetButtonClicks("bob"),
"Meshcat does not have any button named bob.");
// Adding a button with the keycode.
meshcat.AddButton("alice", "KeyT");
CheckWebsocketCommand(meshcat, R"""({
"type": "button",
"name": "alice"
})""", {}, {});
EXPECT_EQ(meshcat.GetButtonClicks("alice"), 1);
// Adding with the same keycode still resets.
meshcat.AddButton("alice", "KeyT");
EXPECT_EQ(meshcat.GetButtonClicks("alice"), 0);
// Adding the same button with an empty keycode throws.
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.AddButton("alice"),
".*does not match the current keycode.*");
// Adding the same button with a different keycode throws.
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.AddButton("alice", "KeyR"),
".*does not match the current keycode.*");
meshcat.DeleteButton("alice");
// Adding a button with the keycode empty, then populated works.
meshcat.AddButton("alice");
meshcat.AddButton("alice", "KeyT");
}
GTEST_TEST(MeshcatTest, Sliders) {
Meshcat meshcat;
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetSliderValue("slider"),
"Meshcat does not have any slider named slider.");
meshcat.AddSlider("slider", 0.2, 1.5, 0.1, 0.5);
EXPECT_NEAR(meshcat.GetSliderValue("slider"), 0.5, 1e-14);
meshcat.SetSliderValue("slider", 0.7);
EXPECT_NEAR(meshcat.GetSliderValue("slider"), 0.7, 1e-14);
meshcat.SetSliderValue("slider", -2.0);
EXPECT_NEAR(meshcat.GetSliderValue("slider"), .2, 1e-14);
meshcat.SetSliderValue("slider", 2.0);
EXPECT_NEAR(meshcat.GetSliderValue("slider"), 1.5, 1e-14);
meshcat.SetSliderValue("slider", 1.245);
EXPECT_NEAR(meshcat.GetSliderValue("slider"), 1.2, 1e-14);
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.AddSlider("slider", 0.2, 1.5, 0.1, 0.5),
"Meshcat already has a slider named slider.");
meshcat.DeleteSlider("slider");
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetSliderValue("slider"),
"Meshcat does not have any slider named slider.");
meshcat.AddSlider("slider1", 2, 3, 0.01, 2.35);
meshcat.AddSlider("slider2", 4, 5, 0.01, 4.56);
auto slider_names = meshcat.GetSliderNames();
EXPECT_THAT(slider_names, ElementsAre("slider1", "slider2"));
meshcat.DeleteAddedControls();
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetSliderValue("slider1"),
"Meshcat does not have any slider named slider1.");
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.GetSliderValue("slider2"),
"Meshcat does not have any slider named slider2.");
slider_names = meshcat.GetSliderNames();
EXPECT_EQ(slider_names.size(), 0);
}
GTEST_TEST(MeshcatTest, DuplicateMixedControls) {
Meshcat meshcat;
meshcat.AddButton("button");
meshcat.AddSlider("slider", 0.2, 1.5, 0.1, 0.5);
// We cannot use AddButton nor AddSlider to change the type of an existing
// control by attempting to re-use its name.
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.AddButton("slider"),
"Meshcat already has a slider named slider.");
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.AddButton("slider", "KeyR"),
"Meshcat already has a slider named slider.");
DRAKE_EXPECT_THROWS_MESSAGE(
meshcat.AddSlider("button", 0.2, 1.5, 0.1, 0.5),
"Meshcat already has a button named button.");
}
// Properly testing Meshcat's limited support for gamepads requires human
// input, and is done in meshcat_manual_test. This test simply ensures the
// entry point forwards along the Javascript messages.
GTEST_TEST(MeshcatTest, Gamepad) {
Meshcat meshcat;
Meshcat::Gamepad gamepad = meshcat.GetGamepad();
// Check the default status assuming no messages have been received:
EXPECT_FALSE(gamepad.index);
EXPECT_TRUE(gamepad.button_values.empty());
EXPECT_TRUE(gamepad.axes.empty());
// Clicking the button increases the count.
CheckWebsocketCommand(meshcat, R"""({
"type": "gamepad",
"name": "",
"gamepad": {
"index": 1,
"button_values": [0, 0.5],
"axes": [0.1, 0.2, 0.3, 0.4]
}
})""", {}, {});
gamepad = meshcat.GetGamepad();
EXPECT_TRUE(gamepad.index);
EXPECT_EQ(gamepad.index, 1);
std::vector<double> expected_button_values{0, 0.5};
std::vector<double> expected_axes{0.1, 0.2, 0.3, 0.4};
EXPECT_EQ(gamepad.button_values, expected_button_values);
EXPECT_EQ(gamepad.axes, expected_axes);
}
GTEST_TEST(MeshcatTest, SetPropertyWebSocket) {
Meshcat meshcat;
meshcat.SetProperty("/Background", "visible", false);
CheckWebsocketCommand(meshcat, {}, 1, R"""({
"type": "set_property",
"path": "/Background",
"property": "visible",
"value": false
})""");
meshcat.SetProperty("/Grid", "visible", false);
// Note: The order of the messages is due to "/Background" < "/Grid" in the
// std::map, not due to the order that SetProperty was called.
CheckWebsocketCommand(meshcat, {}, 1, R"""({
"type": "set_property",
"path": "/Background",
"property": "visible",
"value": false
})""");
CheckWebsocketCommand(meshcat, {}, 2, R"""({
"type": "set_property",
"path": "/Grid",
"property": "visible",
"value": false
})""");
// Confirm that meshcat.Flush() doesn't crash even when we've had multiple
// clients connect, received data, and disconnect.
meshcat.Flush();
}
GTEST_TEST(MeshcatTest, SetPerspectiveCamera) {
Meshcat meshcat;
Meshcat::PerspectiveCamera perspective;
perspective.fov = 82;
perspective.aspect = 1.5;
meshcat.SetCamera(perspective, "/my/camera");
CheckWebsocketCommand(meshcat, {}, 1, R"""({
"type": "set_object",
"path": "/my/camera",
"object": {
"object": {
"type": "PerspectiveCamera",
"fov": 82.0,
"aspect": 1.5,
"near": 0.01,
"far": 100,
"zoom": 1.0
}
}
})""");
}
GTEST_TEST(MeshcatTest, SetOrthographicCamera) {
Meshcat meshcat;
Meshcat::OrthographicCamera ortho;
ortho.left = -1.23;
ortho.bottom = .84;
meshcat.SetCamera(ortho, "/my/camera");
CheckWebsocketCommand(meshcat, {}, 1, R"""({
"type": "set_object",
"path": "/my/camera",
"object": {
"object": {
"type": "OrthographicCamera",
"left": -1.23,
"right": 1.0,
"top": -1.0,
"bottom": 0.84,
"near": -1000.0,
"far": 1000.0,
"zoom": 1.0
}
}
})""");
}
GTEST_TEST(MeshcatTest, SetAnimation) {
Meshcat meshcat;
MeshcatAnimation animation;
animation.SetTransform(0, "sphere", RigidTransformd(Vector3d{0, 0, 0}));
animation.SetTransform(20, "sphere", RigidTransformd(Vector3d{0, 0, 1}));
animation.SetTransform(40, "sphere", RigidTransformd(Vector3d{0, 0, 0}));
animation.SetProperty(0, "cylinder", "visible", true);
animation.SetProperty(20, "cylinder", "visible", false);
animation.SetProperty(40, "cylinder", "visible", true);
animation.SetProperty(0, "ellipsoid/<object>", "material.opacity", 0.0);
animation.SetProperty(20, "ellipsoid/<object>", "material.opacity", 1.0);
animation.SetProperty(40, "ellipsoid/<object>", "material.opacity", 0.0);
animation.set_loop_mode(MeshcatAnimation::kLoopRepeat);
animation.set_repetitions(4);
animation.set_autoplay(true);
animation.set_clamp_when_finished(true);
meshcat.SetAnimation(animation);
// The animations will be in lexographical order by path since we're using a
// std::map with the path strings as the (sorted) keys.
CheckWebsocketCommand(meshcat, {}, 1, R"""({
"type": "set_animation",
"animations": [{
"path": "/drake/cylinder",
"clip": {
"fps": 32.0,
"name": "default",
"tracks": [{
"name": ".visible",
"type": "boolean",
"keys": [{
"time": 0,
"value": true
},{
"time": 20,
"value": false
},{
"time": 40,
"value": true
}]
}]
}
}, {
"path": "/drake/ellipsoid/<object>",
"clip": {
"fps": 32.0,
"name": "default",
"tracks": [{
"name": ".material.opacity",
"type": "number",
"keys": [{
"time": 0,
"value": 0.0
},{
"time": 20,
"value": 1.0
},{
"time": 40,
"value": 0.0
}]
}]
}
}, {
"path": "/drake/sphere",
"clip": {
"fps": 32.0,
"name": "default",
"tracks": [{
"name": ".position",
"type": "vector3",
"keys": [{
"time": 0,
"value": [0.0, 0.0, 0.0]
},{
"time": 20,
"value": [0.0, 0.0, 1.0]
},{
"time": 40,
"value": [0.0, 0.0, 0.0]
}]
}, {
"name": ".quaternion",
"type": "quaternion",
"keys": [{
"time": 0,
"value": [0.0, 0.0, 0.0, 1.0]
},{
"time": 20,
"value": [0.0, 0.0, 0.0, 1.0]
},{
"time": 40,
"value": [0.0, 0.0, 0.0, 1.0]
}]
}]
}
}],
"options": {
"play": true,
"loopMode": 2201,
"repetitions": 4,
"clampWhenFinished": true
}
})""");
}
GTEST_TEST(MeshcatTest, Set2dRenderMode) {
Meshcat meshcat;
meshcat.Set2dRenderMode();
// We simply confirm that all of the objects have been set, and use
// meshcat_manual_test to check that the visualizer updates as we expect.
EXPECT_FALSE(
meshcat.GetPackedObject("/Cameras/default/rotated").empty());
EXPECT_FALSE(meshcat.GetPackedTransform("/Cameras/default").empty());
EXPECT_FALSE(
meshcat.GetPackedProperty("/Cameras/default/rotated/<object>", "position")
.empty());
EXPECT_FALSE(meshcat.GetPackedProperty("/Background", "visible").empty());
EXPECT_FALSE(meshcat.GetPackedProperty("/Grid", "visible").empty());
EXPECT_FALSE(meshcat.GetPackedProperty("/Axes", "visible").empty());
}
GTEST_TEST(MeshcatTest, ResetRenderMode) {
Meshcat meshcat;
meshcat.ResetRenderMode();
// We simply confirm that all of the objects have been set, and use
// meshcat_manual_test to check that the visualizer updates as we expect.
EXPECT_FALSE(
meshcat.GetPackedObject("/Cameras/default/rotated").empty());
EXPECT_FALSE(meshcat.GetPackedTransform("/Cameras/default").empty());
EXPECT_FALSE(
meshcat.GetPackedProperty("/Cameras/default/rotated/<object>", "position")
.empty());
EXPECT_FALSE(meshcat.GetPackedProperty("/Background", "visible").empty());
EXPECT_FALSE(meshcat.GetPackedProperty("/Grid", "visible").empty());
EXPECT_FALSE(meshcat.GetPackedProperty("/Axes", "visible").empty());
}
GTEST_TEST(MeshcatTest, StaticHtml) {
Meshcat meshcat;
// Call each command that will be saved (at least) once.
meshcat.SetObject("box", Box(.25, .25, .5), Rgba(0, 0, 1, 1));
meshcat.SetTransform("box", RigidTransformd(Vector3d{0, 0, 0}));
meshcat.SetProperty("/Background", "visible", false);
MeshcatAnimation animation;
animation.SetTransform(0, "box", RigidTransformd());
animation.SetTransform(20, "box",
RigidTransformd(RotationMatrixd::MakeZRotation(M_PI)));
const std::string html = meshcat.StaticHtml();
// Confirm that the js source links were replaced.
EXPECT_THAT(html, ::testing::Not(HasSubstr("meshcat.js")));
EXPECT_THAT(html, ::testing::Not(HasSubstr("stats.min.js")));
// The static html replaces the javascript web socket connection code with
// direct invocation of MeshCat with all of the data. We'll confirm that
// this appears to have happened by testing for the presence of the injected
// tree (base64 content) and the absence of what is *believed* to be the
// delimiting text of the connection block.
EXPECT_THAT(html, HasSubstr("data:application/octet-binary;base64"));
EXPECT_THAT(html, ::testing::Not(HasSubstr("CONNECTION BLOCK")));
}
// Check MeshcatParams.hide_stats_plot sends a hide_realtime_rate message
GTEST_TEST(MeshcatTest, RealtimeRatePlot) {
MeshcatParams params;
params.show_stats_plot = true;
Meshcat meshcat(params);
CheckWebsocketCommand(meshcat, {}, 1, R"""({
"type": "show_realtime_rate",
"show": true
})""");
}
} // namespace
} // namespace geometry
} // namespace drake
| [
"noreply@github.com"
] | noreply@github.com |
04642b1e529b56521e9248d197568ebf8c39de55 | b86a4d813c429e364c6df9f55e93178072d67ad9 | /t102.cpp | cfa2343c0c1c3f7456c6560d5ba2eb2b003f867d | [] | no_license | kayneo/Test | 5748677c179fbc355671efbd1e6089cd92a99d53 | f78abc26011a68db1533229ea5ef25819e112e0a | refs/heads/master | 2020-04-01T23:09:23.806325 | 2018-10-22T05:22:17 | 2018-10-22T05:22:17 | 153,744,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | cpp | #include <iostream>
void testsize()
{
printf("%s:%d\n%s:%d\n%s:%d\n%s:%d\n%s:%d\n%s:%d\n",
"short", sizeof(short),
"int", sizeof(int),
"long", sizeof(long),
"long long", sizeof(long long),
"double", sizeof(double),
"long double", sizeof(long double));
}
int main()
{
testsize();
return 0;
} | [
"vision.kt@gmail.com"
] | vision.kt@gmail.com |
7ca65fb54333e87a5a332b1c395bbb38bde380cf | 814c72475e0707cec908dfebb15bf16112f4f344 | /Sanctam3Project/Source/Scene.h | 4912b5990e2a2eae94b2b9b5fbc6bd8b84e5cc1d | [] | no_license | ebichan8741/OriginalGame | d05a21b11a25c2f11870328b46fc5e914ce5c581 | 0e74dc8c1a1ce2023e7838f9f00ede9b7522b661 | refs/heads/develop | 2020-09-09T15:38:02.086956 | 2019-11-17T01:57:09 | 2019-11-17T01:57:09 | 221,258,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h | #pragma once
#include "Sanctam3Project.h"
#define MAX_SCENE (256)
typedef enum
{
PRIOLITY_0 = 0,
PRIOLITY_1,
PRIOLITY_2,
PRIOLITY_3,
PRIOLITY_4,
PRIOLITY_MAX
}PRIOLITY;
class CScene
{
public:
virtual HRESULT Init(void) = 0;
virtual void Uninit(void) = 0;
virtual void Update(void) = 0;
virtual void Draw(void) = 0;
CScene(int nPriolity);
~CScene();
static void UpdateAll(void);
static void DrawAll(void);
static void ReleaseAll(void);
void Release(void);
protected:
float m_LengthSq;
LPDIRECT3DVERTEXBUFFER9 m_pVtxBuff;
static CScene *m_Top[PRIOLITY_MAX];
CScene *m_Next;
bool m_Delete;
};
| [
"t.ebichan0121@gmail.com"
] | t.ebichan0121@gmail.com |
55ab9f8ac44cf4acbc11a45196c91320bd70175a | f407d2792c17a1ceec620d1083b81cccf580ea46 | /RobotArmProject/joint_angle.cpp | 77c348d459fd79ae7daea433eced135005a2cfef | [] | no_license | obushi/RobotArmProject | d7f150233710d6ad4af6320e3ad4ed8dddc0f3b2 | ae9c3720e44ab96e430f72b53955f74a222295f0 | refs/heads/master | 2020-03-18T10:46:00.309429 | 2018-05-24T02:43:13 | 2018-05-24T02:43:13 | 134,632,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,339 | cpp | //
// joint_angle.cpp
// RobotArmProject
//
// Created by NoriyasuObushi on 2018/05/24.
// Copyright © 2018 NoriyasuObushi. All rights reserved.
//
#include "joint_angle.hpp"
namespace robot_arm_project {
JointAngle::JointAngle(double p1, double p2, double p3, double p4, double p5, double p6):
p1(p1), p2(p2), p3(p3), p4(p4), p5(p5), p6(p6) {}
double p1, p2, p3, p4, p5, p6;
void JointAngle::Print() const {
std::cout << "Joint Angles:" << std::endl;
std::cout << "p1[rad] : " << p1 << std::endl;
std::cout << "p2[rad] : " << p2 << std::endl;
std::cout << "p3[rad] : " << p3 << std::endl;
std::cout << "p4[rad] : " << p4 << std::endl;
std::cout << "p5[rad] : " << p5 << std::endl;
std::cout << "p6[rad] : " << p6 << std::endl;
}
void JointAngle::PrintDegree() const {
std::cout << "Joint Angles:" << std::endl;
std::cout << "p1[deg] : " << Rad2Deg(p1) << std::endl;
std::cout << "p2[deg] : " << Rad2Deg(p2) << std::endl;
std::cout << "p3[deg] : " << Rad2Deg(p3) << std::endl;
std::cout << "p4[deg] : " << Rad2Deg(p4) << std::endl;
std::cout << "p5[deg] : " << Rad2Deg(p5) << std::endl;
std::cout << "p6[deg] : " << Rad2Deg(p6) << std::endl;
}
} // namespace robot_arm_project
| [
"nryas@me.com"
] | nryas@me.com |
aadb025f543c2566502127e97c618d3ad9ad5f6c | 4c0c57f9ddb87f46d58192e1ebfd2c40f6d2c315 | /tdutils/td/utils/optional.h | f9d122b0dc8e69be95988170a0c14da0075fcf7c | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | luckydonald-backup/td | 9693cf868b3afdc5b5257e95e37af79380472d0b | 71d03f39c364367a8a7c51f783a41099297de826 | refs/heads/master | 2021-09-02T08:08:18.834827 | 2018-12-31T19:04:05 | 2017-12-31T20:08:40 | 115,928,341 | 2 | 0 | null | 2018-01-01T15:37:21 | 2018-01-01T15:37:20 | null | UTF-8 | C++ | false | false | 685 | h | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2017
//
// 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)
//
#pragma once
#include "td/utils/Status.h"
#include <utility>
namespace td {
template <class T>
class optional {
public:
optional() = default;
template <class T1>
optional(T1 &&t) : impl_(std::forward<T1>(t)) {
}
explicit operator bool() {
return impl_.is_ok();
}
T &value() {
return impl_.ok_ref();
}
T &operator*() {
return value();
}
private:
Result<T> impl_;
};
} // namespace td
| [
"arseny30@gmail.com"
] | arseny30@gmail.com |
d8cd12e387fdb4d07bccda7f25b3d441a66ddf4a | 707571467d58baed5944d814506f1e0d0164a7db | /EmployeeApp/EmployeeApp/Employee.cpp | a41d909a0130d9cf363634100c418e8412906873 | [] | no_license | maciek1maciek/EmployeeApp | 6d5326b6001080390e369b3de7813f23954f672d | 4ff9c2e50ea934cdd9c28267287e1200ed40cd20 | refs/heads/main | 2023-02-24T08:24:36.973382 | 2021-01-27T22:14:39 | 2021-01-27T22:14:39 | 330,741,788 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,139 | cpp | #include <iostream>
#include "Employee.h"
#include <cstring>
using namespace std;
Employee::Employee(string name, string surname, int seniority, int salary, position p):name(name),surname(surname),seniority(seniority),salary(salary),p(p){
enumChange(p);
}
string Employee::enumChange(position p) {
switch (p) {
case 1:
valEnum= "Team Leader";
break;
case 2:
valEnum = "Scrum Master";
break;
case 3:
valEnum = "Junior Dev";
break;
case 4:
valEnum = "Mid Dev";
break;
case 5:
valEnum = "Senior Dev";
break;
}
return valEnum;
}
ostream& operator<<(std::ostream& out, const Employee& emp) {
out <<
" Imie: " << emp.name << "\n" <<
" Nazwisko: " << emp.surname << "\n" <<
" staz: " << emp.seniority << "(w miesiacach) " << "\n" <<
" pensja: " << emp.salary << "\n" <<
" stanowisko: " << emp.valEnum << " \n" <<
" ";
return out;
}
string Employee::getName() {
return name;
}
string Employee::getSurname() {
return surname;
}
int Employee::getSeniority() {
return seniority;
}
int Employee::getSalary() {
return salary;
}
position Employee::getPosition() {
return p;
}
| [
"maciejkoczyk@gmail.com"
] | maciejkoczyk@gmail.com |
03b1dbe957611e63877b6062c8ece9d9aafd0f1f | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/abc106/A/4708036.cpp | ca0afc56f4b5de3d6a0cecdbbbb0fea129d7d956 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 112 | cpp | #include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
cout << (a-1)*(b-1) << endl;
} | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
d90921dc792847efdded961361f55f4f37fcef8a | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE427_Uncontrolled_Search_Path_Element/CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83_goodG2B.cpp | e138108476074c7591055db689aa9c8432bff85b | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,396 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83_goodG2B.cpp
Label Definition File: CWE427_Uncontrolled_Search_Path_Element.label.xml
Template File: sources-sink-83_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 427 Uncontrolled Search Path Element
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Use a hardcoded path
* Sinks:
* BadSink : Set the environment variable
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83.h"
namespace CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83
{
CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83_goodG2B::CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83_goodG2B(char * dataCopy)
{
data = dataCopy;
/* FIX: Set the path as the "system" path */
strcat(data, NEW_PATH);
}
CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83_goodG2B::~CWE427_Uncontrolled_Search_Path_Element__char_connect_socket_83_goodG2B()
{
/* POTENTIAL FLAW: Set a new environment variable with a path that is possibly insecure */
PUTENV(data);
}
}
#endif /* OMITGOOD */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
ac341bfeb9709a2fda3d5efa376140ebca3da0f2 | cd99ca9461435d1417cb146d966e54272fbcc7ad | /3rd party/maxsdk/samples/modifiers/uvwunwrap/uvwunwrap/ToolSolver.cpp | 73e9dce157e6b4602a1e18660651980987d7b56a | [] | no_license | mortany/xray15 | eacce7965e785dd71d1877eae25c1f9eff680eec | 72a13fb24e9b388850bc769427c231da8f599228 | refs/heads/master | 2020-08-02T20:45:23.493981 | 2019-10-14T18:48:48 | 2019-10-14T18:48:48 | 211,499,718 | 0 | 0 | null | 2019-09-28T12:50:47 | 2019-09-28T12:50:46 | null | UTF-8 | C++ | false | false | 7,963 | cpp | /*
Copyright 2010 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.
*/
#include "unwrap.h"
#include "modsres.h"
BOOL Solver::Solve(int startFrame, int endFrame, int samples,
Tab<EdgeBondage> &springs, Tab<SpringClass> &vertexData,
float stiffness, float dampening, float decay,
UnwrapMod *mod, MeshTopoData *ld, BOOL updateViewport)
{
BOOL biret = TRUE;
int tps = GetTicksPerFrame();
int sampleInc = tps/samples;
BitArray lockedVerts;
lockedVerts.SetSize(vertexData.Count());
lockedVerts.ClearAll();
Box3 boundsVert;
boundsVert.Init();
for (int i = 0; i < springs.Count(); i++)
{
if (springs[i].isEdge)
{
int a= springs[i].v2;
if ((a < 0) || (a>=lockedVerts.GetSize()))
{
}
else
{
boundsVert += vertexData[a].pos;
lockedVerts.Set(a);
}
}
}
Point3 boxVec = boundsVert.pmax-boundsVert.pmin;
maxVelocity = Length(boxVec)*0.05f;
for (int i = 0; i < vertexData.Count(); i++)
{
if (vertexData[i].weight == 0.0f)
lockedVerts.Set(i);
}
vertsToProcess.ZeroCount();
for (int i = 0; i < vertexData.Count(); i++)
{
if (!lockedVerts[i])
vertsToProcess.Append(1,&i,10000);
}
holdHoldVertexData = vertexData;
int frames = endFrame-startFrame;
for (int i = startFrame; i < (frames*tps); i+=tps)
{
if (ld->GetUserCancel())
{
i = (frames*tps);
biret = FALSE;
}
TimeValue sampleTime = i;
for (int k =0; k < samples; k++)
{
sampleTime += sampleInc;
Evaluate(springs, vertexData,
i,
samples,
stiffness, dampening);
// Evaluate(lmd, sampleTime,t, nv, os,samples,1.0f);
for (int k=0;k<vertsToProcess.Count();k++)
{
int index = vertsToProcess[k];
vertexData[index].vel *= decay;
}
}
if (mod && ((i%4) == 0) && ld)
{
TimeValue t = GetCOREInterface()->GetTime();
for (int j = 0; j < vertsToProcess.Count(); j++)
{
int index = vertsToProcess[j];
Point3 p = vertexData[index].pos;
ld->SetTVVert(t,index,p);
}
mod->peltData.ResolvePatchHandles();
mod->InvalidateView();
if (updateViewport)
{
mod->NotifyDependents(FOREVER, PART_TEXMAP, REFMSG_CHANGE);
UpdateWindow(mod->hDialogWnd);
if (mod->ip) mod->ip->RedrawViews(t);
}
}
}
return biret;
}
void Solver::Evaluate(Tab<EdgeBondage> &springs, Tab<SpringClass> &vertexData,
TimeValue i,
int samples,
float &stiffness, float &dampening)
{
for (int j = 0; j < vertsToProcess.Count(); j++)
{
int index = vertsToProcess[j];
holdHoldVertexData[index] = vertexData[index];
}
SolveFrame(0, springs, vertexData,
stiffness, dampening);
int solver = 4;
float time = 1.0f;//( 1.0f/(float)samples); //put back with a multiplier in 4+
if (solver >= 1)
{
for (int id=0;id<vertsToProcess.Count();id++)
{
int j = vertsToProcess[id];
vertexData[j].tempPos[0] = vertexData[j].pos;
vertexData[j].pos = vertexData[j].pos + vertexData[j].tempVel[0] * (0.5f*time);
}
SolveFrame(1, springs, vertexData,
stiffness, dampening);
}
if (solver > 1)
{
for (int id=0;id<vertsToProcess.Count();id++)
{
int j = vertsToProcess[id];
vertexData[j].pos = vertexData[j].tempPos[0] + vertexData[j].tempVel[1] * 0.5f*time;
}
SolveFrame(2, springs, vertexData,
// i,
// samples,
stiffness, dampening);
// Solve(2, lmd, tempT, t, nv, os,samples);
for (int id=0;id<vertsToProcess.Count();id++)
{
int j = vertsToProcess[id];
vertexData[j].pos = vertexData[j].tempPos[0] + vertexData[j].tempVel[2] *0.5f*time;
}
SolveFrame(3, springs, vertexData,
stiffness, dampening);
for (int id=0;id<vertsToProcess.Count();id++)
{
int j = vertsToProcess[id];
vertexData[j].pos = vertexData[j].tempPos[0] + vertexData[j].tempVel[3]*time;
}
SolveFrame(4, springs, vertexData,
stiffness, dampening);
}
float largestVelocityChange = 0.0f;
for (int id=0;id<vertsToProcess.Count();id++)
{
int j = vertsToProcess[id];
vertexData[j].vel += vertexData[j].tempVel[0]/6.0f +
vertexData[j].tempVel[1]/3.0f +
vertexData[j].tempVel[2]/3.0f +
vertexData[j].tempVel[3]/6.0f ;
float w = vertexData[j].weight;
vertexData[j].vel *= w;
vertexData[j].pos = vertexData[j].tempPos[0];
Point3 v = vertexData[j].vel*time;
float velMag = Length(vertexData[j].vel);
if (velMag > largestVelocityChange)
largestVelocityChange = velMag;
vertexData[j].pos += v;
}
BOOL error = FALSE;
BOOL backStep = FALSE;
if (largestVelocityChange > (maxVelocity*0.1f))
error = TRUE;
if (largestVelocityChange > (maxVelocity))
backStep = TRUE;
if (error)
{
stiffness *= 0.9f;
dampening *= 0.9f;
if (backStep)
{
for (int i = 0; i < vertsToProcess.Count(); i++)
{
int index = vertsToProcess[i];
vertexData[index] = holdHoldVertexData[index];
}
}
}
}
void Solver::SolveFrame(int level,
Tab<EdgeBondage> &springs, Tab<SpringClass> &vertexData,
float strength, float dampening)
{
int nv = vertexData.Count();
float time = 1.0f;//( 1.0f/(float)samples); put back with a multiplier in 4+
//do springs
for (int id=0;id<vertsToProcess.Count();id++)
{
int j = vertsToProcess[id];
vertexData[j].tempVel[level].x = 0.0f;
vertexData[j].tempVel[level].y = 0.0f;
vertexData[j].tempVel[level].z = 0.0f;
}
for (int j=0; j<springs.Count();j++)
{
int a = springs[j].v1;
int b = springs[j].v2;
if ((a>=0) && (a<nv) && (b>=0) && (b<nv))
{
Point3 p1,p2;
Point3 v1(0.0f,0.0f,0.0f),v2(0.0f,0.0f,0.0f);
p1 = vertexData[a].pos;
v1 = vertexData[a].vel;
p2 = vertexData[b].pos;
v2 = vertexData[b].vel;
float wa = vertexData[a].weight;
float wb = vertexData[b].weight;
if ( (wa == 0.0f) && (wb == 0.0f))
{
}
else
{
Point3 l = p1-p2;
float len = 0.0f;
float restLen = 0.0f;
float str = strength;// * springs[j].extraStiffness;
float damp = dampening;// * springs[j].extraStiffness;
if (springs[j].cornerIndex == -1)
{
len = Length(p2-p1);
restLen = springs[j].dist;// * springs[j].distPer;
}
else
{
Point3 cp = vertexData[springs[j].cornerIndex].pos;
p1.z = 0.0f;
p2.z = 0.0f;
cp.z = 0.0f;
Point3 vecA, vecB;
vecA = Normalize(p1 - cp);
vecB = Normalize(p2 - cp);
float dot = DotProd(vecA,vecB);
float angle = 0.0f;
if (dot == -1.0)
angle = 0.0f;
else if (dot == 0.0)
angle = PI*0.5f;
else if (dot >= 1.0)
angle = PI;
else
{
angle = acos(dot);
}
len = angle;
restLen = springs[j].dist;// * springs[j].distPer;
str *= 0.01f;
damp *= 0.01f;
}
Point3 dvel = v1-v2;
if (len < 0.0001f)
{
}
else
{
if (restLen != len)
{
Point3 v;
if (springs[j].cornerIndex == -1)
v = ((str)*(len-restLen)) * l/len;
else v = ((str)*(len-restLen)+(damp)*((DotProd(dvel,l))/len)) * l/len;
if (springs[j].isEdge) v *= 2.0f;
v *= time;
v *= springs[j].str;
vertexData[a].tempVel[level] -= v;
vertexData[b].tempVel[level] += v;
// vertexData[a].tempVel[level].z += 0.000001f;
// vertexData[b].tempVel[level].z += 0.000001f;
}
}
}
}
}
}
| [
"cheatmaster1@mail.ru"
] | cheatmaster1@mail.ru |
f8049fb637ea3db417dd3ad39c9efb6214f9fb69 | 27b10c2d1576ee4a2a31b62b40e984ec1b623525 | /Dev01_Handout_Completed/Motor2D/j1Input.h | dafa5fdbb0b467a2724e605207449ff09ee256d7 | [] | no_license | Arnau77/DESVJ-Platformer_Arnau_Miquel | 6161be0a68edd5f341aabe4fdce6a276dd7591bb | d3ef629eaf3ad0341f2c5fb5928b7fb675218d5e | refs/heads/master | 2020-08-04T01:32:50.349515 | 2019-11-17T19:34:51 | 2019-11-17T19:34:51 | 211,954,920 | 0 | 0 | null | 2019-09-30T20:53:41 | 2019-09-30T20:53:40 | null | UTF-8 | C++ | false | false | 1,383 | h | #ifndef __j1INPUT_H__
#define __j1INPUT_H__
#include "j1Module.h"
#define NUM_KEYS 352
#define NUM_MOUSE_BUTTONS 5
#define LAST_KEYS_PRESSED_BUFFER 50
struct SDL_Rect;
enum j1EventWindow
{
WE_QUIT = 0,
WE_HIDE = 1,
WE_SHOW = 2,
WE_COUNT
};
enum j1KeyState
{
KS_IDLE = 0,
KS_DOWN,
KS_REPEAT,
KS_UP
};
class j1Input : public j1Module
{
public:
j1Input();
// Destructor
virtual ~j1Input();
// Called before render is available
bool Awake(pugi::xml_node *);
// Called before the first frame
bool Start();
// Called each loop iteration
bool PreUpdate();
// Called before quitting
bool CleanUp();
// Gather relevant win events
bool GetWindowEvent(j1EventWindow ev);
// Check key states (includes mouse and joy buttons)
bool GetKeyDown(int code);
bool GetKeyRepeat(int code);
bool GetKeyUp(int code);
// Check if a certain window event happened
bool GetWindowEvent(int code);
// Get mouse / axis position
void GetMousePosition(int &x, int &y);
void GetMouseMotion(int& x, int& y);
bool GetMouseButtonDown(int code);
bool GetMouseButtonRepeat(int code);
bool GetMouseButtonUp(int code);
private:
void CleanKeys();
private:
bool windowEvents[WE_COUNT];
j1KeyState keyState[NUM_KEYS];
j1KeyState mouse_buttons[NUM_MOUSE_BUTTONS];
int mouse_motion_x;
int mouse_motion_y;
int mouse_x;
int mouse_y;
};
#endif // __j1INPUT_H__ | [
"sg.miquel@gmail.com"
] | sg.miquel@gmail.com |
e7bdbf1a4314cd9c9a5b8820b4640545e9e1f3fa | cb2ea99f0258daab254f9aad168225dd294a4957 | /ex.cpp | e5ad6d08d9d423a34c2141ea05485a26b1d78d84 | [] | no_license | abhishekkarayala187/vs_code_practise | 0873bd7be3a87f35fd2fdd6e4764051bb29d94eb | 55acd8b4670c18fa42650bde1c5a511f4a83d2ca | refs/heads/master | 2023-07-13T17:53:11.099298 | 2021-08-27T19:24:07 | 2021-08-27T19:24:07 | 366,817,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 278 | cpp | #include<iostream>
#include<string>
using namespace std;
int main(){
int num, integer = 1;
cin>>num;
for(int j = 1; j <= num; j++){
for (int i = 1; i <= j; i++){
cout<<integer <<" ";
integer++;
}
cout<<endl;
}
} | [
"Abhishek"
] | Abhishek |
78d0f4c1a06f95d14773f19fa69e44b0ad046b1e | bb2b93a6a738bcb0a62c2c46e721e05732357de4 | /Software/ann_arbor_percussion_synthesizer_test/src/AnnArborPercussionControlsFactory.test.cpp | 72285be903aa31a1d58ddfeb701b385f6591dcdf | [
"MIT"
] | permissive | XiNNiW/Ann-Arbor-Percussion-Synthesizer | 5082bd01527bf5dea1895338712aa2cc1c4e6451 | 48dac491c5d9d81e28842283657b7392e96ff1d8 | refs/heads/master | 2021-04-28T15:33:10.391144 | 2018-02-27T03:34:20 | 2018-02-27T03:34:20 | 121,990,911 | 0 | 0 | null | 2018-02-18T21:09:03 | 2018-02-18T21:09:03 | null | UTF-8 | C++ | false | false | 4,433 | cpp | /*
* AnnArborPercussionControlsFactory.test.cpp
*
* Created on: Feb 25, 2018
* Author: xinniw
*/
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <AnnArborPercussionControlsFactory.h>
#include "MockPlatformProvider.h"
#include "MockKnob.h"
using AnnArborPercussion::AnnArborPercussionControlsFactory;
TEST(AnnArborPercussionControlsFactoryTest, create_length_knob_passes_the_right_parameters) {
MockPlatformProvider mockProvider;
MockKnob mockLengthKnob;
int pinForDrumLengthKnob = 14;
int minValueForDrumLengthKnob = 0;
int maxValueForDrumLengthKnob = 2000;
EXPECT_CALL(mockProvider,
createKnob(
pinForDrumLengthKnob,
minValueForDrumLengthKnob,
maxValueForDrumLengthKnob
)
).Times(1).WillOnce(testing::Return(&mockLengthKnob));
AnnArborPercussionControlsFactory* controlsFactory = new AnnArborPercussionControlsFactory();
KnobInterface* actualKnob = controlsFactory->createLengthKnob(&mockProvider);
int expectedDrumLength = 5;
EXPECT_CALL(mockLengthKnob, getValue()).Times(1).WillOnce(testing::Return(expectedDrumLength));
EXPECT_EQ(actualKnob->getValue(), expectedDrumLength);
}
TEST(AnnArborPercussionControlsFactoryTest, create_motion_knob_passes_the_right_parameters) {
MockPlatformProvider mockProvider;
MockKnob mockMotionKnob;
int pinForDrumMotionKnob = 21;
int minValueForDrumMotionKnob = 1;
int maxValueForDrumMotionKnob = 2000;
EXPECT_CALL(mockProvider,
createKnob(
pinForDrumMotionKnob,
minValueForDrumMotionKnob,
maxValueForDrumMotionKnob
)
).Times(1).WillOnce(testing::Return(&mockMotionKnob));
AnnArborPercussionControlsFactory* controlsFactory = new AnnArborPercussionControlsFactory();
KnobInterface* actualKnob = controlsFactory->createMotionKnob(&mockProvider);
int expectedDrumMotion = 54;
EXPECT_CALL(mockMotionKnob, getValue()).Times(1).WillOnce(testing::Return(expectedDrumMotion));
EXPECT_EQ(actualKnob->getValue(), expectedDrumMotion);
}
TEST(AnnArborPercussionControlsFactoryTest, create_frequency_knob_passes_the_right_parameters) {
MockPlatformProvider mockProvider;
MockKnob mockFrequencyKnob;
int pinForDrumFrequencyKnob = 15;
int minValueForDrumFrequencyKnob = 20;
int maxValueForDrumFrequencyKnob = 2500;
EXPECT_CALL(mockProvider,
createKnob(
pinForDrumFrequencyKnob,
minValueForDrumFrequencyKnob,
maxValueForDrumFrequencyKnob
)
).Times(1).WillOnce(testing::Return(&mockFrequencyKnob));
AnnArborPercussionControlsFactory* controlsFactory = new AnnArborPercussionControlsFactory();
KnobInterface* actualKnob = controlsFactory->createFrequencyKnob(&mockProvider);
int expectedDrumFrequency = 1400;
EXPECT_CALL(mockFrequencyKnob, getValue()).Times(1).WillOnce(testing::Return(expectedDrumFrequency));
EXPECT_EQ(actualKnob->getValue(), expectedDrumFrequency);
}
TEST(AnnArborPercussionControlsFactoryTest, create_teeth_knob_passes_the_right_parameters) {
MockPlatformProvider mockProvider;
MockKnob mockTeethKnob;
int pinForDrumTeethKnob = 20;
int minValueForDrumTeethKnob = 1;
int maxValueForDrumTeethKnob = 2000;
EXPECT_CALL(mockProvider,
createKnob(
pinForDrumTeethKnob,
minValueForDrumTeethKnob,
maxValueForDrumTeethKnob
)
).Times(1).WillOnce(testing::Return(&mockTeethKnob));
AnnArborPercussionControlsFactory* controlsFactory = new AnnArborPercussionControlsFactory();
KnobInterface* actualKnob = controlsFactory->createTeethKnob(&mockProvider);
int expectedDrumTeeth = 540;
EXPECT_CALL(mockTeethKnob, getValue()).Times(1).WillOnce(testing::Return(expectedDrumTeeth));
EXPECT_EQ(actualKnob->getValue(), expectedDrumTeeth);
}
TEST(AnnArborPercussionControlsFactoryTest, create_mod_knob_passes_the_right_parameters) {
MockPlatformProvider mockProvider;
MockKnob mockModKnob;
int pinForDrumModKnob = 16;
int minValueForDrumModKnob = 1;
int maxValueForDrumModKnob = 2000;
EXPECT_CALL(mockProvider,
createKnob(
pinForDrumModKnob,
minValueForDrumModKnob,
maxValueForDrumModKnob
)
).Times(1).WillOnce(testing::Return(&mockModKnob));
AnnArborPercussionControlsFactory* controlsFactory = new AnnArborPercussionControlsFactory();
KnobInterface* actualKnob = controlsFactory->createModKnob(&mockProvider);
int expectedDrumTeeth = 240;
EXPECT_CALL(mockModKnob, getValue()).Times(1).WillOnce(testing::Return(expectedDrumTeeth));
EXPECT_EQ(actualKnob->getValue(), expectedDrumTeeth);
}
| [
"dlminnix09@gmail.com"
] | dlminnix09@gmail.com |
534ebbfdc1afdc9e2d7a13432c07fe56a2bc0377 | 668ebb505f4d8932e67dfdd1b24a99edcd4d880e | /5596.cpp | 23d7ad54159b6af88c1d7af90d5a9ae6f0968fec | [] | no_license | jpark1607/baekjoon_Cplusplus | 06df940723ffb18ad142b267bae636e78ac610d8 | 8a1f4749d946bc256998ef9903098c8da6da1926 | refs/heads/master | 2021-07-13T03:47:29.002547 | 2021-07-11T14:01:10 | 2021-07-11T14:01:10 | 51,923,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 259 | cpp | #include <stdio.h>
int main(void) {
int A, B, C, D;
int S, T;
scanf("%d %d %d %d", &A, &B, &C, &D);
S = A + B + C + D;
scanf("%d %d %d %d", &A, &B, &C, &D);
T = A + B + C + D;
if(S > T)
printf("%d", S);
else
printf("%d", T);
return 0;
}
| [
"jpark1607@gmail.com"
] | jpark1607@gmail.com |
cf5002249ec0c5d67b75b15dfeb56f149b569162 | 79fe9da6524f97ad4cc14800371b24089ae9fef9 | /Stacks/LC_DailyTemperatures.cpp | 3562d57467ead19656b7bbf113ebfc1dc21c316e | [] | no_license | kodegod/Interview-Preparation | 1502dbc8c9bd2a09daa964ecea87f4fb2ac35328 | 8047d5dea489e257f5b88763907dd86192ead1d3 | refs/heads/main | 2023-08-06T23:21:40.429586 | 2021-10-01T20:13:06 | 2021-10-01T20:13:06 | 314,172,331 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | //https://leetcode.com/problems/daily-temperatures/
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& nums) {
int n = nums.size();
stack<int> s;
s.push(0);
vector<int> ans(n);
for(int i=1; i<n; i++)
{
while(s.size()>0 && nums[i] > nums[s.top()])
{
ans[s.top()] = i - s.top();
s.pop();
}
s.push(i);
}
return ans;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
83149016e704e58611d1fdaf09e54f73c3460ac1 | a811a787be8f306efaa0e32b2c037621328bb991 | /MPI-Cocktail-Project/MPI-Cocktail-Project/dispenser.cpp | a2d5d2a5dcdeca50fc5251df3e5c02fb80a6e5da | [] | no_license | maxmacstn/lpcxpresso-cocktail-machine | 540f448e024e995cd89574ec2b32e2682f1716aa | 474eca910d0d94825769f8dfc4bc42568735ce67 | refs/heads/master | 2020-04-05T01:07:43.348086 | 2018-11-22T10:24:48 | 2018-11-22T10:24:48 | 156,424,601 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,745 | cpp | #include "Dispenser.h"
Dispenser::Dispenser() {
dispenseTimer.start();
ms_counter = dispenseTimer.read_ms();
}
void Dispenser::addIngredient(Ingredient* ingredient) {
// pwmOut[totalIngredient] = new PwmOut(P2_0);
ingredientStartTime[ingredients.size()] = 0;
ingredientStopTime[ingredients.size()] = 0;
ingredients.push_back(ingredient);
}
void Dispenser::addIngredients(vector<Ingredient*> newIngredients){
ingredients.insert(ingredients.end(), newIngredients.begin(), newIngredients.end()); //Append vector
}
int Dispenser:: getIngredientIndex(Ingredient* ingredient){
for(int i = 0; i < ingredients.size(); i++){
if (ingredients[i] == ingredient){
return i;
}
}
return -1;
}
void Dispenser::dispense(int ingredientNo, int ms) {
ingredientStartTime[ingredientNo] = ms_counter;
ingredientStopTime[ingredientNo] = ms + ms_counter;
}
void Dispenser::dispense(Ingredient* ingredient, int sec) {
dispense(this->getIngredientIndex(ingredient),sec);
}
vector< pair<string, pair<float, int> > > Dispenser :: calculate_each_pump(Recipe* recipe,float quantity)
{
vector< pair<Ingredient* ,float> > recipe_portion_list = recipe->getIngredient_portion();
vector< pair<string, pair<float, int> > > result_components;
for(int i = 0; i < recipe_portion_list.size(); i++)
{
pair<string, pair<float, int> > tmp;
float qty = recipe_portion_list[i].second * quantity;
// int time_taken = (qty / flowrate) * 1000; //non - dynamic flowrate
int time_taken = (qty / (recipe_portion_list[i].first->getFlowRate())) * 1000; //Dynamic flow rate for each ingredient
pair<float, int> qty_time;
qty_time = make_pair(qty, time_taken);
tmp = make_pair(recipe_portion_list[i].first->getName(), qty_time);
result_components.push_back(tmp);
}
return result_components;
}
// Dispense by recipe
void Dispenser :: dispense(Recipe* recipe,float quantity)
{
vector< pair<Ingredient* ,float> > recipe_portion_list = recipe->getIngredient_portion();
vector< pair<string, float> > result_components;
for(int i = 0; i < recipe_portion_list.size(); i++)
{
pair<string, float> tmp;
float qty = recipe_portion_list[i].second * quantity;
tmp = make_pair(recipe_portion_list[i].first->getName(), qty);
result_components.push_back(tmp);
// int time_taken = (qty / flowrate) * 1000; //non - dynamic flowrate
int time_taken = (qty / (recipe_portion_list[i].first->getFlowRate())) * 1000; //Dynamic flow rate for each ingredient
dispense(recipe_portion_list[i].first, time_taken);
}
}
void Dispenser::run() {
ms_counter = dispenseTimer.read_ms();
for (int i = 0; i < ingredients.size(); i++) {
if (ingredientStopTime[i] > ms_counter) {
ingredients[i]->getPWMOut().write(ingredients[i]->getDispenseSpeed());
} else {
ingredients[i]->getPWMOut().write(0);
}
}
}
void Dispenser::stopDispenseAll() {
for (int i = 0; i < ingredients.size(); i++) {
ingredientStopTime[i] = 0;
}
}
int Dispenser::getDispenseProgress(Ingredient* ingredient){
int index = this->getIngredientIndex(ingredient);
if (index == -1)
return -1;
if(ingredientStopTime[index] <= ms_counter){
return 100;
}
else{
return 100 - (((float)(ingredientStopTime[index] - ms_counter) / (ingredientStopTime[index] - ingredientStartTime[index]))*100);
}
}
int Dispenser :: getTotalDispenseProgress()
{
int min = INT_MAX;
for(int i = 0; i < ingredients.size(); i++)
{
if(getDispenseProgress(ingredients[i]) < min)
{
min = getDispenseProgress(ingredients[i]);
}
}
return min;
}
//
//float Dispenser :: getTimeFromQuantity(float quantity)
//{
// return quantity/flowrate;
//}
//
//float Dispenser :: getQuantityFromTime(float time)
//{
// return time * flowrate;
//}
| [
"max2.-@hotmail.com"
] | max2.-@hotmail.com |
2ff7c2b4ac3e29606858cbe919f9b9cc73819d7b | a5ef9538cfcc125eb8d3ea9119a38b50e14a0285 | /Commands/Quit.h | 476d42ad16ffc733c52d23da1d8bf4beeacf74d9 | [] | no_license | WasseemB/Dna-Analyzer-Project | 7e4f990e8e73b54953e3098402830f81239ea585 | 15ad707ee319440089d5571f997f068e056a30d2 | refs/heads/master | 2023-05-07T22:42:47.548629 | 2020-03-17T12:01:59 | 2020-03-17T12:01:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | h | //
// Created by Wasseem Bazbaz on 16/03/2020.
//
#ifndef DNASEQUENCE_QUIT_H
#define DNASEQUENCE_QUIT_H
#include "Command.h"
class Quit : public Command {
public:
Quit() {};
void run(std::vector<std::string> args);
int parse(std::vector<std::string> args) { return 1; };
std::string getHelp();
std::string getInfo();
private:
static const std::string s_HELP;
static const std::string s_INFO;
};
#endif //DNASEQUENCE_QUIT_H
| [
"the.waswas@gmail.com"
] | the.waswas@gmail.com |
9038894bdf341c698d88a26d143ab34a20e921d7 | 5c938206b689772fc8562493b5916c5591d3cf4d | /Arduino-to-processing_LEDS.ino | e29e677dd5b2b0960e76856b331b6eb444ab825f | [] | no_license | unicornrobot/conductive-tufted-divination | 53d8cc1e330894e7e500ee36ecf5ad8d8f0d60eb | 13a10dec29cf5f68de154bb2018abbe4dc70576e | refs/heads/main | 2023-07-04T01:41:26.550547 | 2021-08-13T16:58:55 | 2021-08-13T16:58:55 | 391,162,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,036 | ino | // Sensor0 Touch 0 = I04 - GREEN WIRE - ORANGE TUFT
// Sensor1 Touch 6 = IO14 - RED WIRE - RED TUFT
// Sensor2 Touch 3 = IO15 - BLUE WIRE - BLUE TUFT
// Sensor3 Touch 5 = IO12 - BLACK WIRE - LIME TUFT
// Sensor4 Touch 4 = IO13 - YELLOW WIRE - PINK TUFT
#include <Adafruit_NeoPixel.h>
//LED pin
#define PIN 2 //gpio2
int range0,range1,range2,range3,range4 = 0;
// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(12, PIN, NEO_GRB + NEO_KHZ800);
#include <TouchLib.h>
/*
* Code generated by TouchLib SemiAutoTuning.
*
* Hardware configuration:
* sensor 0: type: capacitive (touchRead()) method), pin 4
*/
/*
* Number of sensors. For capacitive sensors: needs to be a minimum of 2. When
* using only one sensor, set N_SENSORS to 2 and use an unused analog input pin for the second
* sensor. For 2 or more sensors you don't need to add an unused analog input.
*/
#define N_SENSORS 5
/*
* Number of measurements per sensor to take in one cycle. More measurements
* means more noise reduction / spreading, but is also slower.
*/
#define N_MEASUREMENTS_PER_SENSOR 16
/* tlSensors is the actual object that contains all the sensors */
TLSensors<N_SENSORS, N_MEASUREMENTS_PER_SENSOR> tlSensors;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pixels.begin(); // This initializes the NeoPixel library.
pixels.setBrightness(20);
pixels.clear();
/*
/*
* Configuration for sensor 0:
* Type: capacitive (touchRead() method)
* Pin: 4 - GREEN WIRE
*/
tlSensors.initialize(0, TLSampleMethodTouchRead);
tlSensors.data[0].tlStructSampleMethod.touchRead.pin = 4;
tlSensors.data[0].releasedToApproachedThreshold = 558;
tlSensors.data[0].approachedToReleasedThreshold = 502;
tlSensors.data[0].approachedToPressedThreshold = 9586;
tlSensors.data[0].pressedToApproachedThreshold = 8627;
tlSensors.data[0].calibratedMaxDelta = 20929;
tlSensors.data[0].filterType = TLStruct::filterTypeAverage;
/*
* Configuration for sensor 1:
* Type: capacitive (touchRead() method)
* Pin: 14
*/
tlSensors.initialize(1, TLSampleMethodTouchRead);
tlSensors.data[1].tlStructSampleMethod.touchRead.pin = 14;
tlSensors.data[1].releasedToApproachedThreshold = 321;
tlSensors.data[1].approachedToReleasedThreshold = 289;
tlSensors.data[1].approachedToPressedThreshold = 12927;
tlSensors.data[1].pressedToApproachedThreshold = 11634;
tlSensors.data[1].calibratedMaxDelta = 27378;
tlSensors.data[1].filterType = TLStruct::filterTypeAverage;
/*
* Configuration for sensor 2:
* Type: capacitive (touchRead() method)
* Pin: 15
*/
tlSensors.initialize(2, TLSampleMethodTouchRead);
tlSensors.data[2].tlStructSampleMethod.touchRead.pin = 15;
tlSensors.data[2].releasedToApproachedThreshold = 290;
tlSensors.data[2].approachedToReleasedThreshold = 1262;
tlSensors.data[2].approachedToPressedThreshold = 11690;
tlSensors.data[2].pressedToApproachedThreshold = 10521;
tlSensors.data[2].calibratedMaxDelta = 24154;
tlSensors.data[2].filterType = TLStruct::filterTypeAverage;
/*
* Configuration for sensor 3:
* Type: capacitive (touchRead() method)
* Pin: 12
*/
tlSensors.initialize(3, TLSampleMethodTouchRead);
tlSensors.data[3].tlStructSampleMethod.touchRead.pin = 12;
tlSensors.data[3].releasedToApproachedThreshold = 240;
tlSensors.data[3].approachedToReleasedThreshold = 1077;
tlSensors.data[3].approachedToPressedThreshold = 9581;
tlSensors.data[3].pressedToApproachedThreshold = 10123;
tlSensors.data[3].calibratedMaxDelta = 20087;
tlSensors.data[3].filterType = TLStruct::filterTypeAverage;
/*
* Configuration for sensor 4:
* Type: capacitive (touchRead() method)
* Pin: 13
*/
tlSensors.initialize(4, TLSampleMethodTouchRead);
tlSensors.data[4].tlStructSampleMethod.touchRead.pin = 13;
tlSensors.data[4].releasedToApproachedThreshold = 1034;
tlSensors.data[4].approachedToReleasedThreshold = 931;
tlSensors.data[4].approachedToPressedThreshold = 13270;
tlSensors.data[4].pressedToApproachedThreshold = 11943;
tlSensors.data[4].calibratedMaxDelta = 28374;
tlSensors.data[4].filterType = TLStruct::filterTypeAverage;
if (tlSensors.error) {
Serial.println("Error detected during initialization of TouchLib. This is "
"probably a bug; please notify the author.");
while (1);
}
/*
Serial.println("Calibrating sensors...");
while(tlSensors.anyButtonIsCalibrating()) {
tlSensors.sample();
}
Serial.println("Calibration done...");
*/
}
void loop() {
//pixels.show(); // This sends the updated pixel color to the hardware.
//delay(200); // Delay for a period of time (in milliseconds).
//int var1 = int(random(100));
tlSensors.sample(); // <-- Take a series of new samples for all sensors //
/*
Serial.print(tlSensors.getDelta(0));Serial.print(",");
Serial.print(tlSensors.getDelta(1));Serial.print(",");
Serial.print(tlSensors.getDelta(2));Serial.print(",");
Serial.print(tlSensors.getDelta(3));Serial.print(",");
Serial.println(tlSensors.getDelta(4));
Serial.print(tlSensors.getRaw(0));Serial.print(",");
Serial.print(tlSensors.getRaw(1));Serial.print(",");
Serial.print(tlSensors.getRaw(2));Serial.print(",");
Serial.print(tlSensors.getRaw(3));Serial.print(",");
Serial.print(tlSensors.getRaw(4));Serial.print(" ");
*/
//change values to between 0 and 100
//** calibrated from raw data - released/pressed
int range0 = map(tlSensors.getRaw(0), 4300, 3000, 0, 100); // (input, min, max, rangemin, rangemax)
int range1 = map(tlSensors.getRaw(1), 5000, 3000, 0, 100);
int range2 = map(tlSensors.getRaw(2), 4000, 2000, 0, 100);
int range3 = map(tlSensors.getRaw(3), 4500, 2500, 0, 100);
int range4 = map(tlSensors.getRaw(4), 4000, 3000, 0, 100);
//cap min and max
if (range0 < 0) {range0 = 0;}; if (range0 >100) {range0 = 100;}
if (range1 < 0) {range1 = 0;}; if (range1 >100) {range1 = 100;}
if (range2 < 10) {range2 = 0;}; if (range2 >100) {range2 = 100;}
if (range3 < 0) {range3 = 0;}; if (range3 >100) {range3 = 100;}
if (range4 < 11) {range4 = 0;}; if (range4 >100) {range4 = 100;}
//output RAW sensor values
/*
Serial.print(tlSensors.getRaw(0));Serial.print(",");
Serial.print(tlSensors.getRaw(1));Serial.print(",");
Serial.print(tlSensors.getRaw(2));Serial.print(",");
Serial.print(tlSensors.getRaw(3));Serial.print(",");
Serial.println(tlSensors.getRaw(4));
*/
//LEDS
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
/*
for (int i = 0; i < 2; i++) { //SECTION 1 - (PIXEL 0/1)
pixels.setPixelColor(i, pixels.Color(255,102,0)); // ORANGE.
//pixels.setBrightness(range0);
//Serial.println(range0);
pixels.show();
}
for (int j = 2; j < 4; j++) { //SECTION 2
//pixels.setBrightness(range1);
pixels.setPixelColor(j, pixels.Color(255,0,0)); // RED.
pixels.show();
}
for (int k = 4; k < 6; k++) { //SECTION 3
//pixels.setBrightness(range2);
pixels.setPixelColor(k, pixels.Color(17,147,174)); // TEAL.
pixels.show();
}
for (int l = 6; l < 8; l++) { //SECTION 4
//pixels.setBrightness(range3);
pixels.setPixelColor(l, pixels.Color(239,255,0)); // LIME.
pixels.show();
}
for (int m = 8; m < 10; m++) { //SECTION 5
//pixels.setBrightness(range4);
pixels.setPixelColor(m, pixels.Color(255,0,213)); // PINK
pixels.show();
}
*/
int ledBar0 = map(range0, 0,100, 0,6);
int ledBar1 = map(range1, 0,100, 6,12);
//Serial.print(ledBar0);Serial.print(" ");
pixels.clear();
for (int i = 0; i < ledBar0 ; i++){
pixels.setPixelColor(i, pixels.Color(255,102,0)); // ORANGE
}
pixels.show();
for (int j = 6; j < ledBar1 ; j++){
pixels.setPixelColor(j, pixels.Color(255,0,0)); // RED
}
pixels.show();
//output scaled (0-100)
Serial.print(range0);Serial.print(",");
Serial.print(range1);Serial.print(",");
Serial.print(range2);Serial.print(",");
Serial.print(range3);Serial.print(",");
Serial.println(range4);
//delay(100);
}
| [
"noreply@github.com"
] | noreply@github.com |
4bfd1c3c2e0adffcb357199c6c985013c924728e | 44440302635bf339b268775d88a7aed3a59f7d7b | /contest1/addmod.cpp | 06b50de979754300dd2f8783b744d20228f9b406 | [] | no_license | EdwardNgo/Algorithm-application | 79eeb64b65071f0c014ff34fe7e75b865f97d6ee | 36d1bc5c6510d95f97dedebf11fbdf83824a39cc | refs/heads/master | 2023-07-12T01:28:49.750121 | 2021-08-15T02:28:14 | 2021-08-15T02:28:14 | 366,232,906 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | #include <iostream>
using namespace std;
int main(){
unsigned long long a,b;
const unsigned int c = 1000000007;
cin >> a >>b;
cout <<(unsigned long long)(a%c+b%c)%c;
return 0;
} | [
"hoangso8000@gmail.com"
] | hoangso8000@gmail.com |
235ddd08cb46f3d53926e2e9e321852b3a69baaa | 33b567f6828bbb06c22a6fdf903448bbe3b78a4f | /opencascade/StepBasic_MassUnit.hxx | 1aec494c195f01b94ba84131f65d76e2aa594062 | [
"Apache-2.0"
] | permissive | CadQuery/OCP | fbee9663df7ae2c948af66a650808079575112b5 | b5cb181491c9900a40de86368006c73f169c0340 | refs/heads/master | 2023-07-10T18:35:44.225848 | 2023-06-12T18:09:07 | 2023-06-12T18:09:07 | 228,692,262 | 64 | 28 | Apache-2.0 | 2023-09-11T12:40:09 | 2019-12-17T20:02:11 | C++ | UTF-8 | C++ | false | false | 1,289 | hxx | // Created on: 2002-12-12
// Created by: data exchange team
// Copyright (c) 2002-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepBasic_MassUnit_HeaderFile
#define _StepBasic_MassUnit_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepBasic_NamedUnit.hxx>
class StepBasic_MassUnit;
DEFINE_STANDARD_HANDLE(StepBasic_MassUnit, StepBasic_NamedUnit)
//! Representation of STEP entity MassUnit
class StepBasic_MassUnit : public StepBasic_NamedUnit
{
public:
//! Empty constructor
Standard_EXPORT StepBasic_MassUnit();
DEFINE_STANDARD_RTTIEXT(StepBasic_MassUnit,StepBasic_NamedUnit)
protected:
private:
};
#endif // _StepBasic_MassUnit_HeaderFile
| [
"adam.jan.urbanczyk@gmail.com"
] | adam.jan.urbanczyk@gmail.com |
b41c4f90b070ea47decf8d55c0bf73dd6329d693 | 7f01e7e5b1493914048e00730624a7f7ca3b077f | /regrasDePontuacao.h | 3b6d4c9ef5868d95e14e819e4d04881cdf03fd3d | [] | no_license | lorenzomoulin/prog3_C- | ce882685bdea6c1dd81061d6909730676fdcb02e | 125f201614460172bd393965554557767e970794 | refs/heads/master | 2021-01-01T19:53:12.170505 | 2017-08-01T03:33:33 | 2017-08-01T03:33:33 | 98,708,674 | 0 | 0 | null | 2017-08-01T03:33:34 | 2017-07-29T04:39:40 | C++ | UTF-8 | C++ | false | false | 1,394 | h | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: regrasDePontuacao.h
* Author: lorenzo
*
* Created on 28 de Julho de 2017, 16:22
*/
#ifndef REGRASDEPONTUACAO_H
#define REGRASDEPONTUACAO_H
#include <vector>
#include <string>
using namespace std;
namespace trabalho{
class regrasDePontuacao {
double fatorMultiplicador;
time_t dataInicio;
time_t dataFim;
int quantidadeAnos;
int pontuacaoMinima;
vector<string> qualis; // VETOR de qualis e de pontos tem mesmo tamanho
vector<int> pontos;
public:
regrasDePontuacao();
time_t getDataInicio();
void setDataInicio(time_t);
time_t getDataFim();
void setDataFim(time_t);
vector<string> getQualis();
void setQualis(vector<string>);
vector<int> getPontos();
void setPontos(vector<int> );
double getMultiplicador();
void setMultiplicador(double);
int getQuantidadeAnosConsiderar();
void setQuantidadeAnosConsiderar(int quantidadeAnosConsiderar);
int getPontuacaoMinimaRecredenciamento();
void setPontuacaoMinimaRecredenciamento(int pontuacaoMinima);
static void expandeQualis(vector<regrasDePontuacao>& vetorRegras, int ano);
private:
};
}
#endif /* REGRASDEPONTUACAO_H */
| [
"noreply@github.com"
] | noreply@github.com |
8ddd3a37ac368590089c3055633415aa97b1dd41 | ea319658f3d3fe64eb857af0cb9ff50bc652e95a | /levelOrder/levelOrder/levelOrder.cpp | 15ff737af51a83d694725be205074ece457875b9 | [] | no_license | Qyuan926/pracode | cf0a8843f68fc7ca40b667e42ce4f8255feed3db | fbb8264ae3e34adc0afdb050c6821d45567f3ce1 | refs/heads/master | 2021-02-12T23:37:57.780398 | 2021-01-05T14:18:54 | 2021-01-05T14:18:54 | 244,642,818 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,966 | cpp | #define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
};
//从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印
//采用队列先进先出的特性,依次进队(先让根节点进队,取出队头元素,将其左右子树依次放入队列),直至队列为空时,结束。
vector<int> levelOrder1(TreeNode* root) {
vector<int> ret;
if (root == nullptr)
{
return ret;
}
queue<TreeNode*> que_;
que_.push(root);
while (!que_.empty())
{
TreeNode* Node = que_.front();
if (Node->left != nullptr)
{
que_.push(Node->left);
}
if (Node->right != nullptr)
{
que_.push(Node->right);
}
que_.pop();
ret.push_back(Node->val);
}
return ret;
}
//从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
//思想:在层序遍历的基础上面加一个节点标志着一层遍历的结束
vector<vector<int>> levelOrder(TreeNode* root) {
vector< vector<int>> ret;
if (root == nullptr)
{
return ret;
}
vector <int> tmp;
queue<TreeNode*> que_;
TreeNode* end = root;
que_.push(root);
while (!que_.empty())
{
TreeNode* Node = que_.front();
que_.pop();
tmp.push_back(Node->val);
if (Node->left != nullptr)
{
que_.push(Node->left);
}
if (Node->right != nullptr)
{
que_.push(Node->right);
}
if (Node == end)
{
ret.push_back(tmp);
end = que_.back();
tmp.clear();
}
}
return ret;
}
// 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推
//在层序遍历的基础上加一个 ( 标志着一层遍历结束的节点) 和 (一个偶数层交换顺序的临时数组)
vector<vector<int>> levelOrder3(TreeNode* root) {
vector< vector<int> > ret;
if (root == nullptr)
{
return ret;
}
vector<int> tmp;
vector<int> convert;
queue<TreeNode*> que_;
que_.push(root);
TreeNode* end = root;
size_t floor = 1;
while (!que_.empty())
{
TreeNode* Node = que_.front();
que_.pop();
tmp.push_back(Node->val);
if (Node->left != nullptr)
{
que_.push(Node->left);
}
if (Node->right != nullptr)
{
que_.push(Node->right);
}
if (Node == end)
{
if (floor % 2 == 0)
{//偶数层,倒着
for (std::vector<int>::reverse_iterator i = tmp.rbegin(); i != tmp.rend(); ++i)
{
convert.push_back(*i);
}
ret.push_back(convert);
end = que_.back();
tmp.clear();
convert.clear();
}
else//奇数层,正着
{
ret.push_back(tmp);
end = que_.back();
tmp.clear();
}
floor++;
}
}
return ret;
}
| [
"lqy6323@foxmail.com"
] | lqy6323@foxmail.com |
038d843e48a959ada813a31b3c6c6467b1f3db5d | d2298a4f134515a31ab22dd65afe81865eb35540 | /FusionCrowd/Math/Util.h | 4b0d664721e8f4e83d9f67ed1ffb9abc60c4ff88 | [] | no_license | Andronnix/FusionCrowd | 87c889499bd33d72379a674e1ca0b035ad1c77f6 | 50dda1c80e409fa5c6435396e1c8e2277e673c6f | refs/heads/master | 2021-08-07T20:48:55.587148 | 2020-12-24T15:30:00 | 2020-12-24T15:30:00 | 233,855,297 | 0 | 0 | null | 2020-01-14T14:07:21 | 2020-01-14T14:07:20 | null | UTF-8 | C++ | false | false | 1,833 | h | #pragma once
#define NOMINMAX
#include <d3d11.h>
#include "SimpleMath.h"
#undef NOMINMAX
namespace FusionCrowd
{
namespace Math
{
inline float orientToRad(const DirectX::SimpleMath::Vector2 & orient)
{
if(orient.LengthSquared() < 0.0001f)
{
return 0;
}
return atan2f(orient.y, orient.x);
}
inline float det(const DirectX::SimpleMath::Vector2 & v1,
const DirectX::SimpleMath::Vector2 & v2)
{
return v1.x * v2.y - v1.y * v2.x;
}
inline float leftOf(const DirectX::SimpleMath::Vector2 & a,
const DirectX::SimpleMath::Vector2 & b,
const DirectX::SimpleMath::Vector2 & c)
{
return det(a - c, b - a);
}
inline DirectX::SimpleMath::Vector2 rotate(DirectX::SimpleMath::Vector2 vec, float rad)
{
return DirectX::SimpleMath::Vector2(
vec.x * cosf(rad) - vec.y * sinf(rad),
vec.x * sinf(rad) + vec.y * cosf(rad)
);
}
inline int sgn(float val)
{
return (0 < val) - (val < 0);
}
inline float clamp(float val, float min, float max)
{
if(val < min) return min;
if(val > max) return max;
return val;
}
inline DirectX::SimpleMath::Vector2 projectOnSegment(DirectX::SimpleMath::Vector2 s1, DirectX::SimpleMath::Vector2 s2, DirectX::SimpleMath::Vector2 p)
{
const float l2 = (s2 - s1).LengthSquared();
if (l2 == 0.0)
return s1;
const float t = clamp((p - s1).Dot(s2 - s1) / l2, 0, 1);
const DirectX::SimpleMath::Vector2 projection = s1 + t * (s2 - s1); // Projection falls on the segment
return projection;
}
inline float distanceToSegment(DirectX::SimpleMath::Vector2 s1, DirectX::SimpleMath::Vector2 s2, DirectX::SimpleMath::Vector2 p)
{
const DirectX::SimpleMath::Vector2 projection = projectOnSegment(s1, s2, p);
return DirectX::SimpleMath::Vector2::Distance(p, projection);
}
}
} | [
"a.d.kokorev@yandex.ru"
] | a.d.kokorev@yandex.ru |
29146edff3f0e6ccc8f61b5c3fe235233fe2ead6 | 7e81f1b0c9c18ac7b185f151a021a55ba362a068 | /JazmineWalletd/ITransactionValidator.h | e6908f6e62208b4d3dce95861c25d2f06643322b | [
"MIT"
] | permissive | jazmineuno/JazmineWalletd | 31aa18771add55688eb68e31f5d4d64707473925 | c14105d8588ce7b0ab83bdfec9e3dc8f4541df84 | refs/heads/master | 2021-05-13T18:37:07.782718 | 2018-01-17T23:47:24 | 2018-01-17T23:47:24 | 116,872,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | h | // Copyright 2018 Waitman Gobble
// Copyright (c) 2011-2016 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include "CryptoNoteBasic.h"
namespace CryptoNote {
struct BlockInfo {
uint32_t height;
Crypto::Hash id;
BlockInfo() {
clear();
}
void clear() {
height = 0;
id = CryptoNote::NULL_HASH;
}
bool empty() const {
return id == CryptoNote::NULL_HASH;
}
};
class ITransactionValidator {
public:
~ITransactionValidator() {}
virtual bool checkTransactionInputs(const CryptoNote::Transaction& tx, BlockInfo& maxUsedBlock) = 0;
virtual bool checkTransactionInputs(const CryptoNote::Transaction& tx, BlockInfo& maxUsedBlock, BlockInfo& lastFailed) = 0;
virtual bool haveSpentKeyImages(const CryptoNote::Transaction& tx) = 0;
virtual bool checkTransactionSize(size_t blobSize) = 0;
};
}
| [
"waitman@tradetal.com"
] | waitman@tradetal.com |
afa3cb88f0bb242e270063c2856b047e1c7575b4 | 9f3528d1038fefad50a5d53dc99ce215cdfbd688 | /CommonFiles/Request.cpp | 1ea09f5f254c73d516c603706c8072b45122c20c | [] | no_license | jsarraffe/Disk-Simulator | bad27fbe96ff3dce091077923bc2fb192b080c7e | ceceba659fb53c8e6af12008e253f6f1fce23a8f | refs/heads/main | 2023-05-01T11:57:18.488868 | 2021-05-19T07:31:54 | 2021-05-19T07:31:54 | 339,600,495 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | cpp | //
// Created by Ali A. Kooshesh on 10/1/18.
//
#include <iostream>
#include "Request.hpp"
Request::Request(double rTime, int rTrack, int rSector) : _time(rTime), _track(rTrack), _sector(rSector) {}
int Request::track() { return _track; }
int Request::sector() { return _sector; }
double Request::time() { return _time; }
void Request::print() {
std::cout << time() << " " << track() << " " << sector() << std::endl;
}
| [
"jsarraffe@gmail.com"
] | jsarraffe@gmail.com |
1d7fd9e09bb9b901a7d2d6c8e22b406c63d69ba9 | 786bc8c2f27aa9f1bddebcbe950d83dd9f4ec521 | /dynamic programming/DP 30Questions/11_CoinChange_MinCoins.cpp | 1ddf0ac38e2e7db9e46c79845684e1bfc49136df | [] | no_license | thelastsupreme/cs106x | 49a8a3f4ae5e4a17d2f005d4aea44adf5947402b | d4efb8ede855a5473c46730a64b8b3894bb07f7e | refs/heads/master | 2022-11-28T23:18:44.299265 | 2020-08-10T04:45:34 | 2020-08-10T04:45:34 | 264,116,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,602 | cpp | #include<iostream>
#include<vector>
using namespace std;
//given denominations get the min no of coins you can use tp split into these deonminations
//for given amount
int coinChange(vector<int>denominations,int value){
vector<vector<int>>t(denominations.size()+1,vector<int>(value+1,0));
for(int i=1;i<value+1;i++){
//cause block 0,i represents no of coins needed whose denomination is 0
//to get a sum of i
//so infinity is represented as INTMAX
t[0][i]=INT32_MAX-1;
}
//special case where we need to initalize second row
//the condition that needs to be checked here is
//For Example:
//if denoms were 3 5 2
//then block 1,4 represents number of coins of denom 3 can be used to get a 4
//which is impossible so init it with INT_MAX
for(int i=1;i<value+1;i++){
if(i%denominations[0]==0){
t[1][i]=i/denominations[0];
}else{
t[1][i]=INT32_MAX-1;
}
}
for(int i=1;i<denominations.size()+1;i++){
for(int j=1;j<value+1;j++){
if(denominations[i-1]<=j){
t[i][j]=min(t[i][j-denominations[i-1]]+1,t[i-1][j]);
//add one to current and take min of both
//thats the reason we used INTMAX-1 cause there is going to be an increment by 1
//while checking for min and it shouldnt overflow
}
else{
t[i][j]=t[i-1][j];
}
}
}
return t[denominations.size()][value];
}
int main(){
cout<<coinChange({3,5,2},27);
} | [
"39990949+thelastsupreme@users.noreply.github.com"
] | 39990949+thelastsupreme@users.noreply.github.com |
b3fcf0d20a73dc73440d8a54c3085fc59e507bde | a1bf13ea2cf90895d3b9427cd7d5a4b8644cfe2d | /src/imagedata.cpp | 476c89935262da83c31bd42b047ea98faac9a384 | [
"Apache-2.0"
] | permissive | chrismilleruk/mos-lib-epd2in9b | dec322ee168c5afc7c29381b01c60892740a74ed | cd3e2c7c8643d7923cf0b5a4018917bf623413ab | refs/heads/master | 2020-03-27T05:47:52.628632 | 2018-09-11T22:10:24 | 2018-09-11T22:10:24 | 146,051,097 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 49,538 | cpp | /**
* @filename : imagedata.cpp
* @brief : data file for epd demo
*
* Copyright (C) Waveshare July 7 2017
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documnetation 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
* furished 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 OR 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 "imagedata.h"
#ifdef __AVR__
#include <avr/pgmspace.h>
#elif defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#else
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#endif
const unsigned char IMAGE_BLACK[] PROGMEM = { /* 0X00,0X01,0X80,0X00,0X28,0X01, */
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF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,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
};
| [
"chrismilleruk@gmail.com"
] | chrismilleruk@gmail.com |
a256e51e6021b9166ef5490c9d0099f69469b13d | 2d361696ad060b82065ee116685aa4bb93d0b701 | /include/corelib/request_control.hpp | 4c1ad8315f68263f939ec71cc675e059e624afa5 | [
"LicenseRef-scancode-public-domain"
] | permissive | AaronNGray/GenomeWorkbench | 5151714257ce73bdfb57aec47ea3c02f941602e0 | 7156b83ec589e0de8f7b0a85699d2a657f3e1c47 | refs/heads/master | 2022-11-16T12:45:40.377330 | 2020-07-10T00:54:19 | 2020-07-10T00:54:19 | 278,501,064 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,702 | hpp | #ifndef CORELIB___REQUEST_CONTROL__HPP
#define CORELIB___REQUEST_CONTROL__HPP
/* $Id: request_control.hpp 574926 2018-11-20 20:23:54Z ucko $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Denis Vakatov, Vladimir Ivanov, Victor Joukov
*
* File Description:
* Manage request rate to some shared resource
*
*/
#include <corelib/ncbi_limits.hpp>
#include <corelib/ncbitime.hpp>
#include <deque>
/** @addtogroup Utility
*
* @{
*/
BEGIN_NCBI_SCOPE
/////////////////////////////////////////////////////////////////////////////
///
/// CRequestRateControlException --
///
/// Define exceptions generated by CRequestThrottler.
///
/// CRequestThrottlerException inherits its basic functionality from
/// CCoreException and defines additional error codes.
class NCBI_XNCBI_EXPORT CRequestRateControlException : public CCoreException
{
public:
/// Error types that CRequestRateControl can generate.
enum EErrCode {
eNumRequestsMax, ///< Maximum number of requests exceeded;
eNumRequestsPerPeriod, ///< Number of requests per period exceeded;
eMinTimeBetweenRequests ///< The time between two consecutive requests
///< is too short;
};
/// Translate from the error code value to its string representation.
virtual const char* GetErrCodeString(void) const override;
// Standard exception boilerplate code.
NCBI_EXCEPTION_DEFAULT(CRequestRateControlException, CCoreException);
};
/////////////////////////////////////////////////////////////////////////////
///
/// CRequestRateControl --
///
/// Manage request rate to some shared resource, for example.
class NCBI_XNCBI_EXPORT CRequestRateControl
{
public:
/// Special value for maximum number of allowed requests per period.
/// Disable any kind of request throttling.
///
/// @sa
/// Reset
static const unsigned int kNoLimit = kMax_UInt;
/// What to do if exceeded the rate limits.
enum EThrottleAction {
eSleep, ///< Sleep till the rate requirements are met & return
eErrCode, ///< Return immediately with err code == FALSE
eException, ///< Throw an exception
eDefault ///< in c-tor -- eSleep; in Approve() -- value set in c-tor
};
/// Throttle mode.
///
/// In case if number of requests and time period are specified,
/// it is possible to select between two modes for request throttler.
/// First mode is eContinuous. It use internal time line to check number
/// of requests in the past period of time, using current time as ending
/// point for that period. Starting point determinates with ordinary
/// subtraction of "per_period" time, specified in object's constructor,
/// from current time. So the controlled time frame moves continuously
/// in time.
/// Contrary to continuos mode, eDiscrete mode have fixed starting point
/// for period of time, where throttler checks number of incoming
/// requests. First time period starts when CRequestRateControl object
/// creates. Each next period starts with interval of "per_period",
/// or from first approved request in case of long period of inactivity.
/// When each new period starts, the throttler drops all restrictions,
/// and starts to count number of allowed requests per period from zero.
/// Usually eDiscrete mode is a little bit faster and less memory consuming.
enum EThrottleMode {
eContinuous, ///< Uses float time frame to check number of requests
eDiscrete ///< Uses fixed time frame to check number of requests
};
/// Constructor.
///
/// Construct class object. Run Reset() method.
///
/// @sa
/// Reset, EThrottleAction, EThrottleMode
CRequestRateControl
(unsigned int num_requests_allowed,
CTimeSpan per_period = CTimeSpan(1,0),
CTimeSpan min_time_between_requests = CTimeSpan(0,0),
EThrottleAction throttle_action = eDefault,
EThrottleMode throttle_mode = eContinuous);
/// Set new restriction for throttling mechanism.
///
/// Zero values for time spans 'per_period' or 'min_time_between_requests'
/// means no rate restriction for that throttling mechanism, respectively.
///
/// @param num_requests_allowed
/// Maximum number of allowed requests per 'per_period'.
/// Can be kNoLimit for unlimited number of requests (throttler is disabled,
/// Approve() always returns TRUE).
/// @param per_period
/// Time span in which only 'num_requests_allowed' requests can be
/// approved.
/// @param min_time_between_requests
/// Minimum time between two succesful consecutive requests.
/// @param throttle_action
/// Set throttle action by default. The eDefault means eSleep here.
/// @param throttle_mode
/// Set throttle action by default. The eDefault means eSleep here.
/// For backward compatibility, use eContinuous mode by default.
/// @sa
/// Approve, ApproveTime
void Reset(unsigned int num_requests_allowed,
CTimeSpan per_period = CTimeSpan(1,0),
CTimeSpan min_time_between_requests = CTimeSpan(0,0),
EThrottleAction throttle_action = eDefault,
EThrottleMode throttle_mode = eContinuous);
/// Approve a request.
///
/// @param action
/// Throttle action used by this function call. If passed argument
/// equal to eDefault that use throttle action was set in
/// the constructor.
/// @return
/// Return TRUE if everything meet to established requirements.
/// Return FALSE if some requirements are not passed, or
/// throw exception if throttle action was set to eException.
/// @sa
/// Reset, ApproveTime
bool Approve(EThrottleAction action = eDefault);
/// Get a time span in which request can be approved.
///
/// You should call this method until it returns zero time span, otherwise
/// you should sleep (using Sleep() method) for indicated time.
///
/// @return
/// Returns time to wait until actual request, zero if can proceed
/// immediately.
/// If you use this method with absolute limitation (no time period and
/// no minimum between requests) and the limitation is exhausted it will
/// throw an exception.
/// @sa
/// Reset, Approve
CTimeSpan ApproveTime(void);
/// Sleep for CTimeSpan.
///
/// @param sleep_time
/// For how long to sleep. If it's impossible to sleep to that long in
/// millisecond range, rounds up sleep time to the whole seconds.
static void Sleep(CTimeSpan sleep_time);
/// Lock/unlock functions for use by generic RAII guard CGuard.
/// See 'corelib/guard.hpp' for details.
void Lock() { Approve(eSleep); }
void Unlock() { /* do nothing */ }
/// Check if throttling is enabled.
bool IsEnabled(void) const { return m_NumRequestsAllowed != kNoLimit; }
private:
typedef double TTime;
///
bool x_Approve(EThrottleAction action, CTimeSpan *sleeptime);
/// Remove from the list of approved requests all expared items.
void x_CleanTimeLine(TTime now);
private:
// Saved parameters
EThrottleMode m_Mode;
unsigned int m_NumRequestsAllowed;
TTime m_PerPeriod;
TTime m_MinTimeBetweenRequests;
EThrottleAction m_ThrottleAction;
CStopWatch m_StopWatch; ///< Stopwatch to measure elapsed time
typedef deque<TTime> TTimeLine;
TTimeLine m_TimeLine; ///< Vector of times of approvals
TTime m_LastApproved; ///< Last approve time
unsigned int m_NumRequests; ///< Num requests per period
};
//////////////////////////////////////////////////////////////////////////////
//
// Inline
//
inline
bool CRequestRateControl::Approve(EThrottleAction action)
{
return x_Approve(action, 0);
}
inline
CTimeSpan CRequestRateControl::ApproveTime()
{
CTimeSpan sleeptime;
bool res = x_Approve(eSleep, &sleeptime);
if ( !res ) {
return sleeptime;
}
// Approve request
return CTimeSpan(0, 0);
}
END_NCBI_SCOPE
/* @} */
#endif /* CORELIB___REQUEST_CONTROL__HPP */
| [
"aaronngray@gmail.com"
] | aaronngray@gmail.com |
5fa97f2bdf100723bbd0080e4d898557b3700aed | 4fe536f681903188c45505f87462d31dfa510f5c | /OrderHistory.h | 9138575af59157222220ce17241af01eb2074a2f | [] | no_license | hengshaochen/Hotel-booknig-system | 56c6a5171a1083bf6500bcca00c26703c1a769ea | fa6e624eafe398e5ff071509dfd1fbe0f776248d | refs/heads/master | 2020-06-10T03:42:08.974472 | 2016-12-10T07:22:14 | 2016-12-10T07:22:14 | 76,097,227 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | h | // OrderHistory.h
// OrderHistory class definition.
#ifndef ORDER_HISTORY_H
#define ORDER_HISTORY_H
#include "AccountDatabase.h" // AccountDatabase class definition
#include "OrderDatabase.h" // OrderDatabase class definition
class OrderHistory
{
public:
OrderHistory( AccountDatabase &, OrderDatabase & ); // constructor initializes data members
void run( string email ); // start the OrderHistory
private:
AccountDatabase &accountDatabase; // account database
OrderDatabase &orderDatabase; // order database
}; // end class OrderHistory
#endif // ORDER_HISTORY_H | [
"henrychen0702@gmail.com"
] | henrychen0702@gmail.com |
f19177856c006d8566a05baba75019e8dbc4becf | b6c21c00d728734590632de062f5c3def6b2ddd9 | /yeti_snowplow/src/navigation_pid_turn.cpp | 17e38bbc01c61fe3e2afc2af73285cde4b1521d2 | [] | no_license | iscumd/Yeti2018 | e877c9c2bfe31332577d0f3027ac4fe714bdd1a2 | 1e959416d7f46f6cfdb840bb46ef21e58e8b52f1 | refs/heads/master | 2020-06-16T13:45:02.551499 | 2018-01-23T04:27:13 | 2018-01-23T04:27:13 | 94,147,327 | 3 | 8 | null | 2018-01-23T04:27:14 | 2017-06-12T22:48:17 | C++ | UTF-8 | C++ | false | false | 5,693 | cpp | #include "ros/ros.h"
#include "geometry_msgs/Pose2D.h"
#include "geometry_msgs/Twist.h"
#include "std_msgs/Bool.h"
#include "std_msgs/Float64.h"
#include "isc_shared/drive_mode.h"
#include "yeti_snowplow/location_point.h"
#include "yeti_snowplow/target.h"
#include "yeti_snowplow/waypoint.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <string>
#include <time.h>
#include <vector>
using namespace std;
//PID CONTROL
//u(t) = Kp * e(t) + Ki * Integral of e(t) + Kd * derivative of e(t)
double turn; // between -1 to 1
//Proportional
//P accounts for present values of the error. For example, if the error is large
//and positive, the control output will also be large and positive.
double kP; // Proportional Term of PID
double pErr; // Current proportional Error
double lastpErr; //Last proportional Error
//DERIVATIVE
//D accounts for possible future trends of the error, based on its current rate of change.
double kD; //Derivative Term of PID
double dErr; // calculated Derrivative Error
//INTEGRAL
//I accounts for past values of the error.For example, if the current
//output is not sufficiently strong, the integral of the error will
//accumulate over time, and the controller will respond by applying a stronger action.
double kI; // Integral Term
double iErr; //
ros::Publisher pub;
// geometry_msgs::Twist previousTargetVelocity;
geometry_msgs::Twist currentTargetVelocity;
geometry_msgs::Twist realVelocity;
double lastTime, thisTime;
double maxIntErr;
bool isAutoMode = false;
bool stallDisable = false;
double mathSign(double number){
//Returns the number's sign
//Equivalent to .NET's Math.Sign()
//number>0 = 1
//number=0 = 0
//number<0 = -1
if (number == 0){
return 0;
}
else if (number > 0) {
return 1;
}
else {
return -1;
}
}
double adjust_angle(double angle, double circle){
//circle = 2pi for radians, 360 for degrees
// Subtract multiples of circle
angle -= floor(angle / circle) * circle;
angle -= floor(2 * angle / circle) * circle;
return angle;
}
void initPID(){
lastTime = ((double)clock()) / CLOCKS_PER_SEC;
pErr = iErr = dErr = 0;
}
void driveModeCallback(const isc_shared::drive_mode::ConstPtr& msg){
isAutoMode = false;
if(msg->mode == "auto"){
isAutoMode = true;
}
}
void stallDisableCallback(const std_msgs::Bool::ConstPtr& msg){
stallDisable = msg->data;
}
void obstacleReactanceVelocityCallback(const geometry_msgs::Twist::ConstPtr& velocity){
/* This fires every time a new velocity is published */
if(velocity->linear.x != currentTargetVelocity.linear.x || velocity->angular.z != currentTargetVelocity.angular.z){
// previousTargetVelocity = currentTargetVelocity;
currentTargetVelocity = *velocity;
initPID();
}
}
void localizationVelocityCallback(const geometry_msgs::Twist::ConstPtr& velocity){
realVelocity = *velocity;
}
void pid(){
double heading = realVelocity.angular.z;//location->theta;
int dir = mathSign(currentTargetVelocity.linear.x);//(int)currentTarget.dir;
double dt; //Delta time. Holds the difference in time from the last time this function was called to this time.
double desiredAngle; // the desired heading. The heading which would cause the robot to directly face the target
if (dir < 0){ //if direction says we should go backward, turn heading around
heading = heading - M_PI * mathSign(heading);
}
//FIND ANGLE TO DESTINATION
// desired angle is the desired Heading the robot should have at this instance if it were to be facing the target.
desiredAngle = adjust_angle(currentTargetVelocity.angular.z/*atan2(dx, dy)*/, 2.0*M_PI);
thisTime = ((double)clock()) / CLOCKS_PER_SEC;
dt = thisTime - lastTime;
/* Current Target Heading PID Calculations */
lastpErr = pErr; //save the last proportional error
pErr = adjust_angle(heading - desiredAngle, 2.0 * M_PI); //calculate the current propotional error between our current heading and the target heading
iErr = iErr + pErr * dt; //increase the cumulated error.
iErr = mathSign(iErr) * fmin(abs(iErr), maxIntErr); //limit the maxmium integral error
if (dt != 0){ //if the time has changed since the last iteration of guide. (cannot divide by 0).
dErr = (pErr - lastpErr) / dt; // calculate the derrivative error
}
if (cos(pErr) > 0.5){ //if the robot is not facing more than +-60 degrees away from the target
turn = -(kP * sin(pErr) *2 + kI * iErr + kD * dErr); //Nattu; calulate how much the robot should turn at this instant.
}
else { //if the robot is facing more than 60 degrees away from the target
turn = -0.5 * mathSign(pErr); //if you need to turn in place, then ignore PID temporarily
}
lastTime = thisTime;
std_msgs::Float64 msg;
msg.data = turn;
pub.publish(msg);
}
int main(int argc, char **argv){
ros::init(argc, argv, "navigation_pid_turn");
ros::NodeHandle n("~");
n.param<double>("proportional_constant", kP, 0.5);
n.param<double>("derivative_constant", kD, 0.0);
n.param<double>("integral_constant", kI, 0.0);
n.param<double>("integral_max_error", maxIntErr, 0.5);
pub = n.advertise<std_msgs::Float64>("/navigation/turn", 5);
initPID();
ros::Subscriber driveModeSub = n.subscribe("/yeti/drive_mode", 5, driveModeCallback);
ros::Subscriber stallDisableSub = n.subscribe("/navigation/disable", 5, stallDisableCallback);
ros::Subscriber reactanceVelocitySub = n.subscribe("/obstacle_reactance/velocity", 5, obstacleReactanceVelocityCallback);
ros::Subscriber localizationVelocitySub = n.subscribe("/localization/velocity", 5, localizationVelocityCallback);
// ros::spin();
ros::Rate loopRate(100); //Hz
while(ros::ok()) {
ros::spinOnce();
if(!isAutoMode && !stallDisable){
pid();
}
loopRate.sleep();
}
return 0;
}
| [
"epicwolverine@me.com"
] | epicwolverine@me.com |
4271a134c1f8ba2ed726bb90d63045153f7a966a | fcce31f4797c6ce8225433a08e512f8ebb956ed6 | /books.cpp | d9c21d431572c0af62a230f0129a7162ddbb0fba | [] | no_license | DatabasesWorks/store | 63f0ec258ad14348b6aa7c95b6606d9e032346ea | c61bd9ca4728a2b69933ae744026cdbbd9e2063d | refs/heads/master | 2020-07-04T23:55:22.134618 | 2019-08-13T09:40:57 | 2019-08-13T09:40:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,171 | cpp | #include "books.h"
#include <QHeaderView>
#include <QtSql>
#include <QtDebug>
#include <QAction>
#include <QComboBox>
#include <QPainter>
namespace { // Запрет использования в других файлах (анонимное пространство имён)
void REPORT_ERROR(QSqlQuery &QUERY) {
qDebug() << QUERY.executedQuery().toUtf8().data() ;
qCritical() << QUERY.lastError().databaseText().toUtf8().data() ;
}
} // namespace
namespace STORE {
namespace Books {
/*********************************************************************/
// Класс делегата
StatusDelegate::StatusDelegate(QObject *parent, const QMap<int,QString> &AllStatus )
: QItemDelegate ( parent ),fAllStatus(AllStatus) {
}
/*-------------------------------------------------------------------*/
//Переопределяем функцию редактора:
QWidget *StatusDelegate::createEditor( QWidget *parent,
const QStyleOptionViewItem &,
const QModelIndex & ) const {
QComboBox *CB = new QComboBox( parent ) ;
QMapIterator<int,QString> K(fAllStatus) ;
CB->addItem( QString(), QVariant() ) ;
while (K.hasNext()) {
K.next();
CB->addItem( K.value(), K.key() ) ;// наименование и идентификатор статуса
}
return CB ;
} ;
/*-------------------------------------------------------------------*/
// Переопределяем функцию перенос данных с модели на редактор:
void StatusDelegate::setEditorData( QWidget *editor,
const QModelIndex &I ) const {
QComboBox *CB = qobject_cast<QComboBox*>(editor) ; // Преобразовываем к ComboBox
if ( ! CB ) return ;
QVariant IdStatus = I.data(Qt::EditRole) ;
if ( ! IdStatus.isValid() ) { // Если данные предназначены для редактирования не валидные (статуса не выставлено)
CB->setCurrentIndex( 0 ) ; // Пустой элемент 0 по счёту
return ;
}
for ( int k = 1 ; k < CB->count() ; k++ ) {
if( CB->itemData(k) == IdStatus ) {
CB->setCurrentIndex(k) ;
break ;
}
}
}
/*-------------------------------------------------------------------*/
// Переопределяем функцию перенос данных с редактора на модель:
void StatusDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &I ) const {
QComboBox *CB = qobject_cast<QComboBox*>(editor) ; // Преобразовываем к ComboBox
if ( ! CB ) return ;
model->setData( I, CB->currentData(), Qt::EditRole ) ; // Передавать не текст, а значение
}
/*-------------------------------------------------------------------*/
// Переопределим функцию рисования paint для штриховки выданного:
void StatusDelegate::paint( QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &I ) const {
QItemDelegate::paint( painter, option, I ) ;
if( I.data(Qt::EditRole) != -2 ) return ; // Если не в переплёте
painter->setBrush( QBrush( QColor("black"), Qt::DiagCrossPattern ) ) ;
painter->setPen( Qt::NoPen ) ; // Не отрисовывать по контуру
painter->drawRect( option.rect ) ; //Отрисовка прямоугольника
}
/*********************************************************************/
// Модель
Model::Model( QObject *parent)
: QSqlQueryModel ( parent ) {
}
/*-------------------------------------------------------------------*/
Model::~Model(){
}
/*-------------------------------------------------------------------*/
void Model::adjust_query() {
QString QueryText =
"select \n"
" b.iid, \n"
" b.rid_catalogue, \n"
" b.author, \n"
" b.title, \n"
" b.eyear, \n"
" b.location, \n"
" b.publisher, \n"
" b.pages, \n"
" b.annote, \n"
" b.rid_status, \n"
" s.title, \n"
" b.acomment \n"
" from books b \n"
" left outer join status s \n"
" on b.rid_status = s.iid \n"
" where b.rid_catalogue = :CID \n" ;
if ( fAuthor.isValid() )
QueryText += " and b.author ~ :AUTHOR \n" ;
if ( fTitle.isValid() )
QueryText += " and b.title ~ :TITLE \n" ;
if ( fYear.isValid() )
QueryText += " and b.eyear = :YEAR \n" ;
QueryText += "; \n" ;
// qDebug() << QueryText.toUtf8().data() ;
QSqlQuery qry ;
qry.prepare( QueryText ) ;
qry.bindValue(":CID", fCatId ) ; // Если fCatId не валидный, то база данных воспримет его как 0
if ( fAuthor.isValid() )
qry.bindValue( ":AUTHOR", "^"+fAuthor.toString() ) ; // Фильтр
if ( fTitle.isValid() )
qry.bindValue( ":TITLE", fTitle ) ;
if ( fYear.isValid() )
qry.bindValue( ":YEAR", fYear ) ;
if( ! qry.exec() ) { // Открыть запрос
// qDebug() <<qry.executedQuery().toUtf8().data() ;
qCritical() << qry.lastError().databaseText().toUtf8().data() ;
}
setQuery( qry ) ;
}
/*-------------------------------------------------------------------*/
void Model::cat_item_selected(QVariant Id ) {
fCatId = Id ;
adjust_query() ;
}
/*-------------------------------------------------------------------*/
void Model::apply_filter( QObject *F ) {
fAuthor = F->property( "author" ) ;
fTitle = F->property( "title" ) ;
fYear = F->property( "year" ) ;
adjust_query() ;
}
/*-------------------------------------------------------------------*/
//void Model::cat_item_selected( QVariant Id ) {
// QSqlQuery qry ;
// qry.prepare(
// "select \n"
// " b.iid, \n"
// " b.rid_catalogue, \n"
// " b.author, \n"
// " b.title, \n"
// " b.eyear, \n"
// " b.location, \n"
// " b.publisher, \n"
// " b.pages, \n"
// " b.annote, \n"
// " b.rid_status, \n"
// " s.title, \n"
// " b.acomment \n"
// " from books b \n"
// " left outer join status s \n"
// " on b.rid_status = s.iid \n"
// " where b.rid_catalogue = :CID ; \n"
// ) ;
// qry.bindValue(":CID", Id ) ; // Если Id не валидный, то база данных воспримет его как 0
// if( ! qry.exec() ) { // Открыть запрос
// qCritical() << qry.lastError().databaseText().toUtf8().data() ;
// }
// setQuery( qry ) ;
//}
/*********************************************************************/
// Модель
Model_EditOnServer::Model_EditOnServer( QObject *parent)
: QSqlTableModel ( parent ) {
setEditStrategy( OnFieldChange) ; // Выбраем стратегию редактирования временной таблици
{
QAction *A = actDeleteRow = new QAction( this ) ;
A->setText( tr("Delete") ) ;
connect( A, SIGNAL(triggered()), this, SLOT(on_delete_row()) ) ;
AllActions << A ;
}{
QAction *A = actNewRow = new QAction( this ) ;
A->setText( tr("New") ) ;
connect( A, SIGNAL(triggered()), this, SLOT(on_new_row()) ) ;
AllActions << A ;
}{
QAction *A = actSaveAll = new QAction( this ) ;
A->setText( tr("Save") ) ;
connect( A, SIGNAL(triggered()), this, SLOT(on_save_all()) ) ;
AllActions << A ;
}{
QAction *A = actRestoreAll = new QAction( this ) ;
A->setText( tr("Restore") ) ;
connect( A, SIGNAL(triggered()), this, SLOT(on_restore_all()) ) ;
AllActions << A ;
}
{
QSqlQuery QUERY ; // для выгрузки всех статусов из базы в Map (справочник статусов)
QUERY.prepare("select iid, title from status ;") ;
bool OK = QUERY.exec() ;
if( ! OK ) {
REPORT_ERROR(QUERY) ;
return ;
}
while( QUERY.next() ) {
int Id = QUERY.value("iid").toInt() ;
AllStatus[Id] = QUERY.value("title").toString() ;
}
}
}
/*-------------------------------------------------------------------*/
Model_EditOnServer::~Model_EditOnServer(){
}
/*-------------------------------------------------------------------*/
void Model_EditOnServer::on_save_all() {
qDebug() << "on_save_all" ;
}
/*-------------------------------------------------------------------*/
void Model_EditOnServer::on_restore_all() {
qDebug() << "on_restore_all" ;
}
/*-------------------------------------------------------------------*/
void Model_EditOnServer::on_delete_row() {
qDebug() << "on_delete_row" ;
}
/*-------------------------------------------------------------------*/
void Model_EditOnServer::on_new_row() {
insertRow( 0 ) ; // Parent = 0, по структуре аналогично представлению
setData( index( 0, 1 ), fCatId, Qt::EditRole ) ; // Добавляем каталожный элемент rid_catalogue
qDebug() << "on_new_row" ;
}
/*-------------------------------------------------------------------*/
void Model_EditOnServer::adjust_query() {
setTable( QString() ) ; // Отключим таблицу от модели
{
QSqlQuery DROP ; // Создадим запрос для удаления временной таблицы, если она была
bool OK = DROP.exec( "drop table if exists my_books ;" ) ;
if ( ! OK ) {
REPORT_ERROR( DROP ) ;
return ;
}
}{
QSqlQuery CREATE ; // Создадим временную таблицу вручную
bool OK = CREATE.exec (
"create temporary table my_books (\n"
" iid bigint primary key, \n"
" rid_catalogue bigint, \n"
" author text, \n"
" title text, \n"
" eyear int, \n"
" location text, \n"
" publisher text, \n"
" pages int, \n"
" annote text, \n"
" rid_status bigint, \n"
" status_title text, \n"
" acomment text \n"
") ; \n"
) ;
if( ! OK ) {
REPORT_ERROR( CREATE ) ;
return ;
}
}{
QString QueryText =// Вставим во временную таблицу
// "create temporary table my_books as \n"
"insert into my_books ( \n"
" iid, \n"
" rid_catalogue, \n"
" author, \n"
" title, \n"
" eyear, \n"
" location, \n"
" publisher, \n"
" pages, \n"
" annote, \n"
" rid_status, \n"
" status_title, \n"
" acomment \n"
") \n"
"select \n"
" b.iid, \n"
" b.rid_catalogue, \n"
" b.author, \n"
" b.title, \n"
" b.eyear, \n"
" b.location, \n"
" b.publisher, \n"
" b.pages, \n"
" b.annote, \n"
" b.rid_status, \n"
" s.title, \n"
" b.acomment \n"
" from books b \n"
" left outer join status s \n"
" on b.rid_status = s.iid \n"
" where b.rid_catalogue = :CID \n" ;
if ( fAuthor.isValid() )
QueryText += " and b.author ~ :AUTHOR \n" ;
if ( fTitle.isValid() )
QueryText += " and b.title ~ :TITLE \n" ;
if ( fYear.isValid() )
QueryText += " and b.eyear = :YEAR \n" ;
QueryText += "; \n" ;
QSqlQuery qry ;
qry.prepare( QueryText ) ;
qry.bindValue(":CID", fCatId ) ; // Если fCatId не валидный, то база данных воспримет его как 0
if ( fAuthor.isValid() )
qry.bindValue( ":AUTHOR", "^"+fAuthor.toString() ) ; // Фильтр
if ( fTitle.isValid() )
qry.bindValue( ":TITLE", fTitle ) ;
if ( fYear.isValid() )
qry.bindValue( ":YEAR", fYear ) ;
if( ! qry.exec() ) { // Открыть запрос
REPORT_ERROR( qry ) ;
return ;
}
} // Конец блока select
// setQuery( qry ) ;
setTable("my_books") ;
if ( ! select() ) {
qCritical() << "Error selecting" ;
} else {
qDebug() << "Selected successfully" ;
}
}
/*-------------------------------------------------------------------*/
void Model_EditOnServer::cat_item_selected(QVariant Id ) {
fCatId = Id ;
qDebug() << "cat_item_selected" << fCatId ;
adjust_query() ;
}
/*-------------------------------------------------------------------*/
void Model_EditOnServer::apply_filter( QObject *F ) {
fAuthor = F->property( "author" ) ;
fTitle = F->property( "title" ) ;
fYear = F->property( "year" ) ;
qDebug() << "apply_filter" << fAuthor << fTitle << fYear ;
// adjust_query() ;
}
/*-------------------------------------------------------------------*/
// Подменим функцию data
QVariant Model_EditOnServer::data( const QModelIndex &I, int role ) const {
if ( ! I.isValid() ) return QSqlTableModel::data( I, role ) ;
if( role != Qt::EditRole ) return QSqlTableModel::data( I, role ) ;
if( I.column() != 10 ) return QSqlTableModel::data( I, role ) ;
return QSqlTableModel::data( index(I.row(),9), role ) ;
}
/*-------------------------------------------------------------------*/
// Подменим функцию setData
bool Model_EditOnServer::setData( const QModelIndex &I, const QVariant &val, int role ) {
if ( ! I.isValid() ) return QSqlTableModel::setData( I, val, role ) ;
if( role != Qt::EditRole ) return QSqlTableModel::setData( I, val, role ) ;
if( I.column() != 10 ) return QSqlTableModel::setData( I, val, role ) ;
bool Result = true ;
// Установили Id status
if ( val.isValid() ) {
bool OK ;
int status_id =val.toInt( &OK ) ;
if (! OK ) { // Если число статуса некорректное
qWarning() << "Invalid status" << val ;
return false ;
} else if ( ! AllStatus.contains(status_id) ){
qWarning() << "Invalid status" << val ;
return false ;
}
Result |= QSqlTableModel::setData( index(I.row(),9), val, role ) ;
Result |= QSqlTableModel::setData( I, AllStatus[status_id], role ) ; // Установка статуса
///qDebug() << val ;
} else {
Result |= QSqlTableModel::setData( index(I.row(),9), QVariant(), role ) ; // Установка пустого статуса
Result |= QSqlTableModel::setData( I, QString(), role ) ;
}
return Result ;
}
/*-------------------------------------------------------------------*/
Qt::ItemFlags Model_EditOnServer::flags( const QModelIndex &I ) const {
Qt::ItemFlags Result = Qt::ItemIsEnabled | Qt::ItemIsSelectable ;
// if( I.column() != 0 && I.column() != 9 && I.column() != 10 ) // Запрет редактирования
if( I.column() != 0 )
Result |= Qt::ItemIsEditable ;
return Result ;
}
/*-------------------------------------------------------------------*/
// Представление
View::View( QWidget *parent )
: QTableView( parent ) {
// Model *M = new Model( this ) ;
Model_EditOnServer *M = new Model_EditOnServer( this ) ;
setModel( M ) ;
addActions( M->AllActions ) ; // Добавляем Actions на представление
setContextMenuPolicy( Qt::ActionsContextMenu ) ;
setColumnHidden( 0, true ) ; // iid никогда не показываем пользователю
setColumnHidden( 1, true ) ;
// setColumnHidden( 9, true ) ;
setWordWrap( false ) ; // запрет разбития текста на несколько строк
setAlternatingRowColors( true ) ; // Попеременный цвет строк
{
QHeaderView *H = verticalHeader() ;
H->setSectionResizeMode( QHeaderView::ResizeToContents ) ; // Порядок изменения размеров строк
}{
QHeaderView *H =horizontalHeader() ;
H->setSectionResizeMode( QHeaderView::ResizeToContents ) ; // Для всех
H->setSectionResizeMode( 3, QHeaderView::Stretch ) ; //Заголовок растянуть
}
// Устанавливаем делегат для колонки 10 на представление:
// Указываем словарь статусов M:
setItemDelegateForColumn( 10 , new StatusDelegate(this, M->AllStatus) ) ;
}
/*-------------------------------------------------------------------*/
View::~View() {
}
/*********************************************************************/
} // namespace Books
} // namespace STORE
| [
"andrey_shirshov@mail.ru"
] | andrey_shirshov@mail.ru |
bdfbf4fe872fca38008cdf88ae87b5af8d0d6843 | b4f09794c97136834aaef49bcdfa789f13bc9949 | /src/qt/walletview.h | 102d823b0b3eed1d19ce6b691fa585e655a05858 | [
"MIT"
] | permissive | bee-group/beenode | c878ca0be7669fc405f00abb277c9ee26477cfc8 | d27c39471bd960779f1b5dd09ad07295fe29d3e6 | refs/heads/master | 2023-07-07T05:28:26.736520 | 2023-07-04T16:48:45 | 2023-07-04T16:48:45 | 180,884,728 | 8 | 11 | MIT | 2020-04-07T07:09:03 | 2019-04-11T22:03:08 | C++ | UTF-8 | C++ | false | false | 4,818 | h | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_WALLETVIEW_H
#define BITCOIN_QT_WALLETVIEW_H
#include "amount.h"
#include "masternodelist.h"
#include <QStackedWidget>
class BitcoinGUI;
class ClientModel;
class OverviewPage;
class PlatformStyle;
class ReceiveCoinsDialog;
class SendCoinsDialog;
class SendCoinsRecipient;
class TransactionView;
class WalletModel;
class AddressBookPage;
QT_BEGIN_NAMESPACE
class QLabel;
class QModelIndex;
class QProgressDialog;
QT_END_NAMESPACE
/*
WalletView class. This class represents the view to a single wallet.
It was added to support multiple wallet functionality. Each wallet gets its own WalletView instance.
It communicates with both the client and the wallet models to give the user an up-to-date view of the
current core state.
*/
class WalletView : public QStackedWidget
{
Q_OBJECT
public:
explicit WalletView(const PlatformStyle *platformStyle, QWidget *parent);
~WalletView();
void setBitcoinGUI(BitcoinGUI *gui);
/** Set the client model.
The client model represents the part of the core that communicates with the P2P network, and is wallet-agnostic.
*/
void setClientModel(ClientModel *clientModel);
/** Set the wallet model.
The wallet model represents a bitcoin wallet, and offers access to the list of transactions, address book and sending
functionality.
*/
void setWalletModel(WalletModel *walletModel);
bool handlePaymentRequest(const SendCoinsRecipient& recipient);
void showOutOfSyncWarning(bool fShow);
private:
ClientModel *clientModel;
WalletModel *walletModel;
OverviewPage *overviewPage;
QWidget *transactionsPage;
ReceiveCoinsDialog *receiveCoinsPage;
SendCoinsDialog *sendCoinsPage;
AddressBookPage *usedSendingAddressesPage;
AddressBookPage *usedReceivingAddressesPage;
MasternodeList *masternodeListPage;
TransactionView *transactionView;
QProgressDialog *progressDialog;
QLabel *transactionSum;
const PlatformStyle *platformStyle;
public Q_SLOTS:
/** Switch to overview (home) page */
void gotoOverviewPage();
/** Switch to history (transactions) page */
void gotoHistoryPage();
/** Switch to masternode page */
void gotoMasternodePage();
/** Switch to receive coins page */
void gotoReceiveCoinsPage();
/** Switch to send coins page */
void gotoSendCoinsPage(QString addr = "");
/** Show Sign/Verify Message dialog and switch to sign message tab */
void gotoSignMessageTab(QString addr = "");
/** Show Sign/Verify Message dialog and switch to verify message tab */
void gotoVerifyMessageTab(QString addr = "");
/** Show incoming transaction notification for new transactions.
The new items are those between start and end inclusive, under the given parent item.
*/
void processNewTransaction(const QModelIndex& parent, int start, int /*end*/);
/** Encrypt the wallet */
void encryptWallet(bool status);
/** Backup the wallet */
void backupWallet();
/** Change encrypted wallet passphrase */
void changePassphrase();
/** Ask for passphrase to unlock wallet temporarily */
void unlockWallet(bool fAnonymizeOnly=false);
/** Lock wallet */
void lockWallet();
/** Show used sending addresses */
void usedSendingAddresses();
/** Show used receiving addresses */
void usedReceivingAddresses();
/** Re-emit encryption status signal */
void updateEncryptionStatus();
/** Show progress dialog e.g. for rescan */
void showProgress(const QString &title, int nProgress);
/** User has requested more information about the out of sync state */
void requestedSyncWarningInfo();
/** Update selected BEENODE amount from transactionview */
void trxAmount(QString amount);
Q_SIGNALS:
/** Signal that we want to show the main window */
void showNormalIfMinimized();
/** Fired when a message should be reported to the user */
void message(const QString &title, const QString &message, unsigned int style);
/** Encryption status of wallet changed */
void encryptionStatusChanged(int status);
/** HD-Enabled status of wallet changed (only possible during startup) */
void hdEnabledStatusChanged(int hdEnabled);
/** Notify that a new transaction appeared */
void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label);
/** Notify that the out of sync warning icon has been pressed */
void outOfSyncWarningClicked();
};
#endif // BITCOIN_QT_WALLETVIEW_H
| [
"coin.eternity@gmail.com"
] | coin.eternity@gmail.com |
e68305733c2b9e89cb0dc91f2b20e0b062f2faeb | 7a7977692d46848ae8f6af4011ba9ddda874a750 | /curlcpp/src/curl_header.cpp | b7880456bb3e0168043b1907f0552289049e857a | [
"MIT"
] | permissive | ISISComputingGroup/EPICS-curl | 576f20fed03d4f0889d98e6320ac51d4c4f1865d | b20d4e2d50437b8b80019346a0cb4794a72a139a | refs/heads/master | 2023-09-02T12:53:32.200099 | 2019-01-21T16:37:02 | 2019-01-21T16:37:02 | 40,836,456 | 0 | 0 | null | 2019-01-21T12:18:11 | 2015-08-16T19:44:31 | C | UTF-8 | C++ | false | false | 1,634 | cpp | /**
* File: curl_header.cpp
* Author: Giuseppe Persico
*/
#include "curl_header.h"
#include "curl_exception.h"
#include <algorithm>
using std::for_each;
using curl::curl_header;
using curl::curl_exception;
// Implementation of constructor.
curl_header::curl_header() : size(0), headers(nullptr) {
// ... nothing to do here ...
}
// Implementation of the list constructor's initialize method.
curl_header::curl_header(initializer_list<string> headers) : size(0), headers(nullptr) {
for_each(headers.begin(),headers.end(),[this](const string header) {
this->add(header);
});
}
/**
* Implementation of assignment operator. The object has just been created, so its members have just
* been loaded in memory, so we need to give a valid value to them (in this case just to "headers").
*/
curl_header &curl_header::operator=(const curl_header &header) {
if (this == &header) {
return *this;
}
curl_slist_free_all(this->headers);
struct curl_slist *tmp_ptr = header.headers;
while (tmp_ptr != nullptr) {
this->add(tmp_ptr->data);
tmp_ptr = tmp_ptr->next;
}
return *this;
}
// Implementation of destructor.
curl_header::~curl_header() noexcept {
if (this->headers != nullptr) {
curl_slist_free_all(this->headers);
this->headers = nullptr;
}
}
// Implementation of add overloaded method.
void curl_header::add(const string header) {
this->headers = curl_slist_append(this->headers,header.c_str());
if (this->headers == nullptr) {
throw curl_exception("Null pointer exception",__FUNCTION__);
}
++this->size;
}
| [
"freddie.akeroyd@stfc.ac.uk"
] | freddie.akeroyd@stfc.ac.uk |
bd3e763d2ae080b80cda77b71965f2115596b96e | 55d560fe6678a3edc9232ef14de8fafd7b7ece12 | /libs/vmd/test/test_is_tuple_fail4.cpp | b5c44d5e01238cd6c90337eab7351ad11476dfe5 | [
"BSL-1.0"
] | permissive | stardog-union/boost | ec3abeeef1b45389228df031bf25b470d3d123c5 | caa4a540db892caa92e5346e0094c63dea51cbfb | refs/heads/stardog/develop | 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 | BSL-1.0 | 2020-11-17T19:50:36 | 2018-09-13T18:38:54 | C++ | UTF-8 | C++ | false | false | 292 | cpp |
// (C) Copyright Edward Diener 2011-2015
// Use, modification and distribution are 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).
#include <libs/vmd/test/test_is_tuple_fail4.cxx>
| [
"james.pack@stardog.com"
] | james.pack@stardog.com |
411823828a633da303addcb9ac58154e2a4d38a1 | c6edda04814ffb23df750ce23b81169ec35c0057 | /GameEditor/SceneRenderer.h | 41df90454ca087a05dbdf1e5ceb43036ddd4a8a2 | [] | no_license | wlodarczykbart/SunEngine | 91d755cca91ca04ef91879ccfd11500f884e5066 | 04200f084653e88ba332bb260b6964996f35f5a0 | refs/heads/master | 2023-06-07T02:33:20.668913 | 2021-07-03T17:31:38 | 2021-07-03T17:31:38 | 315,081,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,293 | h | #pragma once
#include "Types.h"
#include "Scene.h"
#include "PipelineSettings.h"
#include "GraphicsPipeline.h"
#include "UniformBuffer.h"
#include "BaseShader.h"
#include "Material.h"
#include "RenderTarget.h"
namespace SunEngine
{
class CommandBuffer;
class CameraComponentData;
class LightComponentData;
class RenderNode;
class BaseShader;
class RenderTarget;
class Material;
class Environment;
enum RenderPassType
{
RPT_OUTPUT,
RPT_GBUFFER,
RPT_DEFERRED_RESOLVE,
RPT_DEFERRED_COPY,
RPT_SSR,
RPT_SSR_BLUR,
RPT_SSR_COPY,
RPT_MSAA_RESOLVE,
};
struct RenderPassInfo
{
RenderTarget* pTarget;
GraphicsPipeline* pPipeline;
ShaderBindings* pBindings;
};
class SceneRenderer
{
public:
SceneRenderer();
~SceneRenderer();
bool Init();
bool PrepareFrame(BaseTexture* pOutputTexture, bool updateTextures, CameraComponentData* pCamera = 0);
bool RenderFrame(CommandBuffer* cmdBuffer, RenderTarget* pOpaqueTarget, const Map<RenderPassType, RenderPassInfo>& renderPasses);
BaseTexture* GetShadowMapTexture() const { return _depthTarget.GetDepthTexture(); }
void SetCascadeSplitLambda(float lambda) { _cascadeSplitLambda = lambda; }
void RegisterShader(BaseShader* pShader) { _registeredShaders.insert(pShader); }
bool BindEnvDataBuffer(CommandBuffer* cmdBuffer, BaseShader* pShader) const;
private:
struct UniformBufferData
{
uint ArrayIndex;
uint UpdateIndex;
UniformBuffer Buffer;
Map<BaseShader*, ShaderBindings> ShaderBindings;
};
class UniformBufferGroup
{
public:
UniformBufferGroup();
bool Init(const String& bufferName, ShaderBindingType bindType, uint blockSize);
void Flush();
void Reset();
void Update(const void* dataBlock, uint& updatedIndex, UniformBufferData** ppUpdatedBuffer = 0, BaseShader* pShader = 0);
private:
String _name;
ShaderBindingType _bindType;
uint _blockSize;
uint _maxUpdates;
Vector<UniquePtr<UniformBufferData>> _buffers;
MemBuffer _data;
UniformBufferData* _current;
};
struct RenderNodeData
{
const RenderNode* RenderNode;
GraphicsPipeline* Pipeline;
UniformBufferData* ObjectBindings;
uint ObjectBufferIndex;
Material* MaterialOverride;
UniformBufferData* SkinnedBoneBindings;
uint SkinnedBoneBufferIndex;
uint64 BaseVariantMask;
uint64 DepthHash;
float SortingDistance;
};
struct DepthRenderData
{
DepthRenderData();
UniformBufferGroup ObjectBufferGroup;
UniformBufferGroup SkinnedBonesBufferGroup;
LinkedList<RenderNodeData> RenderList;
AABB FrustumBox;
UniquePtr<CameraComponentData> CameraData;
uint CameraIndex;
};
struct ReflectionProbeData
{
ReflectionProbeData();
bool NeedsUpdate;
Vector<glm::vec3> ProbeCenters;
uint CurrentUpdateProbe;
uint CurrentUpdateFace;
RenderTarget Target;
Material EnvFaceCopyMaterial[6];
UniformBufferGroup ObjectBufferGroup;
UniformBufferGroup SkinnedBonesBufferGroup;
LinkedList<RenderNodeData> RenderList;
UniquePtr<CameraComponentData> CameraData;
uint CameraIndex;
};
void ProcessRenderNode(RenderNode* pNode);
void ProcessDepthRenderNode(RenderNode* pNode, DepthRenderData* pDepthData);
void ProcessRenderList(CommandBuffer* cmdBuffer, LinkedList<RenderNodeData>& renderList, uint cameraUpdateIndex = 0, bool isDepth = false);
bool GetPipeline(RenderNodeData& node, bool& sorted, bool isShadow = false);
bool TryBindBuffer(CommandBuffer* cmdBuffer, BaseShader* pShader, UniformBufferData* buffer, IBindState* pBindState = 0) const;
void RenderEnvironment(CommandBuffer* cmdBuffer);
void RenderCommand(CommandBuffer* cmdBuffer, GraphicsPipeline* pPipeline, ShaderBindings* pBindings, uint vertexCount = 6, uint cameraUpdateIndex = 0);
bool CreateDepthMaterial(Material* pMaterial, uint64 variantMask, Material* pEmptyMaterial) const;
uint64 CalculateDepthVariantHash(Material* pMaterial, uint64 variantMask) const;
void UpdateShadowCascades(Vector<CameraBufferData>& cameraBuffersToFill);
bool ShouldRender(const RenderNode* pNode) const;
uint64 GetVariantMask(const RenderNode* pNode) const;
bool PerformSkinningCheck(const RenderNode* pNode);
void UpdateEnvironmentProbes(Vector<CameraBufferData>& cameraBuffersToFill);
void RenderEnvironmentProbes(CommandBuffer* cmdBuffer);
bool _bInit;
UniquePtr<UniformBufferData> _cameraBuffer;
UniquePtr<UniformBufferData> _environmentBuffer;
UniquePtr<UniformBufferData> _shadowBuffer;
Vector<UniquePtr<GraphicsPipeline>> _graphicsPipelines;
UniformBufferGroup _objectBufferGroup;
UniformBufferGroup _skinnedBonesBufferGroup;
CameraComponentData* _currentCamera;
const Environment* _currentEnvironment;
HashSet<BaseShader*> _currentShaders;
LinkedList<RenderNodeData> _gbufferRenderList;
LinkedList<RenderNodeData> _opaqueRenderList;
LinkedList<RenderNodeData> _sortedRenderList;
Map<usize, UniquePtr<Material>> _depthMaterials;
RenderTarget _depthTarget;
Vector<UniquePtr<DepthRenderData>> _depthPasses;
float _cascadeSplitLambda;
Vector<ShaderMat4> _skinnedBoneMatrixBlock;
StrMap<GraphicsPipeline> _helperPipelines;
RenderTarget _envTarget;
ReflectionProbeData _envProbeData;
AABB _shadowCasterAABB;
HashSet<BaseShader*> _registeredShaders;
};
} | [
"bartwlodarczyk92@gmail.com"
] | bartwlodarczyk92@gmail.com |
0db88316cc4d35f1bf491b28b9a9517695692bb5 | f3b5c4a5ce869dee94c3dfa8d110bab1b4be698b | /controller/src/ifmap/ifmap_update_queue.cc | b491e9aefaadf06924a883863e3a2b7f3085d1a6 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | pan2za/ctrl | 8f808fb4da117fce346ff3d54f80b4e3d6b86b52 | 1d49df03ec4577b014b7d7ef2557d76e795f6a1c | refs/heads/master | 2021-01-22T23:16:48.002959 | 2015-06-17T06:13:36 | 2015-06-17T06:13:36 | 37,454,161 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,337 | cc | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "ifmap/ifmap_update_queue.h"
#include <boost/checked_delete.hpp>
#include <boost/assign/list_of.hpp>
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>
#include <sandesh/request_pipeline.h>
#include "ifmap/ifmap_exporter.h"
#include "ifmap/ifmap_link.h"
#include "ifmap/ifmap_sandesh_context.h"
#include "ifmap/ifmap_server.h"
#include "ifmap/ifmap_server_show_types.h"
IFMapUpdateQueue::IFMapUpdateQueue(IFMapServer *server) : server_(server) {
list_.push_back(tail_marker_);
}
struct IFMapListEntryDisposer {
void operator()(IFMapListEntry *ptr) {
boost::checked_delete(ptr);
}
};
IFMapUpdateQueue::~IFMapUpdateQueue() {
list_.erase(list_.iterator_to(tail_marker_));
list_.clear_and_dispose(IFMapListEntryDisposer());
}
bool IFMapUpdateQueue::Enqueue(IFMapUpdate *update) {
assert(!update->advertise().empty());
bool tm_last = false;
if (GetLast() == tail_marker()) {
tm_last = true;
}
list_.push_back(*update);
return tm_last;
}
void IFMapUpdateQueue::Dequeue(IFMapUpdate *update) {
list_.erase(list_.iterator_to(*update));
}
IFMapMarker *IFMapUpdateQueue::GetMarker(int bit) {
MarkerMap::iterator loc = marker_map_.find(bit);
if (loc == marker_map_.end()) {
return NULL;
}
return loc->second;
}
void IFMapUpdateQueue::Join(int bit) {
IFMapMarker *marker = &tail_marker_;
marker->mask.set(bit);
marker_map_.insert(std::make_pair(bit, marker));
}
void IFMapUpdateQueue::Leave(int bit) {
MarkerMap::iterator loc = marker_map_.find(bit);
assert(loc != marker_map_.end());
IFMapMarker *marker = loc->second;
BitSet reset_bs;
reset_bs.set(bit);
// Start with the first element after the client's marker
for (List::iterator iter = list_.iterator_to(*marker), next;
iter != list_.end(); iter = next) {
IFMapListEntry *item = iter.operator->();
next = ++iter;
if (item->IsMarker()) {
continue;
}
IFMapUpdate *update = static_cast<IFMapUpdate *>(item);
update->AdvertiseReset(reset_bs);
if (update->advertise().empty()) {
Dequeue(update);
}
// Update may be freed.
server_->exporter()->StateUpdateOnDequeue(update, reset_bs, true);
}
marker_map_.erase(loc);
marker->mask.reset(bit);
if ((marker != &tail_marker_) && (marker->mask.empty())) {
list_.erase(list_.iterator_to(*marker));
delete marker;
}
}
void IFMapUpdateQueue::MarkerMerge(IFMapMarker *dst, IFMapMarker *src,
const BitSet &mmove) {
//
// Set the bits in dst and update the MarkerMap. Be sure to set the dst
// before we reset the src since bitset maybe a reference to src->mask.
// Call to operator|=()
//
dst->mask |= mmove;
for (size_t i = mmove.find_first();
i != BitSet::npos; i = mmove.find_next(i)) {
MarkerMap::iterator loc = marker_map_.find(i);
assert(loc != marker_map_.end());
loc->second = dst;
}
// Reset the bits in the src and get rid of it in case it's now empty.
src->mask.Reset(mmove);
if (src->mask.empty()) {
assert(src != &tail_marker_);
list_.erase(list_.iterator_to(*src));
delete src;
}
}
IFMapMarker* IFMapUpdateQueue::MarkerSplit(IFMapMarker *marker,
IFMapListEntry *current,
const BitSet &msplit, bool before) {
assert(!msplit.empty());
IFMapMarker *new_marker = new IFMapMarker();
// call to operator=()
new_marker->mask = msplit;
marker->mask.Reset(msplit);
assert(!marker->mask.empty());
for (size_t i = msplit.find_first();
i != BitSet::npos; i = msplit.find_next(i)) {
MarkerMap::iterator loc = marker_map_.find(i);
assert(loc != marker_map_.end());
loc->second = new_marker;
}
if (before) {
// Insert new_marker before current
list_.insert(list_.iterator_to(*current), *new_marker);
} else {
// Insert new_marker after current
list_.insert(++list_.iterator_to(*current), *new_marker);
}
return new_marker;
}
IFMapMarker* IFMapUpdateQueue::MarkerSplitBefore(IFMapMarker *marker,
IFMapListEntry *current,
const BitSet &msplit) {
bool before = true;
IFMapMarker *ret_marker = MarkerSplit(marker, current, msplit, before);
return ret_marker;
}
IFMapMarker* IFMapUpdateQueue::MarkerSplitAfter(IFMapMarker *marker,
IFMapListEntry *current,
const BitSet &msplit) {
bool before = false;
IFMapMarker *ret_marker = MarkerSplit(marker, current, msplit, before);
return ret_marker;
}
// Insert marker before current
void IFMapUpdateQueue::MoveMarkerBefore(IFMapMarker *marker,
IFMapListEntry *current) {
if (marker != current) {
list_.erase(list_.iterator_to(*marker));
list_.insert(list_.iterator_to(*current), *marker);
}
}
// Insert marker after current
void IFMapUpdateQueue::MoveMarkerAfter(IFMapMarker *marker,
IFMapListEntry *current) {
if (marker != current) {
list_.erase(list_.iterator_to(*marker));
list_.insert(++list_.iterator_to(*current), *marker);
}
}
IFMapListEntry *IFMapUpdateQueue::Previous(IFMapListEntry *current) {
List::iterator iter = list_.iterator_to(*current);
if (iter == list_.begin()) {
return NULL;
}
--iter;
return iter.operator->();
}
IFMapListEntry *IFMapUpdateQueue::GetLast() {
// the list must always have the tail_marker
assert(!list_.empty());
List::reverse_iterator riter;
riter = list_.rbegin();
return riter.operator->();
}
IFMapListEntry * IFMapUpdateQueue::Next(IFMapListEntry *current) {
List::iterator iter = list_.iterator_to(*current);
if (++iter == list_.end()) {
return NULL;
}
return iter.operator->();
}
bool IFMapUpdateQueue::empty() const {
return (list_.begin().operator->() == &tail_marker_) &&
(list_.rbegin().operator->() == &tail_marker_);
}
int IFMapUpdateQueue::size() const {
return (int)list_.size();
}
void IFMapUpdateQueue::PrintQueue() {
int i = 0;
IFMapListEntry *item;
List::iterator iter = list_.iterator_to(list_.front());
while (iter != list_.end()) {
item = iter.operator->();
if (item->IsMarker()) {
IFMapMarker *marker = static_cast<IFMapMarker *>(item);
if (marker == &tail_marker_) {
std::cout << i << ". Tail Marker: " << item;
} else {
std::cout << i << ". Marker: " << item;
}
std::cout << " clients:";
for (size_t j = marker->mask.find_first();
j != BitSet::npos; j = marker->mask.find_next(j)) {
std::cout << " " << j;
}
std::cout << std::endl;
}
if (item->IsUpdate()) {
std::cout << i << ". Update: " << item << " ";
}
if (item->IsDelete()) {
std::cout << i << ". Delete: " << item << " ";
}
if (item->IsUpdate() || item->IsDelete()) {
IFMapUpdate *update = static_cast<IFMapUpdate *>(item);
const IFMapObjectPtr ref = update->data();
if (ref.type == IFMapObjectPtr::NODE) {
std::cout << "node <";
std::cout << ref.u.node->name() << ">" << std::endl;
} else if (ref.type == IFMapObjectPtr::LINK) {
std::cout << ref.u.link->ToString() << std::endl;
}
}
iter++;
i++;
}
std::cout << "**End of queue**" << std::endl;
}
// almost everything in this class is static since we dont really want to
// intantiate this class
class ShowIFMapUpdateQueue {
public:
static const int kMaxElementsPerRound = 50;
struct ShowData : public RequestPipeline::InstData {
std::vector<UpdateQueueShowEntry> send_buffer;
};
static RequestPipeline::InstData *AllocBuffer(int stage) {
return static_cast<RequestPipeline::InstData *>(new ShowData);
}
struct TrackerData : public RequestPipeline::InstData {
// init as 1 indicates we need to init 'first' to begin() since there is
// no way to initialize an iterator here.
TrackerData() : init(1) { }
int init;
std::vector<UpdateQueueShowEntry>::const_iterator first;
};
static RequestPipeline::InstData *AllocTracker(int stage) {
return static_cast<RequestPipeline::InstData *>(new TrackerData);
}
static void CopyNode(UpdateQueueShowEntry *dest, IFMapListEntry *src,
IFMapUpdateQueue *queue);
static bool BufferStage(const Sandesh *sr,
const RequestPipeline::PipeSpec ps, int stage,
int instNum, RequestPipeline::InstData *data);
static bool SendStage(const Sandesh *sr, const RequestPipeline::PipeSpec ps,
int stage, int instNum,
RequestPipeline::InstData *data);
};
void ShowIFMapUpdateQueue::CopyNode(UpdateQueueShowEntry *dest,
IFMapListEntry *src,
IFMapUpdateQueue *queue) {
if (src->IsUpdate() || src->IsDelete()) {
IFMapUpdate *update = static_cast<IFMapUpdate *>(src);
const IFMapObjectPtr ref = update->data();
if (ref.type == IFMapObjectPtr::NODE) {
dest->node_name = "<![CDATA[" + ref.u.node->name() + "]]>";
} else if (ref.type == IFMapObjectPtr::LINK) {
dest->node_name = "<![CDATA[" + ref.u.link->ToString() + "]]>";
}
if (src->IsUpdate()) {
dest->qe_type = "Update";
}
if (src->IsDelete()) {
dest->qe_type = "Delete";
}
dest->qe_bitset = update->advertise().ToString();
}
if (src->IsMarker()) {
IFMapMarker *marker = static_cast<IFMapMarker *>(src);
dest->node_name = "Marker";
if (marker == queue->tail_marker()) {
dest->qe_type = "Tail-Marker";
} else {
dest->qe_type = "Marker";
}
dest->qe_bitset = marker->mask.ToString();
}
}
bool ShowIFMapUpdateQueue::BufferStage(const Sandesh *sr,
const RequestPipeline::PipeSpec ps,
int stage, int instNum,
RequestPipeline::InstData *data) {
const IFMapUpdateQueueShowReq *request =
static_cast<const IFMapUpdateQueueShowReq *>(ps.snhRequest_.get());
IFMapSandeshContext *sctx =
static_cast<IFMapSandeshContext *>(request->module_context("IFMap"));
ShowData *show_data = static_cast<ShowData *>(data);
IFMapUpdateQueue *queue = sctx->ifmap_server()->queue();
assert(queue);
show_data->send_buffer.reserve(queue->list_.size());
IFMapUpdateQueue::List::iterator iter =
queue->list_.iterator_to(queue->list_.front());
while (iter != queue->list_.end()) {
IFMapListEntry *item = iter.operator->();
UpdateQueueShowEntry dest;
CopyNode(&dest, item, queue);
show_data->send_buffer.push_back(dest);
iter++;
}
return true;
}
// Can be called multiple times i.e. approx total/kMaxElementsPerRound
bool ShowIFMapUpdateQueue::SendStage(const Sandesh *sr,
const RequestPipeline::PipeSpec ps,
int stage, int instNum,
RequestPipeline::InstData *data) {
const RequestPipeline::StageData *prev_stage_data = ps.GetStageData(0);
const ShowIFMapUpdateQueue::ShowData &show_data =
static_cast<const ShowIFMapUpdateQueue::ShowData &>
(prev_stage_data->at(0));
// Data for this stage
TrackerData *tracker_data = static_cast<TrackerData *>(data);
std::vector<UpdateQueueShowEntry> dest_buffer;
std::vector<UpdateQueueShowEntry>::const_iterator first, last;
bool more = false;
if (tracker_data->init) {
first = show_data.send_buffer.begin();
tracker_data->init = 0;
} else {
first = tracker_data->first;
}
int rem_num = show_data.send_buffer.end() - first;
int send_num = (rem_num < kMaxElementsPerRound) ? rem_num :
kMaxElementsPerRound;
last = first + send_num;
copy(first, last, back_inserter(dest_buffer));
// Decide if we want to be called again.
if ((rem_num - send_num) > 0) {
more = true;
} else {
more = false;
}
const IFMapUpdateQueueShowReq *request =
static_cast<const IFMapUpdateQueueShowReq *>(ps.snhRequest_.get());
IFMapUpdateQueueShowResp *response = new IFMapUpdateQueueShowResp();
response->set_queue(dest_buffer);
response->set_context(request->context());
response->set_more(more);
response->Response();
tracker_data->first = first + send_num;
// Return 'false' to be called again
return (!more);
}
void IFMapUpdateQueueShowReq::HandleRequest() const {
RequestPipeline::StageSpec s0, s1;
TaskScheduler *scheduler = TaskScheduler::GetInstance();
// 2 stages - first: gather/read, second: send
s0.taskId_ = scheduler->GetTaskId("db::DBTable");
s0.allocFn_ = ShowIFMapUpdateQueue::AllocBuffer;
s0.cbFn_ = ShowIFMapUpdateQueue::BufferStage;
s0.instances_.push_back(0);
// control-node ifmap show command task
s1.taskId_ = scheduler->GetTaskId("cn_ifmap::ShowCommand");
s1.allocFn_ = ShowIFMapUpdateQueue::AllocTracker;
s1.cbFn_ = ShowIFMapUpdateQueue::SendStage;
s1.instances_.push_back(0);
RequestPipeline::PipeSpec ps(this);
ps.stages_= boost::assign::list_of(s0)(s1);
RequestPipeline rp(ps);
}
| [
"pan2za@live.com"
] | pan2za@live.com |
a83d6625cf7a5bd474ab83c3f7e9c0e47fd71eaf | f3d628043cf15afe9c7074035322f850dfbd836d | /spoj/QTREE5.cpp | 63dc044de1c70ac8a5a67db6dd4bfd837256c402 | [
"MIT"
] | permissive | Shahraaz/CP_S5 | 6f812c37700400ea8b5ea07f3eff8dcf21a8f468 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | refs/heads/master | 2021-07-26T13:19:34.205574 | 2021-06-30T07:34:30 | 2021-06-30T07:34:30 | 197,087,890 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,772 | cpp | //Optimise
#include <bits/stdc++.h>
using namespace std;
// #define multitest 1
#ifdef WIN32
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
#define pc(...) PC(#__VA_ARGS__, __VA_ARGS__);
template <typename T, typename U>
ostream &operator<<(ostream &out, const pair<T, U> &p)
{
out << '[' << p.first << ", " << p.second << ']';
return out;
}
template <typename Arg>
void PC(const char *name, Arg &&arg)
{
std::cerr << name << " { ";
for (const auto &v : arg)
cerr << v << ' ';
cerr << " }\n";
}
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
const char *comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << " = " << arg1;
ZZ(comma, args...);
}
#else
#define db(...)
#define pc(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
const long long mod = 1000000007;
auto TimeStart = chrono::steady_clock::now();
const int nax = 1e5 + 10;
struct CentroidDecomposition
{
vector<vector<int>> &Adj;
vector<int> subTreeSize, parentInCentroid;
vector<bool> Computed;
int root, n, currentTreeSize;
CentroidDecomposition(vector<vector<int>> &tree) : Adj(tree)
{
n = Adj.size();
parentInCentroid.assign(n, -1);
subTreeSize.assign(n, 0);
Computed.assign(n, false);
decompose(0, -1);
}
void dfs(int node, int parent)
{
currentTreeSize++;
subTreeSize[node] = 1;
for (auto child : Adj[node])
{
if (child == parent || Computed[child])
continue;
dfs(child, node);
subTreeSize[node] += subTreeSize[child];
}
}
int getCentroid(int node, int parent)
{
for (auto child : Adj[node])
if (child != parent && !Computed[child])
if (subTreeSize[child] > currentTreeSize / 2)
return getCentroid(child, node);
return node;
}
void decompose(int node, int parent)
{
currentTreeSize = 0;
dfs(node, node);
int centroid = getCentroid(node, node);
parentInCentroid[centroid] = (parent == -1) ? centroid : parent;
Computed[centroid] = true;
for (auto child : Adj[centroid])
if (!Computed[child])
decompose(child, centroid);
}
};
struct LeastCommonAncestor
{
vector<int> Level;
vector<vector<int>> dp;
vector<vector<int>> Adj;
int Log;
LeastCommonAncestor(vector<vector<int>> Tree) : Adj(Tree)
{
Log = 20;
int n = Tree.size();
dp.assign(Log, vector<int>(n));
Level.assign(n, 0);
dfs(0, 0, 0);
for (int i = 1; i < Log; ++i)
for (int j = 0; j < n; ++j)
dp[i][j] = dp[i - 1][dp[i - 1][j]];
}
void dfs(int node, int parent, int level)
{
dp[0][node] = parent;
Level[node] = level;
for (auto child : Adj[node])
if (child != parent)
dfs(child, node, level + 1);
}
int lca(int a, int b)
{
db(a, b);
if (Level[a] > Level[b])
swap(a, b);
int d = Level[b] - Level[a];
for (int i = 0; i < Log; ++i)
if (d & (1 << i))
b = dp[i][b];
if (a == b)
return a;
for (int i = Log - 1; i >= 0; --i)
if (dp[i][a] != dp[i][b])
{
a = dp[i][a];
b = dp[i][b];
}
db(dp[0][a]);
return dp[0][a];
}
int dist(int a, int b)
{
return Level[a] + Level[b] - 2 * Level[lca(a, b)];
}
};
struct node
{
int pos, dist;
node(int pos, int dist) : pos(pos), dist(dist) {}
bool operator<(const node &x) const
{
return dist > x.dist;
}
};
priority_queue<node> Q[nax];
bool white[nax];
int distw(int x)
{
while (!Q[x].empty())
{
node curr = Q[x].top();
if (!white[curr.pos])
Q[x].pop();
else
return curr.dist;
}
return INT_MAX;
}
void solve()
{
int n, u, v;
cin >> n;
vector<vector<int>> Tree(n);
for (int i = 1; i < n; ++i)
{
cin >> u >> v;
--u;
--v;
Tree[u].pb(v);
Tree[v].pb(u);
}
int q, ch;
cin >> q;
CentroidDecomposition cd(Tree);
LeastCommonAncestor lcaTree(Tree);
while (q--)
{
cin >> ch >> v;
--v;
if (!ch)
{
white[v] = !white[v];
if (white[v])
{
int curr = v;
while (true)
{
Q[curr].push(node(v, lcaTree.dist(v, curr)));
int next = cd.parentInCentroid[curr];
if (next == curr)
break;
curr = next;
}
}
}
else
{
ll ans = INT_MAX;
int curr = v;
while (true)
{
ans = min(ans, (ll)lcaTree.dist(v, curr) + distw(curr));
int next = cd.parentInCentroid[curr];
if (next == curr)
break;
curr = next;
}
if (ans > n)
cout << -1 << '\n';
else
cout << ans << '\n';
flush(cout);
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
#ifdef multitest
cin >> t;
#endif
while (t--)
solve();
#ifdef WIN32
cerr << "\n\nTime elapsed: " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " seconds.\n";
#endif
return 0;
} | [
"shahraazhussain@gmail.com"
] | shahraazhussain@gmail.com |
7c50728e6127bf64512ea9f6b22c78ea0e0a061e | 98fd810a6d20152ac6bf7e885d479e256cf3b6fb | /inference/engine/include/ocl/reshape_ocl.hpp | 5c038babf119fe48117fdd9ec06c962a640d98fb | [
"MIT"
] | permissive | zhzhuangxue/bolt | 73df6b73c009dcacddb9940ebd0276e84db6458f | 08577f80291a8a99f64fc24454a17832c56eb02b | refs/heads/master | 2023-05-28T06:43:42.690197 | 2021-06-08T09:01:59 | 2021-06-08T09:01:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,619 | hpp | // Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef _RESHAPE_OCL_H
#define _RESHAPE_OCL_H
#include "reshape.hpp"
class ReshapeOCL : public Reshape {
public:
ReshapeOCL(DataType dt, ReshapeParamSpec p) : Reshape(dt, p)
{
setMALIArchInfo(
&(this->archInfo), nullptr, &this->needSetKernelVec, &this->needSelectKernelLS);
}
~ReshapeOCL(){DESTROY_OCL_KERNEL}
std::shared_ptr<Operator> clone() override
{
std::shared_ptr<ReshapeOCL> mem =
std::shared_ptr<ReshapeOCL>(new ReshapeOCL(this->dt, this->p));
*mem = *this;
return mem;
}
inline void run_prepare()
{
OCLContext::getInstance().handle.get()->curOpName = this->get_name();
Tensor inputTensor = this->inputTensors[0];
Tensor outputTensor = this->outputTensors[0];
CHECK_STATUS(reshape(inputTensor, this->temp, outputTensor, &this->archInfo));
}
EE infer_output_tensors_size(
std::vector<Tensor *> inTensors, std::vector<Tensor *> outTensors) override
{
this->needSetKernelVec = true;
CHECK_STATUS(
reshape_infer_output_size(inTensors[0], this->p, outTensors[0], &this->archInfo));
return SUCCESS;
}
U32 infer_tmp_memory_size() override
{
U32 bytes = 0;
CHECK_STATUS(reshape_infer_forward_tmp_bytes(
this->inputTensors[0], this->outputTensors[0], &bytes, &this->archInfo));
return bytes;
}
REGISTER_OCL_OPERATOR_RUN
};
#endif // _RESHAPE_OCL_H
| [
"jianfeifeng@outlook.com"
] | jianfeifeng@outlook.com |
9663e04ed170af8cc8ffe3f3f9b6d48cfdcafe88 | 4532136ea6a95a4bff0bb3433072f43fdbc91544 | /include/onnxruntime/core/platform/threadpool.h | 6cd9d81df3135a8c87069b67b6c755b3090bb3bf | [
"MIT"
] | permissive | hchandola/onnxruntime | 503e82e2b555b9307c84533d89c1a36a3f3dc77c | 02bae6bd063024199ff241eacacc44d5db77490e | refs/heads/master | 2022-10-09T20:27:53.443525 | 2020-04-23T04:17:05 | 2020-04-23T04:17:05 | 270,791,726 | 0 | 0 | MIT | 2020-06-08T19:05:16 | 2020-06-08T19:05:16 | null | UTF-8 | C++ | false | false | 12,848 | h | /* Copyright 2015 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.
==============================================================================*/
/* Modifications Copyright (c) Microsoft. */
#pragma once
#include <string>
#include <vector>
#include <functional>
#include <memory>
#include "core/common/common.h"
#include "core/platform/env.h"
#include "core/common/optional.h"
#include <functional>
#include <memory>
// This file use PIMPL to avoid having eigen headers here
namespace Eigen {
class Allocator;
class ThreadPoolInterface;
struct ThreadPoolDevice;
} // namespace Eigen
namespace onnxruntime {
struct TensorOpCost {
double bytes_loaded;
double bytes_stored;
double compute_cycles;
};
template <typename Environment>
class ThreadPoolTempl;
namespace concurrency {
class ThreadPool {
public:
// Scheduling strategies for ParallelFor. The strategy governs how the given
// units of work are distributed among the available threads in the
// threadpool.
enum class SchedulingStrategy {
// The Adaptive scheduling strategy adaptively chooses the shard sizes based
// on the cost of each unit of work, and the cost model of the underlying
// threadpool device.
//
// The 'cost_per_unit' is an estimate of the number of CPU cycles (or
// nanoseconds if not CPU-bound) to complete a unit of work. Overestimating
// creates too many shards and CPU time will be dominated by per-shard
// overhead, such as Context creation. Underestimating may not fully make
// use of the specified parallelism, and may also cause inefficiencies due
// to load balancing issues and stragglers.
kAdaptive,
// The Fixed Block Size scheduling strategy shards the given units of work
// into shards of fixed size. In case the total number of units is not
// evenly divisible by 'block_size', at most one of the shards may be of
// smaller size. The exact number of shards may be found by a call to
// NumShardsUsedByFixedBlockSizeScheduling.
//
// Each shard may be executed on a different thread in parallel, depending
// on the number of threads available in the pool. Note that when there
// aren't enough threads in the pool to achieve full parallelism, function
// calls will be automatically queued.
kFixedBlockSize
};
// Contains additional parameters for either the Adaptive or the Fixed Block
// Size scheduling strategy.
class SchedulingParams {
public:
explicit SchedulingParams(SchedulingStrategy strategy, optional<int64_t> cost_per_unit,
optional<std::ptrdiff_t> block_size)
: strategy_(strategy), cost_per_unit_(cost_per_unit), block_size_(block_size) {
}
SchedulingStrategy strategy() const {
return strategy_;
}
optional<int64_t> cost_per_unit() const {
return cost_per_unit_;
}
optional<std::ptrdiff_t> block_size() const {
return block_size_;
}
private:
// The underlying Scheduling Strategy for which this instance contains
// additional parameters.
SchedulingStrategy strategy_;
// The estimated cost per unit of work in number of CPU cycles (or
// nanoseconds if not CPU-bound). Only applicable for Adaptive scheduling
// strategy.
optional<int64_t> cost_per_unit_;
// The block size of each shard. Only applicable for Fixed Block Size
// scheduling strategy.
optional<std::ptrdiff_t> block_size_;
};
#ifdef _WIN32
using NAME_CHAR_TYPE = wchar_t;
#else
using NAME_CHAR_TYPE = char;
#endif
// Constructs a pool that contains "num_threads" threads with specified
// "name". env->StartThread() is used to create individual threads with the
// given ThreadOptions. If "low_latency_hint" is true the thread pool
// implementation may use it as a hint that lower latency is preferred at the
// cost of higher CPU usage, e.g. by letting one or more idle threads spin
// wait. Conversely, if the threadpool is used to schedule high-latency
// operations like I/O the hint should be set to false.
//
// REQUIRES: num_threads > 0
// The allocator parameter is only used for creating a Eigen::ThreadPoolDevice to be used with Eigen Tensor classes.
ThreadPool(Env* env, const ThreadOptions& thread_options, const NAME_CHAR_TYPE* name, int num_threads,
bool low_latency_hint, Eigen::Allocator* allocator = nullptr);
// Constructs a pool that wraps around the thread::ThreadPoolInterface
// instance provided by the caller. Caller retains ownership of
// `user_threadpool` and must ensure its lifetime is longer than the
// ThreadPool instance.
ThreadPool(Eigen::ThreadPoolInterface* user_threadpool, Eigen::Allocator* allocator);
// Waits until all scheduled work has finished and then destroy the
// set of threads.
~ThreadPool();
// Schedules fn() for execution in the pool of threads.
void Schedule(std::function<void()> fn);
// Returns the number of shards used by ParallelForFixedBlockSizeScheduling
// with these parameters.
int NumShardsUsedByFixedBlockSizeScheduling(std::ptrdiff_t total, std::ptrdiff_t block_size);
// ParallelFor shards the "total" units of work assuming each unit of work
// having roughly "cost_per_unit" cost, in cycles. Each unit of work is
// indexed 0, 1, ..., total - 1. Each shard contains 1 or more units of work
// and the total cost of each shard is roughly the same.
//
// "cost_per_unit" is an estimate of the number of CPU cycles (or nanoseconds
// if not CPU-bound) to complete a unit of work. Overestimating creates too
// many shards and CPU time will be dominated by per-shard overhead, such as
// Context creation. Underestimating may not fully make use of the specified
// parallelism, and may also cause inefficiencies due to load balancing
// issues and stragglers.
void ParallelFor(std::ptrdiff_t total, double cost_per_unit,
const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn);
static void TryParallelFor(concurrency::ThreadPool* tp, std::ptrdiff_t total, double cost_per_unit,
const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn) {
TryParallelFor(tp, total, TensorOpCost{0, 0, static_cast<double>(cost_per_unit)}, fn);
}
void ParallelFor(std::ptrdiff_t total, const TensorOpCost& cost_per_unit,
const std::function<void(std::ptrdiff_t first, std::ptrdiff_t)>& fn);
static void TryParallelFor(concurrency::ThreadPool* tp, std::ptrdiff_t total, const TensorOpCost& cost_per_unit,
const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn) {
if (tp == nullptr) {
fn(0, total);
return;
}
tp->ParallelFor(total, cost_per_unit, fn);
}
// Similar to ParallelFor above, but takes the specified scheduling strategy
// into account.
void
ParallelFor(std::ptrdiff_t total, const SchedulingParams& scheduling_params,
const std::function<void(std::ptrdiff_t, std::ptrdiff_t)>& fn);
static void TryParallelFor(concurrency::ThreadPool* tp, std::ptrdiff_t total, const SchedulingParams& scheduling_params,
const std::function<void(std::ptrdiff_t, std::ptrdiff_t)>& fn) {
if (tp == nullptr) {
fn(0, total);
return;
}
tp->ParallelFor(total, scheduling_params, fn);
}
// Prefer using this API to get the number of threads unless you know what you're doing.
// This API takes into account if openmp is enabled/disabled and if the thread pool ptr is nullptr.
static int NumThreads(const concurrency::ThreadPool* tp);
// Returns the number of threads in the pool. Preferably use the static version of this API instead.
int NumThreads() const;
// Returns current thread id between 0 and NumThreads() - 1, if called from a
// thread in the pool. Returns -1 otherwise.
int CurrentThreadId() const;
// If ThreadPool implementation is compatible with Eigen::ThreadPoolInterface,
// returns a non-null pointer. The caller does not own the object the returned
// pointer points to, and should not attempt to delete.
Eigen::ThreadPoolInterface* AsEigenThreadPool() const;
// Directly schedule the 'total' tasks to the underlying threadpool, without
// cutting them by halves
void SimpleParallelFor(std::ptrdiff_t total, std::function<void(std::ptrdiff_t)> fn);
#ifdef _OPENMP
template <typename F>
inline static void TryBatchParallelFor(ThreadPool*, std::ptrdiff_t total, F&& fn, std::ptrdiff_t /*num_batches*/) {
#pragma omp parallel for
for (std::ptrdiff_t i = 0; i < total; ++i) {
fn(i);
}
}
#else
/**
* Tries to call the given function in parallel, with calls split into (num_batches) batches.
*\param num_batches If it is zero, it will be replaced to the value of NumThreads().
*\param fn A std::function or STL style functor with signature of "void f(int32_t);"
* Pitfall: Caller should cap `num_batches` to a reasonable value based on the cost of `fn` and the value of `total`.
*For example, if fn is as simple as: int sum=0; fn = [&](int i){sum +=i;} and `total` is 100, then num_batches should
*be just 1.
*
* ```
**/
template <typename F>
inline static void TryBatchParallelFor(ThreadPool* tp, std::ptrdiff_t total, F&& fn, std::ptrdiff_t num_batches) {
if (tp == nullptr) {
for (std::ptrdiff_t i = 0; i < total; ++i) {
// In many cases, fn can be inlined here.
fn(i);
}
return;
}
if (total <= 0)
return;
if (total == 1) {
fn(0);
return;
}
if (num_batches <= 0) {
num_batches = std::min<ptrdiff_t>(total, tp->NumThreads());
}
if (num_batches <= 1) {
for (int i = 0; i < total; i++) {
fn(i);
}
return;
}
tp->SimpleParallelFor(num_batches, [&](std::ptrdiff_t batch_index) {
std::ptrdiff_t start, work_remaining;
PartitionWork(batch_index, num_batches, total, &start, &work_remaining);
std::ptrdiff_t end = start + work_remaining;
for (std::ptrdiff_t i = start; i < end; i++) {
fn(i);
}
});
}
#endif
#ifndef _OPENMP
//Deprecated. Please avoid using Eigen Tensor because it will blow up binary size quickly.
Eigen::ThreadPoolDevice& Device() {
return *threadpool_device_;
}
#endif
ORT_DISALLOW_COPY_AND_ASSIGNMENT(ThreadPool);
private:
// Divides the work represented by the range [0, total) into k shards.
// Calls fn(i*block_size, (i+1)*block_size) from the ith shard (0 <= i < k).
// Each shard may be executed on a different thread in parallel, depending on
// the number of threads available in the pool.
// When (i+1)*block_size > total, fn(i*block_size, total) is called instead.
// Here, k = NumShardsUsedByFixedBlockSizeScheduling(total, block_size).
// Requires 0 < block_size <= total.
void ParallelForFixedBlockSizeScheduling(std::ptrdiff_t total, std::ptrdiff_t block_size,
const std::function<void(std::ptrdiff_t, std::ptrdiff_t)>& fn);
ThreadOptions thread_options_;
// underlying_threadpool_ is the user_threadpool if user_threadpool is
// provided in the constructor. Otherwise it is the eigen_threadpool_.
Eigen::ThreadPoolInterface* underlying_threadpool_;
// eigen_threadpool_ is instantiated and owned by thread::ThreadPool if
// user_threadpool is not in the constructor.
std::unique_ptr<ThreadPoolTempl<Env>> eigen_threadpool_;
#ifndef _OPENMP
std::unique_ptr<Eigen::ThreadPoolDevice> threadpool_device_;
#endif
// Copied from MlasPartitionWork
static void PartitionWork(std::ptrdiff_t ThreadId, std::ptrdiff_t ThreadCount, std::ptrdiff_t TotalWork,
std::ptrdiff_t* WorkIndex, std::ptrdiff_t* WorkRemaining) {
const std::ptrdiff_t WorkPerThread = TotalWork / ThreadCount;
const std::ptrdiff_t WorkPerThreadExtra = TotalWork % ThreadCount;
if (ThreadId < WorkPerThreadExtra) {
*WorkIndex = (WorkPerThread + 1) * ThreadId;
*WorkRemaining = WorkPerThread + 1;
} else {
*WorkIndex = WorkPerThread * ThreadId + WorkPerThreadExtra;
*WorkRemaining = WorkPerThread;
}
}
};
} // namespace concurrency
} // namespace onnxruntime
| [
"noreply@github.com"
] | noreply@github.com |
2b19cb99b1779985669dee950ce30d746b6deabe | f81b774e5306ac01d2c6c1289d9e01b5264aae70 | /components/services/storage/partition_impl.cc | c9a5222e893038df2f191e92b6e1e4ce0923c85f | [
"BSD-3-Clause"
] | permissive | waaberi/chromium | a4015160d8460233b33fe1304e8fd9960a3650a9 | 6549065bd785179608f7b8828da403f3ca5f7aab | refs/heads/master | 2022-12-13T03:09:16.887475 | 2020-09-05T20:29:36 | 2020-09-05T20:29:36 | 293,153,821 | 1 | 1 | BSD-3-Clause | 2020-09-05T21:02:50 | 2020-09-05T21:02:49 | null | UTF-8 | C++ | false | false | 3,492 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/services/storage/partition_impl.h"
#include <utility>
#include "base/bind.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "build/build_config.h"
#include "components/services/storage/dom_storage/local_storage_impl.h"
#include "components/services/storage/dom_storage/session_storage_impl.h"
#include "components/services/storage/storage_service_impl.h"
namespace storage {
namespace {
const char kSessionStorageDirectory[] = "Session Storage";
} // namespace
PartitionImpl::PartitionImpl(StorageServiceImpl* service,
const base::Optional<base::FilePath>& path)
: service_(service), path_(path) {
receivers_.set_disconnect_handler(base::BindRepeating(
&PartitionImpl::OnDisconnect, base::Unretained(this)));
}
PartitionImpl::~PartitionImpl() = default;
void PartitionImpl::BindReceiver(
mojo::PendingReceiver<mojom::Partition> receiver) {
DCHECK(receivers_.empty() || path_.has_value())
<< "In-memory partitions must have at most one client.";
receivers_.Add(this, std::move(receiver));
}
void PartitionImpl::BindOriginContext(
const url::Origin& origin,
mojo::PendingReceiver<mojom::OriginContext> receiver) {
auto iter = origin_contexts_.find(origin);
if (iter == origin_contexts_.end()) {
auto result = origin_contexts_.emplace(
origin, std::make_unique<OriginContextImpl>(this, origin));
iter = result.first;
}
iter->second->BindReceiver(std::move(receiver));
}
void PartitionImpl::BindSessionStorageControl(
mojo::PendingReceiver<mojom::SessionStorageControl> receiver) {
// This object deletes itself on disconnection.
session_storage_ = new SessionStorageImpl(
path_.value_or(base::FilePath()),
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::WithBaseSyncPrimitives(),
base::TaskShutdownBehavior::BLOCK_SHUTDOWN}),
base::SequencedTaskRunnerHandle::Get(),
#if defined(OS_ANDROID)
// On Android there is no support for session storage restoring, and since
// the restoring code is responsible for database cleanup, we must
// manually delete the old database here before we open a new one.
SessionStorageImpl::BackingMode::kClearDiskStateOnOpen,
#else
path_.has_value() ? SessionStorageImpl::BackingMode::kRestoreDiskState
: SessionStorageImpl::BackingMode::kNoDisk,
#endif
std::string(kSessionStorageDirectory), std::move(receiver));
}
void PartitionImpl::BindLocalStorageControl(
mojo::PendingReceiver<mojom::LocalStorageControl> receiver) {
// This object deletes itself on disconnection.
local_storage_ = new LocalStorageImpl(
path_.value_or(base::FilePath()), base::SequencedTaskRunnerHandle::Get(),
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::WithBaseSyncPrimitives(),
base::TaskShutdownBehavior::BLOCK_SHUTDOWN}),
std::move(receiver));
}
void PartitionImpl::OnDisconnect() {
if (receivers_.empty()) {
// Deletes |this|.
service_->RemovePartition(this);
}
}
void PartitionImpl::RemoveOriginContext(const url::Origin& origin) {
origin_contexts_.erase(origin);
}
} // namespace storage
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
5958f2fc908a63880cb46de34309bd8b5de68888 | ace7238fc99af5ff0075970d752a50212ae6ebe6 | /node_modules/nodegit/src/odb_object.cc | 13d6991f4e5b75f0e37f5dac0b0b09256d7a41bf | [
"MIT"
] | permissive | jelandon/platt-schoolwork | 5033348ecaa6dd3bf67b28609829f8bba9ffd927 | 3513182d90dd0de3662e12770fc6adff15a606ff | refs/heads/master | 2020-03-06T21:13:02.998419 | 2018-03-29T06:05:11 | 2018-03-29T06:05:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,233 | cc | // This is a generated file, modify: generate/templates/templates/class_content.cc
#include <nan.h>
#include <string.h>
extern "C" {
#include <git2.h>
}
#include "../include/nodegit.h"
#include "../include/lock_master.h"
#include "../include/functions/copy.h"
#include "../include/odb_object.h"
#include "nodegit_wrapper.cc"
#include "../include/async_libgit2_queue_worker.h"
#include "../include/wrapper.h"
#include "node_buffer.h"
#include "../include/oid.h"
#include <iostream>
using namespace std;
using namespace v8;
using namespace node;
GitOdbObject::~GitOdbObject() {
// this will cause an error if you have a non-self-freeing object that also needs
// to save values. Since the object that will eventually free the object has no
// way of knowing to free these values.
}
void GitOdbObject::InitializeComponent(v8::Local<v8::Object> target) {
Nan::HandleScope scope;
v8::Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(Nan::New("OdbObject").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "data", Data);
Nan::SetPrototypeMethod(tpl, "dup", Dup);
Nan::SetPrototypeMethod(tpl, "free", Free);
Nan::SetPrototypeMethod(tpl, "id", Id);
Nan::SetPrototypeMethod(tpl, "size", Size);
Nan::SetPrototypeMethod(tpl, "type", Type);
InitializeTemplate(tpl);
v8::Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
constructor_template.Reset(_constructor_template);
Nan::Set(target, Nan::New("OdbObject").ToLocalChecked(), _constructor_template);
}
/*
* @return Buffer result */
NAN_METHOD(GitOdbObject::Data) {
Nan::EscapableHandleScope scope;
giterr_clear();
{
LockMaster lockMaster(/*asyncAction: */false , Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
const void * result = git_odb_object_data(
Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
v8::Local<v8::Value> to;
// start convert_to_v8 block
if (result != NULL) {
// Wrapper result
to = Wrapper::New(result);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
}
/*
* @param OdbObject callback
*/
NAN_METHOD(GitOdbObject::Dup) {
if (info.Length() == 0 || !info[0]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
DupBaton* baton = new DupBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->source = Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue();
Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[0]));
DupWorker *worker = new DupWorker(baton, callback);
worker->SaveToPersistent("source", info.This());
AsyncLibgit2QueueWorker(worker);
return;
}
void GitOdbObject::DupWorker::Execute() {
giterr_clear();
{
LockMaster lockMaster(/*asyncAction: */true ,baton->source
);
int result = git_odb_object_dup(
&baton->dest,baton->source );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
}
void GitOdbObject::DupWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
v8::Local<v8::Value> to;
// start convert_to_v8 block
if (baton->dest != NULL) {
// GitOdbObject baton->dest
to = GitOdbObject::New(baton->dest, false );
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
v8::Local<v8::Value> result = to;
v8::Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
v8::Local<v8::Object> err;
if (baton->error->message) {
err = Nan::Error(baton->error->message)->ToObject();
} else {
err = Nan::Error("Method dup has thrown an error.")->ToObject();
}
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
err->Set(Nan::New("errorFunction").ToLocalChecked(), Nan::New("OdbObject.dup").ToLocalChecked());
v8::Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else if (baton->error_code < 0) {
std::queue< v8::Local<v8::Value> > workerArguments;
bool callbackFired = false;
while(!workerArguments.empty()) {
v8::Local<v8::Value> node = workerArguments.front();
workerArguments.pop();
if (
!node->IsObject()
|| node->IsArray()
|| node->IsBooleanObject()
|| node->IsDate()
|| node->IsFunction()
|| node->IsNumberObject()
|| node->IsRegExp()
|| node->IsStringObject()
) {
continue;
}
v8::Local<v8::Object> nodeObj = node->ToObject();
v8::Local<v8::Value> checkValue = GetPrivate(nodeObj, Nan::New("NodeGitPromiseError").ToLocalChecked());
if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
v8::Local<v8::Value> argv[1] = {
checkValue->ToObject()
};
callback->Call(1, argv);
callbackFired = true;
break;
}
v8::Local<v8::Array> properties = nodeObj->GetPropertyNames();
for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
v8::Local<v8::String> propName = properties->Get(propIndex)->ToString();
v8::Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
if (!nodeToQueue->IsUndefined()) {
workerArguments.push(nodeToQueue);
}
}
}
if (!callbackFired) {
v8::Local<v8::Object> err = Nan::Error("Method dup has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
err->Set(Nan::New("errorFunction").ToLocalChecked(), Nan::New("OdbObject.dup").ToLocalChecked());
v8::Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
}
} else {
callback->Call(0, NULL);
}
}
delete baton;
}
/*
*/
NAN_METHOD(GitOdbObject::Free) {
Nan::EscapableHandleScope scope;
if (Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue() != NULL) {
giterr_clear();
{
LockMaster lockMaster(/*asyncAction: */false , Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
git_odb_object_free(
Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->ClearValue();
}
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
}
/*
* @return Oid result */
NAN_METHOD(GitOdbObject::Id) {
Nan::EscapableHandleScope scope;
giterr_clear();
{
LockMaster lockMaster(/*asyncAction: */false , Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
const git_oid * result = git_odb_object_id(
Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
v8::Local<v8::Value> to;
// start convert_to_v8 block
if (result != NULL) {
// GitOid result
to = GitOid::New(result, true , info.This() );
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
}
/*
* @return Number result */
NAN_METHOD(GitOdbObject::Size) {
Nan::EscapableHandleScope scope;
giterr_clear();
{
LockMaster lockMaster(/*asyncAction: */false , Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
size_t result = git_odb_object_size(
Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
v8::Local<v8::Value> to;
// start convert_to_v8 block
to = Nan::New<Number>( result);
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
}
/*
* @return Number result */
NAN_METHOD(GitOdbObject::Type) {
Nan::EscapableHandleScope scope;
giterr_clear();
{
LockMaster lockMaster(/*asyncAction: */false , Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
git_otype result = git_odb_object_type(
Nan::ObjectWrap::Unwrap<GitOdbObject>(info.This())->GetValue()
);
v8::Local<v8::Value> to;
// start convert_to_v8 block
to = Nan::New<Number>( result);
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
}
// force base class template instantiation, to make sure we get all the
// methods, statics, etc.
template class NodeGitWrapper<GitOdbObjectTraits>;
| [
"32464431+jelandon@users.noreply.github.com"
] | 32464431+jelandon@users.noreply.github.com |
514cb6aa5e491fd80d26c083592e1d68edb776d4 | 81d04e91493f13426fd8f7e5a596fd105c63bcee | /codeforces/1466D.cpp | f586dcfd06edf7190a3dd4a3adba886bb61ddcc8 | [] | no_license | vrintle/CP-solutions | 8bfd981d485f0bf55f0cde204595c1d6bc5e1943 | 653de100063290b1904cf054e468ed55d8f0e269 | refs/heads/master | 2023-03-22T00:20:19.362697 | 2021-03-03T12:27:36 | 2021-03-03T12:27:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | cpp | //1466D - 13th Labour of Heracles
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ll t;
cin >> t;
while(t--) {
ll n;
cin >> n;
priority_queue<pair<ll, ll>>pq;
vector<pair<ll, ll>>v;
ll sum = 0;
for(ll i = 0; i < n; i++) {
ll temp;
cin >> temp;
sum += temp;
v.push_back({temp, 0});
}
for(ll i = 0; i < n-1; i++) {
int u, w;
cin >> u >> w;
v[u-1].second++;
v[w-1].second++;
}
for(ll i = 0; i < n; i++) {
pq.push({v[i].first, v[i].second});
}
// while (!pq.empty()) {
// pair<ll, ll>t = pq.top();
// cout << "t: " << t.first << " " << t.second << endl;
// pq.pop();
// }
cout << sum << " ";
pair<ll, ll>t;
if(!pq.empty())
t = pq.top();
for(ll i = 2; i <= n-1; i++) {
if(pq.empty()) {
cout << sum << " ";
}
else {
while(t.second <= 1 && !pq.empty()) {
pq.pop();
t = pq.top();
}
if(pq.empty()) {
cout << sum << " ";
}
else {
sum += t.first;
t.second--;
cout << sum << " ";
}
}
}
cout << endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
57977e31a5240fd12597041de33dbc6024b8612f | 995d5b6de21b7e903d83784b3ebb068b05fdadb9 | /w03_h03_life/src/ofApp.cpp | 32cb4fc06c7c70426029b223b69368ee45101245 | [] | no_license | jcontour/Jessie_OFanimation2015 | 2aa1369c7aa628a1c31c3a2045f4a8c66fd0092a | 52393e8b3febe49fe853c20a1e41da68e5bea78a | refs/heads/master | 2020-06-04T15:51:47.779390 | 2015-05-23T18:49:36 | 2015-05-23T18:49:36 | 31,288,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,305 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(100);
for (int i = 0; i < 10; i++){
head.setup();
snakePositions.push_back(head);
}
for (int i = 0; i < snakePositions.size()-1; i++){
body.setup();
snake.push_back(body);
}
snakePos.x = 0;
snakePos.y = 0;
minSpeed = 1;
maxSpeed = 2;
snakeMove.x = ofRandom(minSpeed, maxSpeed);
snakeMove.y = ofRandom(minSpeed, maxSpeed);
}
//--------------------------------------------------------------
void ofApp::update(){
if (snakePos.x > ofGetWindowWidth()){
snakeMove.x = -ofRandom(minSpeed, maxSpeed);
};
if (snakePos.x < 0){
snakeMove.x = ofRandom(minSpeed, maxSpeed);
};
if (snakePos.y > ofGetWindowHeight()){
snakeMove.y = -ofRandom(minSpeed, maxSpeed);
};
if (snakePos.y < 0){
snakeMove.y = ofRandom(minSpeed, maxSpeed);
};
snakePositions[0].update(snakePos);
//follow the circle in front of them
for (int i = 1; i < snakePositions.size(); i++) {
snakePositions[i].update(snakePositions[i-1].pos);
};
//update head position
snakePos.x += snakeMove.x;
snakePos.y += snakeMove.y;
//update oscillating points
for (int i = 0; i < snake.size()-1; i++){
snake[i].update(8-i);
}
}
//--------------------------------------------------------------
void ofApp::draw(){
// for (int i = 0; i < 5; i++){
// snakePositions[i].draw(10 -i);
// }
snakePositions[0].draw(snakePositions.size());
for (int i = 0; i < snake.size(); i ++){
//finding direction of movement
ofVec2f diff;
diff = snakePositions[i + 1].pos - snakePositions[i].pos;
rot = atan2(diff.y, diff.x);
rot = ofRadToDeg(rot);
ofPushMatrix();
ofTranslate(snakePositions[i+1].pos);
ofRotate(rot);
snake[i].draw((snakePositions.size()-1)-i);
ofPopMatrix();
}
//how to draw line between oscillating points?
//how to make tapering line based on radius of each point?
}
//--------------------------------------------------------------
| [
"Contour@Jessies-MacBook-Air.local"
] | Contour@Jessies-MacBook-Air.local |
dc66910d658ac7b4bbedb1888d6f209a6fa5b40f | d4c720f93631097ee048940d669e0859e85eabcf | /chrome/browser/accessibility/live_caption_speech_recognition_host_browsertest.cc | 74163be0ef263a9962a115fbd2790330d0be5958 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 3b920d87437d9293f654de1f22d3ea341e7a8b55 | refs/heads/webnn | 2023-03-21T03:20:15.377034 | 2023-01-25T21:19:44 | 2023-01-25T21:19:44 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 9,872 | cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/accessibility/live_caption_speech_recognition_host.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/accessibility/live_caption_controller_factory.h"
#include "chrome/browser/accessibility/live_caption_test_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/live_caption/caption_bubble_controller.h"
#include "components/live_caption/live_caption_controller.h"
#include "components/live_caption/pref_names.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/test/browser_test.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/constants/ash_features.h"
#endif
namespace {
// A WebContentsObserver that allows waiting for some media to start or stop
// playing fullscreen.
class FullscreenEventsWaiter : public content::WebContentsObserver {
public:
explicit FullscreenEventsWaiter(content::WebContents* web_contents)
: WebContentsObserver(web_contents) {}
FullscreenEventsWaiter(const FullscreenEventsWaiter& rhs) = delete;
FullscreenEventsWaiter& operator=(const FullscreenEventsWaiter& rhs) = delete;
~FullscreenEventsWaiter() override = default;
void MediaEffectivelyFullscreenChanged(bool value) override {
if (run_loop_)
run_loop_->Quit();
}
// Wait for the current media playing fullscreen mode to be equal to
// |expected_media_fullscreen_mode|.
void Wait() {
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
private:
std::unique_ptr<base::RunLoop> run_loop_;
};
} // namespace
namespace captions {
class LiveCaptionSpeechRecognitionHostTest : public LiveCaptionBrowserTest {
public:
LiveCaptionSpeechRecognitionHostTest() = default;
~LiveCaptionSpeechRecognitionHostTest() override = default;
LiveCaptionSpeechRecognitionHostTest(
const LiveCaptionSpeechRecognitionHostTest&) = delete;
LiveCaptionSpeechRecognitionHostTest& operator=(
const LiveCaptionSpeechRecognitionHostTest&) = delete;
// LiveCaptionBrowserTest:
void SetUp() override {
// This is required for the fullscreen video tests.
embedded_test_server()->ServeFilesFromSourceDirectory(
base::FilePath(FILE_PATH_LITERAL("content/test/data")));
LiveCaptionBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
InProcessBrowserTest::SetUpOnMainThread();
ASSERT_TRUE(embedded_test_server()->Start());
}
void CreateLiveCaptionSpeechRecognitionHost(
content::RenderFrameHost* frame_host) {
mojo::Remote<media::mojom::SpeechRecognitionRecognizerClient> remote;
mojo::PendingReceiver<media::mojom::SpeechRecognitionRecognizerClient>
receiver;
remote.Bind(receiver.InitWithNewPipeAndPassRemote());
LiveCaptionSpeechRecognitionHost::Create(frame_host, std::move(receiver));
remotes_.emplace(frame_host, std::move(remote));
}
void OnSpeechRecognitionRecognitionEvent(content::RenderFrameHost* frame_host,
std::string text,
bool expected_success) {
remotes_[frame_host]->OnSpeechRecognitionRecognitionEvent(
media::SpeechRecognitionResult(text, /*is_final=*/false),
base::BindOnce(&LiveCaptionSpeechRecognitionHostTest::
DispatchTranscriptionCallback,
base::Unretained(this), expected_success));
}
void OnLanguageIdentificationEvent(
content::RenderFrameHost* frame_host,
const std::string& language,
const media::mojom::ConfidenceLevel confidence_level) {
remotes_[frame_host]->OnLanguageIdentificationEvent(
media::mojom::LanguageIdentificationEvent::New(language,
confidence_level));
}
void OnSpeechRecognitionError(content::RenderFrameHost* frame_host) {
remotes_[frame_host]->OnSpeechRecognitionError();
}
bool HasBubbleController() {
return LiveCaptionControllerFactory::GetForProfile(browser()->profile())
->caption_bubble_controller_for_testing() != nullptr;
}
void ExpectIsWidgetVisible(bool visible) {
#if defined(TOOLKIT_VIEWS)
CaptionBubbleController* bubble_controller =
LiveCaptionControllerFactory::GetForProfile(browser()->profile())
->caption_bubble_controller_for_testing();
EXPECT_EQ(visible, bubble_controller->IsWidgetVisibleForTesting());
#endif
}
private:
void DispatchTranscriptionCallback(bool expected_success, bool success) {
EXPECT_EQ(expected_success, success);
}
std::map<content::RenderFrameHost*,
mojo::Remote<media::mojom::SpeechRecognitionRecognizerClient>>
remotes_;
};
// Disabled due to flaky crashes; https://crbug.com/1216304.
IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
DISABLED_DestroysWithoutCrashing) {
content::RenderFrameHost* frame_host = browser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame();
CreateLiveCaptionSpeechRecognitionHost(frame_host);
SetLiveCaptionEnabled(true);
OnSpeechRecognitionRecognitionEvent(
frame_host,
"Pandas' coloring helps them camouflage in snowy environments.",
/* expected_success= */ true);
base::RunLoop().RunUntilIdle();
ExpectIsWidgetVisible(true);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL("http://www.google.com")));
content::WaitForLoadStop(
browser()->tab_strip_model()->GetActiveWebContents());
content::RenderFrameHost* new_frame_host = browser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame();
// After navigating to a new URL, the main frame should be different from the
// former frame host.
CreateLiveCaptionSpeechRecognitionHost(new_frame_host);
ExpectIsWidgetVisible(false);
// Test passes if the following line runs without crashing.
OnSpeechRecognitionRecognitionEvent(new_frame_host,
"Pandas have vertical slits for pupils.",
/* expected_success= */ true);
base::RunLoop().RunUntilIdle();
ExpectIsWidgetVisible(true);
}
IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
OnSpeechRecognitionRecognitionEvent) {
content::RenderFrameHost* frame_host = browser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame();
CreateLiveCaptionSpeechRecognitionHost(frame_host);
SetLiveCaptionEnabled(true);
OnSpeechRecognitionRecognitionEvent(frame_host,
"Pandas learn to climb at 5 months old.",
/* expected_success= */ true);
base::RunLoop().RunUntilIdle();
ExpectIsWidgetVisible(true);
SetLiveCaptionEnabled(false);
OnSpeechRecognitionRecognitionEvent(
frame_host,
"Pandas have an extended wrist bone which they use like a thumb.",
/* expected_success= */ false);
base::RunLoop().RunUntilIdle();
}
IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
OnLanguageIdentificationEvent) {
content::RenderFrameHost* frame_host = browser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame();
CreateLiveCaptionSpeechRecognitionHost(frame_host);
SetLiveCaptionEnabled(true);
OnLanguageIdentificationEvent(
frame_host, "en-US", media::mojom::ConfidenceLevel::kHighlyConfident);
}
IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
OnSpeechRecognitionError) {
content::RenderFrameHost* frame_host = browser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame();
CreateLiveCaptionSpeechRecognitionHost(frame_host);
SetLiveCaptionEnabled(true);
OnSpeechRecognitionError(frame_host);
}
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
MediaEffectivelyFullscreenChanged) {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::RenderFrameHost* frame_host = web_contents->GetPrimaryMainFrame();
CreateLiveCaptionSpeechRecognitionHost(frame_host);
EXPECT_TRUE(content::NavigateToURL(
web_contents, embedded_test_server()->GetURL("/media/fullscreen.html")));
SetLiveCaptionEnabled(true);
EXPECT_TRUE(HasBubbleController());
FullscreenEventsWaiter waiter(web_contents);
EXPECT_TRUE(content::ExecJs(web_contents, "makeFullscreen('small_video')"));
waiter.Wait();
EXPECT_TRUE(HasBubbleController());
EXPECT_TRUE(content::ExecJs(web_contents, "exitFullscreen()"));
waiter.Wait();
EXPECT_TRUE(HasBubbleController());
}
#endif
} // namespace captions
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
98a39e68a2affad1254f378cb612920f08581973 | c56b86c0c098948a1aa7ca3b4a25c7be47af2f45 | /Qt/mega_git_tests/Test_SerialTerm/src/main.cpp | 1c74546d276edc0f5da2034675c33eaf59024123 | [] | no_license | jianglin2045/mega_GIT | 764e460282f1242be5530c8e20e498119f20f827 | 7224c3cf50bf029ff127a3e3db0bb3698af28aa4 | refs/heads/master | 2023-02-13T19:41:30.407632 | 2021-01-11T21:09:31 | 2021-01-11T21:09:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,848 | cpp | /*********************************************************************************
** **
** Copyright (C) 2012 **
** **
** This program is free software: you can redistribute it and/or modify **
** it under the terms of the GNU General Public License as published by **
** the Free Software Foundation, either version 3 of the License, or **
** (at your option) any later version. **
** **
** This program is distributed in the hope that it will be useful, **
** but WITHOUT ANY WARRANTY; without even the implied warranty of **
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
** GNU General Public License for more details. **
** **
** You should have received a copy of the GNU General Public License **
** along with this program. If not, see http://www.gnu.org/licenses/. **
** **
**********************************************************************************
** Author: Bikbao Rinat Zinorovich **
**********************************************************************************/
#ifdef HAVE_QT5
# include <QtWidgets>
#else
# include <QtGui>
#endif
//--------------------------------------------------------------------------------
#include "test_serialterm_mainbox.hpp"
#include "qtsingleapplication.h"
#include "mysplashscreen.hpp"
#include "mainwindow.hpp"
#include "defines.hpp"
#include "version.hpp"
//--------------------------------------------------------------------------------
#include "codecs.h"
//--------------------------------------------------------------------------------
#ifdef QT_DEBUG
# include "test.hpp"
# include <QDebug>
#endif
//--------------------------------------------------------------------------------
#define SINGLE_APP
//--------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
set_codecs();
#ifdef SINGLE_APP
QtSingleApplication app(argc, argv);
if(app.isRunning())
{
//QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("Application already running!"));
if(app.sendMessage("Wake up!")) return 0;
}
#else
QApplication app(argc, argv);
#endif
app.setOrganizationName(QObject::tr(ORGNAME));
app.setApplicationName(QObject::tr(APPNAME));
app.setWindowIcon(QIcon(ICON_PROGRAMM));
QPixmap pixmap(":/logo/logo.png");
MySplashScreen *splash = new MySplashScreen(pixmap, 10);
Q_ASSERT(splash);
splash->show();
MainWindow *main_window = new MainWindow();
Q_ASSERT(main_window);
MainBox *mainBox = new MainBox(main_window, splash);
Q_ASSERT(mainBox);
main_window->setCentralWidget(mainBox);
main_window->show();
splash->finish(main_window);
#ifdef SINGLE_APP
QObject::connect(&app, SIGNAL(messageReceived(const QString&)), main_window, SLOT(set_focus(QString)));
#endif
qDebug() << qPrintable(QString(QObject::tr("Starting application %1")).arg(QObject::tr(APPNAME)));
#ifdef QT_DEBUG
int test_result = QTest::qExec(new Test(), argc, argv);
if (test_result != EXIT_SUCCESS)
{
return test_result;
}
#endif
return app.exec();
}
//--------------------------------------------------------------------------------
| [
"tux4096@gmail.com"
] | tux4096@gmail.com |
3a892b997df163220c97d04f28c69a3d1de0c9ee | 81339647b4d22638a2b9917758ab79bdc4d7663a | /src/ibrio/recovery.cpp | a5be571470cfba3ce19154c4b7c7c1f43df7d8f6 | [
"MIT"
] | permissive | IBnetCouncil/ibrio | 03690649e1f9ee4aa4458a4ca4e49d488c4d187e | 4d726c6dc10b8a3d2d4247eeb347d937dfd730a0 | refs/heads/master | 2023-07-29T23:14:25.118321 | 2021-09-13T03:32:38 | 2021-09-13T03:32:38 | 401,224,182 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,559 | cpp | // Copyright (c) 2019-2021 The Ibrio developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "recovery.h"
#include <boost/filesystem.hpp>
#include "block.h"
#include "core.h"
#include "purger.h"
#include "timeseries.h"
using namespace boost::filesystem;
namespace ibrio
{
class CRecoveryWalker : public storage::CTSWalker<CBlockEx>
{
public:
CRecoveryWalker(IDispatcher* pDispatcherIn, const size_t nSizeIn)
: pDispatcher(pDispatcherIn), nSize(nSizeIn), nNextSize(nSizeIn / 100), nWalkedFileSize(0) {}
bool Walk(const CBlockEx& t, uint32 nFile, uint32 nOffset) override
{
if (!t.IsGenesis())
{
Errno err = pDispatcher->AddNewBlock(t);
if (err == OK)
{
xengine::StdTrace("Recovery", "Recovery block [%s]", t.GetHash().ToString().c_str());
}
else if (err != ERR_ALREADY_HAVE)
{
printf("...... block: %s, file: %u, offset: %u\n", t.GetHash().ToString().c_str(), nFile, nOffset);
xengine::StdError("Recovery", "Recovery block [%s] error: %s", t.GetHash().ToString().c_str(), ErrorString(err));
return false;
}
}
if (nWalkedFileSize + nOffset > nNextSize)
{
xengine::StdLog("CRecovery", "....................... Recovered %d%% ..................", nNextSize / (nSize / 100));
nNextSize += (nSize / 100);
}
return true;
}
protected:
IDispatcher* pDispatcher;
const size_t nSize;
size_t nNextSize;
size_t nWalkedFileSize;
};
CRecovery::CRecovery()
: pDispatcher(nullptr)
{
}
CRecovery::~CRecovery()
{
}
bool CRecovery::HandleInitialize()
{
if (!GetObject("dispatcher", pDispatcher))
{
Error("Failed to request dispatcher");
return false;
}
if (!StorageConfig()->strRecoveryDir.empty())
{
Warn("Clear old database except wallet address");
CProofOfWorkParam param(StorageConfig()->fTestNet);
storage::CPurger purger;
if (!purger(Config()->pathData, param.hashGenesisBlock))
{
Error("Failed to reset DB");
return false;
}
Warn("Clear completed");
}
return true;
}
void CRecovery::HandleDeinitialize()
{
pDispatcher = nullptr;
}
bool CRecovery::HandleInvoke()
{
if (!StorageConfig()->strRecoveryDir.empty())
{
Log("Recovery [%s] begin", StorageConfig()->strRecoveryDir.c_str());
path blockDir(StorageConfig()->strRecoveryDir);
if (!exists(blockDir))
{
Error("Recovery dir [%s] not exist", StorageConfig()->strRecoveryDir.c_str());
return false;
}
storage::CTimeSeriesCached tsBlock;
if (!tsBlock.Initialize(blockDir, "block"))
{
Error("Recovery initialze fail");
return false;
}
size_t nSize = tsBlock.GetSize();
CRecoveryWalker walker(pDispatcher, nSize);
uint32 nLastFile;
uint32 nLastPos;
if (!tsBlock.WalkThrough(walker, nLastFile, nLastPos, false))
{
Error("Recovery walkthrough fail");
return false;
}
xengine::StdLog("CRecovery", "....................... Recovered success .......................");
Log("Recovery [%s] end", StorageConfig()->strRecoveryDir.c_str());
}
return true;
}
} // namespace ibrio
| [
"ibr.feedback@gmail.com"
] | ibr.feedback@gmail.com |
d48602967ec80cfca90c480d321c38e4dfc4fb10 | 9d36a59d612086b6b94bb7553e9292fc6567d95d | /core/src/array/array_sorted_read_state.cc | e3d8347f6c14844fc9c7c506bee3eca7bbd7f089 | [
"MIT"
] | permissive | JamesRamm/TileDB | 1f846c17855f4036122adbd35cab59ee55e0c61a | 106b72ba8558203f90d765f982adbf3743a2cd8c | refs/heads/master | 2021-01-20T07:27:56.162993 | 2017-06-10T00:30:36 | 2017-06-10T00:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 97,575 | cc | /**
* @file array_sorted_read_state.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2016 MIT and Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice 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.
*
* @section DESCRIPTION
*
* This file implements the ArraySortedReadState class.
*/
#include "array_sorted_read_state.h"
#include "comparators.h"
#include "math.h"
#include "utils.h"
#include <cassert>
/* ****************************** */
/* MACROS */
/* ****************************** */
#ifdef TILEDB_VERBOSE
# define PRINT_ERROR(x) std::cerr << TILEDB_ASRS_ERRMSG << x << ".\n"
#else
# define PRINT_ERROR(x) do { } while(0)
#endif
#if defined HAVE_OPENMP && defined USE_PARALLEL_SORT
#include <parallel/algorithm>
#define SORT(first, last, comp) __gnu_parallel::sort((first), (last), (comp))
#else
#include <algorithm>
#define SORT(first, last, comp) std::sort((first), (last), (comp))
#endif
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
/* ****************************** */
/* GLOBAL VARIABLES */
/* ****************************** */
std::string tiledb_asrs_errmsg = "";
/* ****************************** */
/* CONSTRUCTORS & DESTRUCTORS */
/* ****************************** */
ArraySortedReadState::ArraySortedReadState(
Array* array)
: array_(array) {
// Calculate the attribute ids
calculate_attribute_ids();
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
int anum = (int) attribute_ids_.size();
// Initializations
aio_id_ = 0;
aio_cnt_ = 0;
coords_size_ = array_schema->coords_size();
copy_id_ = 0;
dim_num_ = array_schema->dim_num();
copy_thread_running_ = false;
copy_thread_canceled_ = false;
read_tile_slabs_done_ = false;
resume_copy_ = false;
resume_aio_ = false;
tile_coords_ = NULL;
tile_domain_ = NULL;
for(int i=0; i<2; ++i) {
aio_overflow_[i] = new bool[anum];
buffer_sizes_[i] = NULL;
buffer_sizes_tmp_[i] = NULL;
buffer_sizes_tmp_bak_[i] = NULL;
buffers_[i] = NULL;
tile_slab_[i] = malloc(2*coords_size_);
tile_slab_norm_[i] = malloc(2*coords_size_);
tile_slab_init_[i] = false;
wait_copy_[i] = false;
wait_aio_[i] = true;
}
overflow_ = new bool[anum];
overflow_still_ = new bool[anum];
for(int i=0; i<anum; ++i) {
overflow_[i] = false;
overflow_still_[i] = true;
if(array_schema->var_size(attribute_ids_[i]))
attribute_sizes_.push_back(sizeof(size_t));
else
attribute_sizes_.push_back(array_schema->cell_size(attribute_ids_[i]));
}
subarray_ = malloc(2*coords_size_);
memcpy(subarray_, array_->subarray(), 2*coords_size_);
// Calculate number of buffers
calculate_buffer_num();
// Calculate buffer sizes
calculate_buffer_sizes();
// Initialize tile slab info and state, and copy state
init_tile_slab_info();
init_tile_slab_state();
init_copy_state();
}
ArraySortedReadState::~ArraySortedReadState() {
// Cancel copy thread
copy_thread_canceled_ = true;
for(int i=0; i<2; ++i)
release_aio(i);
// Wait for thread to be destroyed
while(copy_thread_running_);
// Join with the terminated thread
pthread_join(copy_thread_, NULL);
// Clean up
free(subarray_);
free(tile_coords_);
free(tile_domain_);
delete [] overflow_;
for(int i=0; i<2; ++i) {
delete [] aio_overflow_[i];
if(buffer_sizes_[i] != NULL)
delete [] buffer_sizes_[i];
if(buffer_sizes_tmp_[i] != NULL)
delete [] buffer_sizes_tmp_[i];
if(buffer_sizes_tmp_bak_[i] != NULL)
delete [] buffer_sizes_tmp_bak_[i];
if(buffers_[i] != NULL) {
for(int b=0; b<buffer_num_; ++b)
free(buffers_[i][b]);
free(buffers_[i]);
}
free(tile_slab_[i]);
free(tile_slab_norm_[i]);
}
// Free tile slab info and state, and copy state
free_copy_state();
free_tile_slab_state();
free_tile_slab_info();
// Destroy conditions and mutexes
for(int i=0; i<2; ++i) {
if(pthread_cond_destroy(&(aio_cond_[i]))) {
std::string errmsg = "Cannot destroy AIO mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
}
if(pthread_cond_destroy(&(copy_cond_[i]))) {
std::string errmsg = "Cannot destroy copy mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
}
}
if(pthread_cond_destroy(&overflow_cond_)) {
std::string errmsg = "Cannot destroy overflow mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
}
if(pthread_mutex_destroy(&aio_mtx_)) {
std::string errmsg = "Cannot destroy AIO mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
}
if(pthread_mutex_destroy(©_mtx_)) {
std::string errmsg = "Cannot destroy copy mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
}
if(pthread_mutex_destroy(&overflow_mtx_)) {
std::string errmsg = "Cannot destroy overflow mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
}
}
/* ****************************** */
/* ACCESSORS */
/* ****************************** */
bool ArraySortedReadState::copy_tile_slab_done() const {
for(int i=0; i < (int) attribute_ids_.size(); ++i) {
// Special case for sparse arrays with extra coordinates attribute
if(i == coords_attr_i_ && extra_coords_)
continue;
// Check
if(!tile_slab_state_.copy_tile_slab_done_[i])
return false;
}
return true;
}
bool ArraySortedReadState::done() const {
if(!read_tile_slabs_done_)
return false;
else
return copy_tile_slab_done();
}
bool ArraySortedReadState::overflow() const {
for(int i=0; i < (int) attribute_ids_.size(); ++i) {
if(overflow_[i])
return true;
}
return false;
}
bool ArraySortedReadState::overflow(int attribute_id) const {
for(int i=0; i < (int) attribute_ids_.size(); ++i) {
if(attribute_ids_[i] == attribute_id)
return overflow_[i];
}
return false;
}
int ArraySortedReadState::read(void** buffers, size_t* buffer_sizes) {
// Trivial case
if(done()) {
for(int i=0; i<buffer_num_; ++i)
buffer_sizes[i] = 0;
return TILEDB_ASRS_OK;
}
// Reset copy state
reset_copy_state(buffers, buffer_sizes);
// Reset overflow
reset_overflow();
// Resume the copy request handling
if(resume_copy_) {
block_copy(1);
block_copy(0);
release_aio(copy_id_);
release_overflow();
}
// Call the appropriate templated read
int type = array_->array_schema()->coords_type();
if(type == TILEDB_INT32) {
return read<int>();
} else if(type == TILEDB_INT64) {
return read<int64_t>();
} else if(type == TILEDB_FLOAT32) {
return read<float>();
} else if(type == TILEDB_FLOAT64) {
return read<double>();
} else if(type == TILEDB_INT8) {
return read<int8_t>();
} else if(type == TILEDB_UINT8) {
return read<uint8_t>();
} else if(type == TILEDB_INT16) {
return read<int16_t>();
} else if(type == TILEDB_UINT16) {
return read<uint16_t>();
} else if(type == TILEDB_UINT32) {
return read<uint32_t>();
} else if(type == TILEDB_UINT64) {
return read<uint64_t>();
} else {
assert(0);
return TILEDB_ASRS_ERR;
}
}
/* ****************************** */
/* MUTATORS */
/* ****************************** */
int ArraySortedReadState::init() {
// Create buffers
if(create_buffers() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Create AIO requests
init_aio_requests();
// Initialize the mutexes and conditions
if(pthread_mutex_init(&aio_mtx_, NULL)) {
std::string errmsg = "Cannot initialize IO mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
if(pthread_mutex_init(©_mtx_, NULL)) {
std::string errmsg = "Cannot initialize copy mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
if(pthread_mutex_init(&overflow_mtx_, NULL)) {
std::string errmsg = "Cannot initialize overflow mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
for(int i=0; i<2; ++i) {
aio_cond_[i] = PTHREAD_COND_INITIALIZER;
if(pthread_cond_init(&(aio_cond_[i]), NULL)) {
std::string errmsg = "Cannot initialize IO mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
copy_cond_[i] = PTHREAD_COND_INITIALIZER;
if(pthread_cond_init(&(copy_cond_[i]), NULL)) {
std::string errmsg = "Cannot initialize copy mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
}
overflow_cond_ = PTHREAD_COND_INITIALIZER;
if(pthread_cond_init(&overflow_cond_, NULL)) {
std::string errmsg = "Cannot initialize overflow mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Initialize functors
const ArraySchema* array_schema = array_->array_schema();
int mode = array_->mode();
int cell_order = array_schema->cell_order();
int tile_order = array_schema->tile_order();
int coords_type = array_schema->coords_type();
if(mode == TILEDB_ARRAY_READ_SORTED_ROW) {
if(coords_type == TILEDB_INT32) {
advance_cell_slab_ = advance_cell_slab_row_s<int>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<int> :
calculate_cell_slab_info_row_col_s<int>;
} else if(coords_type == TILEDB_INT64) {
advance_cell_slab_ = advance_cell_slab_row_s<int64_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<int64_t> :
calculate_cell_slab_info_row_col_s<int64_t>;
} else if(coords_type == TILEDB_FLOAT32) {
advance_cell_slab_ = advance_cell_slab_row_s<float>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<float> :
calculate_cell_slab_info_row_col_s<float>;
} else if(coords_type == TILEDB_FLOAT64) {
advance_cell_slab_ = advance_cell_slab_row_s<double>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<double> :
calculate_cell_slab_info_row_col_s<double>;
} else if(coords_type == TILEDB_INT8) {
advance_cell_slab_ = advance_cell_slab_row_s<int8_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<int8_t> :
calculate_cell_slab_info_row_col_s<int8_t>;
} else if(coords_type == TILEDB_UINT8) {
advance_cell_slab_ = advance_cell_slab_row_s<uint8_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<uint8_t> :
calculate_cell_slab_info_row_col_s<uint8_t>;
} else if(coords_type == TILEDB_INT16) {
advance_cell_slab_ = advance_cell_slab_row_s<int16_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<int16_t> :
calculate_cell_slab_info_row_col_s<int16_t>;
} else if(coords_type == TILEDB_UINT16) {
advance_cell_slab_ = advance_cell_slab_row_s<uint16_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<uint16_t> :
calculate_cell_slab_info_row_col_s<uint16_t>;
} else if(coords_type == TILEDB_UINT32) {
advance_cell_slab_ = advance_cell_slab_row_s<uint32_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<uint32_t> :
calculate_cell_slab_info_row_col_s<uint32_t>;
} else if(coords_type == TILEDB_UINT64) {
advance_cell_slab_ = advance_cell_slab_row_s<uint64_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_row_row_s<uint64_t> :
calculate_cell_slab_info_row_col_s<uint64_t>;
} else {
assert(0);
}
} else { // mode == TILEDB_ARRAY_READ_SORTED_COL
if(coords_type == TILEDB_INT32) {
advance_cell_slab_ = advance_cell_slab_col_s<int>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<int> :
calculate_cell_slab_info_col_col_s<int>;
} else if(coords_type == TILEDB_INT64) {
advance_cell_slab_ = advance_cell_slab_col_s<int64_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<int64_t> :
calculate_cell_slab_info_col_col_s<int64_t>;
} else if(coords_type == TILEDB_FLOAT32) {
advance_cell_slab_ = advance_cell_slab_col_s<float>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<float> :
calculate_cell_slab_info_col_col_s<float>;
} else if(coords_type == TILEDB_FLOAT64) {
advance_cell_slab_ = advance_cell_slab_col_s<double>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<double> :
calculate_cell_slab_info_col_col_s<double>;
} else if(coords_type == TILEDB_INT8) {
advance_cell_slab_ = advance_cell_slab_col_s<int8_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<int8_t> :
calculate_cell_slab_info_col_col_s<int8_t>;
} else if(coords_type == TILEDB_UINT8) {
advance_cell_slab_ = advance_cell_slab_col_s<uint8_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<uint8_t> :
calculate_cell_slab_info_col_col_s<uint8_t>;
} else if(coords_type == TILEDB_INT16) {
advance_cell_slab_ = advance_cell_slab_col_s<int16_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<int16_t> :
calculate_cell_slab_info_col_col_s<int16_t>;
} else if(coords_type == TILEDB_UINT16) {
advance_cell_slab_ = advance_cell_slab_col_s<uint16_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<uint16_t> :
calculate_cell_slab_info_col_col_s<uint16_t>;
} else if(coords_type == TILEDB_UINT32) {
advance_cell_slab_ = advance_cell_slab_col_s<uint32_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<uint32_t> :
calculate_cell_slab_info_col_col_s<uint32_t>;
} else if(coords_type == TILEDB_UINT64) {
advance_cell_slab_ = advance_cell_slab_col_s<uint64_t>;
calculate_cell_slab_info_ =
(cell_order == TILEDB_ROW_MAJOR) ?
calculate_cell_slab_info_col_row_s<uint64_t> :
calculate_cell_slab_info_col_col_s<uint64_t>;
} else {
assert(0);
}
}
if(tile_order == TILEDB_ROW_MAJOR) {
if(coords_type == TILEDB_INT32)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<int>;
else if(coords_type == TILEDB_INT64)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<int64_t>;
else if(coords_type == TILEDB_FLOAT32)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<float>;
else if(coords_type == TILEDB_FLOAT64)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<double>;
else if(coords_type == TILEDB_INT8)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<int8_t>;
else if(coords_type == TILEDB_UINT8)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<uint8_t>;
else if(coords_type == TILEDB_INT16)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<int16_t>;
else if(coords_type == TILEDB_UINT16)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<uint16_t>;
else if(coords_type == TILEDB_UINT32)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<uint32_t>;
else if(coords_type == TILEDB_UINT64)
calculate_tile_slab_info_ = calculate_tile_slab_info_row<uint64_t>;
else
assert(0);
} else { // tile_order == TILEDB_COL_MAJOR
if(coords_type == TILEDB_INT32)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<int>;
else if(coords_type == TILEDB_INT64)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<int64_t>;
else if(coords_type == TILEDB_FLOAT32)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<float>;
else if(coords_type == TILEDB_FLOAT64)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<double>;
else if(coords_type == TILEDB_INT8)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<int8_t>;
else if(coords_type == TILEDB_UINT8)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<uint8_t>;
else if(coords_type == TILEDB_INT16)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<int16_t>;
else if(coords_type == TILEDB_UINT16)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<uint16_t>;
else if(coords_type == TILEDB_UINT32)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<uint32_t>;
else if(coords_type == TILEDB_UINT64)
calculate_tile_slab_info_ = calculate_tile_slab_info_col<uint64_t>;
else
assert(0);
}
// Create the thread that will be handling all the copying
if(pthread_create(
©_thread_,
NULL,
ArraySortedReadState::copy_handler,
this)) {
std::string errmsg = "Cannot create AIO thread";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
copy_thread_running_ = true;
// Success
return TILEDB_ASRS_OK;
}
/* ****************************** */
/* PRIVATE METHODS */
/* ****************************** */
template<class T>
void *ArraySortedReadState::advance_cell_slab_col_s(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int aid = ((ASRS_Data*) data)->id_;
asrs->advance_cell_slab_col<T>(aid);
return NULL;
}
template<class T>
void *ArraySortedReadState::advance_cell_slab_row_s(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int aid = ((ASRS_Data*) data)->id_;
asrs->advance_cell_slab_row<T>(aid);
return NULL;
}
template<class T>
void ArraySortedReadState::advance_cell_slab_col(int aid) {
// For easy reference
int64_t& tid = tile_slab_state_.current_tile_[aid]; // Tile id
int64_t cell_slab_num = tile_slab_info_[copy_id_].cell_slab_num_[tid];
T* current_coords = (T*) tile_slab_state_.current_coords_[aid];
const T* tile_slab = (const T*) tile_slab_norm_[copy_id_];
// Advance cell slab coordinates
int d = 0;
current_coords[d] += cell_slab_num;
int64_t dim_overflow;
for(int i=0; i<dim_num_-1; ++i) {
dim_overflow =
(current_coords[i] - tile_slab[2*i]) /
(tile_slab[2*i+1]-tile_slab[2*i]+1);
current_coords[i+1] += dim_overflow;
current_coords[i] -= dim_overflow * (tile_slab[2*i+1]-tile_slab[2*i]+1);
}
// Check if done
if(current_coords[dim_num_-1] > tile_slab[2*(dim_num_-1)+1]) {
tile_slab_state_.copy_tile_slab_done_[aid] = true;
return;
}
// Calculate new tile and offset for the current coords
update_current_tile_and_offset<T>(aid);
}
template<class T>
void ArraySortedReadState::advance_cell_slab_row(int aid) {
// For easy reference
int64_t& tid = tile_slab_state_.current_tile_[aid]; // Tile id
int64_t cell_slab_num = tile_slab_info_[copy_id_].cell_slab_num_[tid];
T* current_coords = (T*) tile_slab_state_.current_coords_[aid];
const T* tile_slab = (const T*) tile_slab_norm_[copy_id_];
// Advance cell slab coordinates
int d = dim_num_-1;
current_coords[d] += cell_slab_num;
int64_t dim_overflow;
for(int i=d; i>0; --i) {
dim_overflow =
(current_coords[i] - tile_slab[2*i]) /
(tile_slab[2*i+1]-tile_slab[2*i]+1);
current_coords[i-1] += dim_overflow;
current_coords[i] -= dim_overflow * (tile_slab[2*i+1]-tile_slab[2*i]+1);
}
// Check if done
if(current_coords[0] > tile_slab[1]) {
tile_slab_state_.copy_tile_slab_done_[aid] = true;
return;
}
// Calculate new tile and offset for the current coords
update_current_tile_and_offset<T>(aid);
}
void *ArraySortedReadState::aio_done(void* data) {
// Retrieve data
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int id = ((ASRS_Data*) data)->id_;
// For easy reference
int anum = (int) asrs->attribute_ids_.size();
const ArraySchema* array_schema = asrs->array_->array_schema();
// Check for overflow
bool overflow = false;
for(int i=0; i<anum; ++i) {
if(asrs->overflow_still_[i] && asrs->aio_overflow_[id][i]) {
overflow = true;
break;
}
}
// Handle overflow
bool sparse = array_schema->dense();
if(overflow) { // OVERFLOW
// Update buffer sizes
for(int i=0, b=0; i<anum; ++i) {
if(!array_schema->var_size(asrs->attribute_ids_[i])) { // FIXED
if(asrs->aio_overflow_[id][i]) {
// Expand buffer
expand_buffer(asrs->buffers_[id][b], asrs->buffer_sizes_[id][b]);
// Re-assign the buffer size for the fixed-sized offsets
asrs->buffer_sizes_tmp_[id][b] = asrs->buffer_sizes_[id][b];
} else {
// Backup sizes and zero them
asrs->buffer_sizes_tmp_bak_[id][b] = asrs->buffer_sizes_tmp_[id][b];
asrs->buffer_sizes_tmp_[id][b] = 0;
// Does not overflow any more
asrs->overflow_still_[i] = false;
}
++b;
} else { // VAR
if(asrs->aio_overflow_[id][i]) {
// Expand offset buffer only in the case of sparse arrays
if(sparse)
expand_buffer(asrs->buffers_[id][b], asrs->buffer_sizes_[id][b]);
// Re-assign the buffer size for the fixed-sized offsets
asrs->buffer_sizes_tmp_[id][b] = asrs->buffer_sizes_[id][b];
++b;
// Expand variable-length cell buffers for both dense and sparse
expand_buffer(asrs->buffers_[id][b], asrs->buffer_sizes_[id][b]);
// Assign the new buffer size for the variable-sized values
asrs->buffer_sizes_tmp_[id][b] = asrs->buffer_sizes_[id][b];
++b;
} else {
// Backup sizes and zero them (fixed-sized offsets)
asrs->buffer_sizes_tmp_bak_[id][b] = asrs->buffer_sizes_tmp_[id][b];
asrs->buffer_sizes_tmp_[id][b] = 0;
++b;
// Backup sizes and zero them (variable-sized values)
asrs->buffer_sizes_tmp_bak_[id][b] = asrs->buffer_sizes_tmp_[id][b];
asrs->buffer_sizes_tmp_[id][b] = 0;
++b;
// Does not overflow any more
asrs->overflow_still_[i] = false;
}
}
}
// Send the request again
asrs->send_aio_request(id);
} else { // NO OVERFLOW
// Restore backup temporary buffer sizes
for(int b=0; b<asrs->buffer_num_; ++b) {
if(asrs->buffer_sizes_tmp_bak_[id][b] != 0)
asrs->buffer_sizes_tmp_[id][b] = asrs->buffer_sizes_tmp_bak_[id][b];
}
// Manage the mutexes and conditions
asrs->release_aio(id);
}
return NULL;
}
bool ArraySortedReadState::aio_overflow(int aio_id) {
// For easy reference
int anum = (int) attribute_ids_.size();
for(int i=0; i<anum; ++i) {
if(aio_overflow_[aio_id][i])
return true;
}
return false;
}
void ArraySortedReadState::block_aio(int id) {
lock_aio_mtx();
wait_aio_[id] = true;
unlock_aio_mtx();
}
void ArraySortedReadState::block_copy(int id) {
lock_copy_mtx();
wait_copy_[id] = true;
unlock_copy_mtx();
}
void ArraySortedReadState::block_overflow() {
lock_overflow_mtx();
resume_copy_ = true;
unlock_overflow_mtx();
}
void ArraySortedReadState::calculate_attribute_ids() {
// Initialization
attribute_ids_ = array_->attribute_ids();
coords_attr_i_ = -1;
// For ease reference
const ArraySchema* array_schema = array_->array_schema();
int attribute_num = array_schema->attribute_num();
// No need to do anything else in case the array is dense
if(array_schema->dense())
return;
// Find the coordinates index
for(int i=0; i<(int)attribute_ids_.size(); ++i) {
if(attribute_ids_[i] == attribute_num) {
coords_attr_i_ = i;
break;
}
}
// If the coordinates index is not found, append coordinates attribute
// to attribute ids.
if(coords_attr_i_ == -1) {
attribute_ids_.push_back(attribute_num);
coords_attr_i_ = attribute_ids_.size() - 1;
extra_coords_ = true;
} else { // No extra coordinates appended
extra_coords_ = false;
}
}
void ArraySortedReadState::calculate_buffer_num() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
int attribute_num = array_schema->attribute_num();
// Calculate number of buffers
buffer_num_ = 0;
int attribute_id_num = (int) attribute_ids_.size();
for(int i=0; i<attribute_id_num; ++i) {
// Fix-sized attribute
if(!array_schema->var_size(attribute_ids_[i])) {
if(attribute_ids_[i] == attribute_num)
coords_buf_i_ = i; // Buffer that holds the coordinates
++buffer_num_;
} else { // Variable-sized attribute
buffer_num_ += 2;
}
}
}
void ArraySortedReadState::calculate_buffer_sizes() {
if(array_->array_schema()->dense())
calculate_buffer_sizes_dense();
else
calculate_buffer_sizes_sparse();
}
void ArraySortedReadState::calculate_buffer_sizes_dense() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
// Get cell number in a (full) tile slab
int64_t tile_slab_cell_num;
if(array_->mode() == TILEDB_ARRAY_READ_SORTED_ROW)
tile_slab_cell_num = array_schema->tile_slab_row_cell_num(subarray_);
else // TILEDB_ARRAY_READ_SORTED_COL
tile_slab_cell_num = array_schema->tile_slab_col_cell_num(subarray_);
// Calculate buffer sizes
int attribute_id_num = (int) attribute_ids_.size();
for(int j=0; j<2; ++j) {
buffer_sizes_[j] = new size_t[buffer_num_];
buffer_sizes_tmp_[j] = new size_t[buffer_num_];
buffer_sizes_tmp_bak_[j] = new size_t[buffer_num_];
for(int i=0, b=0; i<attribute_id_num; ++i) {
// Fix-sized attribute
if(!array_schema->var_size(attribute_ids_[i])) {
buffer_sizes_[j][b] =
tile_slab_cell_num * array_schema->cell_size(attribute_ids_[i]);
buffer_sizes_tmp_bak_[j][b] = 0;
++b;
} else { // Variable-sized attribute
buffer_sizes_[j][b] = tile_slab_cell_num * sizeof(size_t);
buffer_sizes_tmp_bak_[j][b] = 0;
++b;
buffer_sizes_[j][b] = 2 * tile_slab_cell_num * sizeof(size_t);
buffer_sizes_tmp_bak_[j][b] = 0;
++b;
}
}
}
}
void ArraySortedReadState::calculate_buffer_sizes_sparse() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
// Calculate buffer sizes
int attribute_id_num = (int) attribute_ids_.size();
for(int j=0; j<2; ++j) {
buffer_sizes_[j] = new size_t[buffer_num_];
buffer_sizes_tmp_[j] = new size_t[buffer_num_];
buffer_sizes_tmp_bak_[j] = new size_t[buffer_num_];
for(int i=0, b=0; i<attribute_id_num; ++i) {
// Fix-sized buffer
buffer_sizes_[j][b] = TILEDB_ASRS_INIT_BUFFER_SIZE;
buffer_sizes_tmp_bak_[j][b] = 0;
++b;
if(array_schema->var_size(attribute_ids_[i])) { // Variable-sized buffer
buffer_sizes_[j][b] = 2*TILEDB_ASRS_INIT_BUFFER_SIZE;
buffer_sizes_tmp_bak_[j][b] = 0;
++b;
}
}
}
}
template<class T>
void *ArraySortedReadState::calculate_cell_slab_info_col_col_s(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int id = ((ASRS_Data*) data)->id_;
int tid = ((ASRS_Data*) data)->id_2_;
asrs->calculate_cell_slab_info_col_col<T>(id, tid);
return NULL;
}
template<class T>
void *ArraySortedReadState::calculate_cell_slab_info_col_row_s(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int id = ((ASRS_Data*) data)->id_;
int tid = ((ASRS_Data*) data)->id_2_;
asrs->calculate_cell_slab_info_col_row<T>(id, tid);
return NULL;
}
template<class T>
void *ArraySortedReadState::calculate_cell_slab_info_row_col_s(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int id = ((ASRS_Data*) data)->id_;
int tid = ((ASRS_Data*) data)->id_2_;
asrs->calculate_cell_slab_info_row_col<T>(id, tid);
return NULL;
}
template<class T>
void *ArraySortedReadState::calculate_cell_slab_info_row_row_s(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int id = ((ASRS_Data*) data)->id_;
int tid = ((ASRS_Data*) data)->id_2_;
asrs->calculate_cell_slab_info_row_row<T>(id, tid);
return NULL;
}
template<class T>
void ArraySortedReadState::calculate_cell_slab_info_col_col(
int id,
int64_t tid) {
// For easy reference
int anum = (int) attribute_ids_.size();
const T* range_overlap = (const T*) tile_slab_info_[id].range_overlap_[tid];
const T* tile_domain = (const T*) tile_domain_;
int64_t tile_num, cell_num;
// Calculate number of cells in cell slab
cell_num = range_overlap[1] - range_overlap[0] + 1;
for(int i=0; i<dim_num_-1; ++i) {
tile_num = tile_domain[2*i+1] - tile_domain[2*i] + 1;
if(tile_num == 1)
cell_num *= range_overlap[2*(i+1)+1] - range_overlap[2*(i+1)] + 1;
else
break;
}
tile_slab_info_[id].cell_slab_num_[tid] = cell_num;
// Calculate size of a cell slab per attribute
for(int aid=0; aid<anum; ++aid)
tile_slab_info_[id].cell_slab_size_[aid][tid] =
tile_slab_info_[id].cell_slab_num_[tid] * attribute_sizes_[aid];
// Calculate cell offset per dimension
int64_t cell_offset = 1;
tile_slab_info_[id].cell_offset_per_dim_[tid][0] = cell_offset;
for(int i=1; i<dim_num_; ++i) {
cell_offset *= (range_overlap[2*(i-1)+1] - range_overlap[2*(i-1)] + 1);
tile_slab_info_[id].cell_offset_per_dim_[tid][i] = cell_offset;
}
}
template<class T>
void ArraySortedReadState::calculate_cell_slab_info_row_row(
int id,
int64_t tid) {
// For easy reference
int anum = (int) attribute_ids_.size();
const T* range_overlap = (const T*) tile_slab_info_[id].range_overlap_[tid];
const T* tile_domain = (const T*) tile_domain_;
int64_t tile_num, cell_num;
// Calculate number of cells in cell slab
cell_num = range_overlap[2*(dim_num_-1)+1] - range_overlap[2*(dim_num_-1)] +1;
for(int i=dim_num_-1; i>0; --i) {
tile_num = tile_domain[2*i+1] - tile_domain[2*i] + 1;
if(tile_num == 1)
cell_num *= range_overlap[2*(i-1)+1] - range_overlap[2*(i-1)] + 1;
else
break;
}
tile_slab_info_[id].cell_slab_num_[tid] = cell_num;
// Calculate size of a cell slab per attribute
for(int aid=0; aid<anum; ++aid)
tile_slab_info_[id].cell_slab_size_[aid][tid] =
tile_slab_info_[id].cell_slab_num_[tid] * attribute_sizes_[aid];
// Calculate cell offset per dimension
int64_t cell_offset = 1;
tile_slab_info_[id].cell_offset_per_dim_[tid][dim_num_-1] = cell_offset;
for(int i=dim_num_-2; i>=0; --i) {
cell_offset *= (range_overlap[2*(i+1)+1] - range_overlap[2*(i+1)] + 1);
tile_slab_info_[id].cell_offset_per_dim_[tid][i] = cell_offset;
}
}
template<class T>
void ArraySortedReadState::calculate_cell_slab_info_col_row(
int id,
int64_t tid) {
// For easy reference
int anum = (int) attribute_ids_.size();
const T* range_overlap = (const T*) tile_slab_info_[id].range_overlap_[tid];
// Calculate number of cells in cell slab
tile_slab_info_[id].cell_slab_num_[tid] = 1;
// Calculate size of a cell slab per attribute
for(int aid=0; aid<anum; ++aid)
tile_slab_info_[id].cell_slab_size_[aid][tid] =
tile_slab_info_[id].cell_slab_num_[tid] * attribute_sizes_[aid];
// Calculate cell offset per dimension
int64_t cell_offset = 1;
tile_slab_info_[id].cell_offset_per_dim_[tid][dim_num_-1] = cell_offset;
for(int i=dim_num_-2; i>=0; --i) {
cell_offset *= (range_overlap[2*(i+1)+1] - range_overlap[2*(i+1)] + 1);
tile_slab_info_[id].cell_offset_per_dim_[tid][i] = cell_offset;
}
}
template<class T>
void ArraySortedReadState::calculate_cell_slab_info_row_col(
int id,
int64_t tid) {
// For easy reference
int anum = (int) attribute_ids_.size();
const T* range_overlap = (const T*) tile_slab_info_[id].range_overlap_[tid];
// Calculate number of cells in cell slab
tile_slab_info_[id].cell_slab_num_[tid] = 1;
// Calculate size of a cell slab per attribute
for(int aid=0; aid<anum; ++aid)
tile_slab_info_[id].cell_slab_size_[aid][tid] =
tile_slab_info_[id].cell_slab_num_[tid] * attribute_sizes_[aid];
// Calculate cell offset per dimension
int64_t cell_offset = 1;
tile_slab_info_[id].cell_offset_per_dim_[tid][0] = cell_offset;
for(int i=1; i<dim_num_; ++i) {
cell_offset *= (range_overlap[2*(i-1)+1] - range_overlap[2*(i-1)] + 1);
tile_slab_info_[id].cell_offset_per_dim_[tid][i] = cell_offset;
}
}
template<class T>
void ArraySortedReadState::calculate_tile_domain(int id) {
// Initializations
tile_coords_ = malloc(coords_size_);
tile_domain_ = malloc(2*coords_size_);
// For easy reference
const T* tile_slab = (const T*) tile_slab_norm_[id];
const T* tile_extents = (const T*) array_->array_schema()->tile_extents();
T* tile_coords = (T*) tile_coords_;
T* tile_domain = (T*) tile_domain_;
// Calculate tile domain and initial tile coordinates
for(int i=0; i<dim_num_; ++i) {
tile_coords[i] = 0;
tile_domain[2*i] = tile_slab[2*i] / tile_extents[i];
tile_domain[2*i+1] = tile_slab[2*i+1] / tile_extents[i];
}
}
template<class T>
void ArraySortedReadState::calculate_tile_slab_info(int id) {
// Calculate number of tiles, if they are not already calculated
if(tile_slab_info_[id].tile_num_ == -1)
init_tile_slab_info<T>(id);
// Calculate tile domain, if not calculated yet
if(tile_domain_ == NULL)
calculate_tile_domain<T>(id);
// Reset tile coordinates
reset_tile_coords<T>();
// Calculate tile slab info
ASRS_Data asrs_data = { id, 0, this };
(*calculate_tile_slab_info_)(&asrs_data);
}
template<class T>
void *ArraySortedReadState::calculate_tile_slab_info_col(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int id = ((ASRS_Data*) data)->id_;
asrs->calculate_tile_slab_info_col<T>(id);
return NULL;
}
template<class T>
void ArraySortedReadState::calculate_tile_slab_info_col(int id) {
// For easy reference
const T* tile_domain = (const T*) tile_domain_;
T* tile_coords = (T*) tile_coords_;
const T* tile_extents = (const T*) array_->array_schema()->tile_extents();
T** range_overlap = (T**) tile_slab_info_[id].range_overlap_;
const T* tile_slab = (const T*) tile_slab_norm_[id];
int64_t tile_offset, tile_cell_num, total_cell_num = 0;
int anum = (int) attribute_ids_.size();
int d;
// Iterate over all tiles in the tile domain
int64_t tid=0; // Tile id
while(tile_coords[dim_num_-1] <= tile_domain[2*(dim_num_-1)+1]) {
// Calculate range overlap, number of cells in the tile
tile_cell_num = 1;
for(int i=0; i<dim_num_; ++i) {
// Range overlap
range_overlap[tid][2*i] =
MAX(tile_coords[i] * tile_extents[i], tile_slab[2*i]);
range_overlap[tid][2*i+1] =
MIN((tile_coords[i]+1) * tile_extents[i] - 1, tile_slab[2*i+1]);
// Number of cells in this tile
tile_cell_num *= range_overlap[tid][2*i+1] - range_overlap[tid][2*i] + 1;
}
// Calculate tile offsets per dimension
tile_offset = 1;
tile_slab_info_[id].tile_offset_per_dim_[0] = tile_offset;
for(int i=1; i<dim_num_; ++i) {
tile_offset *= (tile_domain[2*(i-1)+1] - tile_domain[2*(i-1)] + 1);
tile_slab_info_[id].tile_offset_per_dim_[i] = tile_offset;
}
// Calculate cell slab info
ASRS_Data asrs_data = { id, tid, this };
(*calculate_cell_slab_info_)(&asrs_data);
// Calculate start offsets
for(int aid=0; aid<anum; ++aid) {
tile_slab_info_[id].start_offsets_[aid][tid] =
total_cell_num * attribute_sizes_[aid];
}
total_cell_num += tile_cell_num;
// Advance tile coordinates
d=0;
++tile_coords[d];
while(d < dim_num_-1 && tile_coords[d] > tile_domain[2*d+1]) {
tile_coords[d] = tile_domain[2*d];
++tile_coords[++d];
}
// Advance tile id
++tid;
}
}
template<class T>
void *ArraySortedReadState::calculate_tile_slab_info_row(void* data) {
ArraySortedReadState* asrs = ((ASRS_Data*) data)->asrs_;
int id = ((ASRS_Data*) data)->id_;
asrs->calculate_tile_slab_info_row<T>(id);
return NULL;
}
template<class T>
void ArraySortedReadState::calculate_tile_slab_info_row(int id) {
// For easy reference
const T* tile_domain = (const T*) tile_domain_;
T* tile_coords = (T*) tile_coords_;
const T* tile_extents = (const T*) array_->array_schema()->tile_extents();
T** range_overlap = (T**) tile_slab_info_[id].range_overlap_;
const T* tile_slab = (const T*) tile_slab_norm_[id];
int64_t tile_offset, tile_cell_num, total_cell_num = 0;
int anum = (int) attribute_ids_.size();
int d;
// Iterate over all tiles in the tile domain
int64_t tid=0; // Tile id
while(tile_coords[0] <= tile_domain[1]) {
// Calculate range overlap, number of cells in the tile
tile_cell_num = 1;
for(int i=0; i<dim_num_; ++i) {
// Range overlap
range_overlap[tid][2*i] =
MAX(tile_coords[i] * tile_extents[i], tile_slab[2*i]);
range_overlap[tid][2*i+1] =
MIN((tile_coords[i]+1) * tile_extents[i] - 1, tile_slab[2*i+1]);
// Number of cells in this tile
tile_cell_num *= range_overlap[tid][2*i+1] - range_overlap[tid][2*i] + 1;
}
// Calculate tile offsets per dimension
tile_offset = 1;
tile_slab_info_[id].tile_offset_per_dim_[dim_num_-1] = tile_offset;
for(int i=dim_num_-2; i>=0; --i) {
tile_offset *= (tile_domain[2*(i+1)+1] - tile_domain[2*(i+1)] + 1);
tile_slab_info_[id].tile_offset_per_dim_[i] = tile_offset;
}
// Calculate cell slab info
ASRS_Data asrs_data = { id, tid, this };
(*calculate_cell_slab_info_)(&asrs_data);
// Calculate start offsets
for(int aid=0; aid<anum; ++aid) {
tile_slab_info_[id].start_offsets_[aid][tid] =
total_cell_num * attribute_sizes_[aid];
}
total_cell_num += tile_cell_num;
// Advance tile coordinates
d=dim_num_-1;
++tile_coords[d];
while(d > 0 && tile_coords[d] > tile_domain[2*d+1]) {
tile_coords[d] = tile_domain[2*d];
++tile_coords[--d];
}
// Advance tile id
++tid;
}
}
void *ArraySortedReadState::copy_handler(void* context) {
// For easy reference
ArraySortedReadState* asrs = (ArraySortedReadState*) context;
// This will enter an indefinite loop that will handle all incoming copy
// requests
int coords_type = asrs->array_->array_schema()->coords_type();
if(asrs->array_->array_schema()->dense()) { // DENSE
if(coords_type == TILEDB_INT32)
asrs->handle_copy_requests_dense<int>();
else if(coords_type == TILEDB_INT64)
asrs->handle_copy_requests_dense<int64_t>();
else if(coords_type == TILEDB_FLOAT32)
asrs->handle_copy_requests_dense<float>();
else if(coords_type == TILEDB_FLOAT64)
asrs->handle_copy_requests_dense<double>();
else if(coords_type == TILEDB_INT8)
asrs->handle_copy_requests_dense<int8_t>();
else if(coords_type == TILEDB_UINT8)
asrs->handle_copy_requests_dense<uint8_t>();
else if(coords_type == TILEDB_INT16)
asrs->handle_copy_requests_dense<int16_t>();
else if(coords_type == TILEDB_UINT16)
asrs->handle_copy_requests_dense<uint16_t>();
else if(coords_type == TILEDB_UINT32)
asrs->handle_copy_requests_dense<uint32_t>();
else if(coords_type == TILEDB_UINT64)
asrs->handle_copy_requests_dense<uint64_t>();
else
assert(0);
} else { // SPARSE
if(coords_type == TILEDB_INT32)
asrs->handle_copy_requests_sparse<int>();
else if(coords_type == TILEDB_INT64)
asrs->handle_copy_requests_sparse<int64_t>();
else if(coords_type == TILEDB_FLOAT32)
asrs->handle_copy_requests_sparse<float>();
else if(coords_type == TILEDB_FLOAT64)
asrs->handle_copy_requests_sparse<double>();
else if(coords_type == TILEDB_INT8)
asrs->handle_copy_requests_sparse<int8_t>();
else if(coords_type == TILEDB_UINT8)
asrs->handle_copy_requests_sparse<uint8_t>();
else if(coords_type == TILEDB_INT16)
asrs->handle_copy_requests_sparse<int16_t>();
else if(coords_type == TILEDB_UINT16)
asrs->handle_copy_requests_sparse<uint16_t>();
else if(coords_type == TILEDB_UINT32)
asrs->handle_copy_requests_sparse<uint32_t>();
else if(coords_type == TILEDB_UINT64)
asrs->handle_copy_requests_sparse<uint64_t>();
else
assert(0);
}
// Return
return NULL;
}
void ArraySortedReadState::copy_tile_slab_dense() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
// Copy tile slab for each attribute separately
for(int i=0, b=0; i<(int)attribute_ids_.size(); ++i) {
if(!array_schema->var_size(attribute_ids_[i])) {
copy_tile_slab_dense(i, b);
++b;
} else {
copy_tile_slab_dense_var(i, b);
b += 2;
}
}
}
void ArraySortedReadState::copy_tile_slab_dense(int aid, int bid) {
// Exit if copy is done for this attribute
if(tile_slab_state_.copy_tile_slab_done_[aid]) {
copy_state_.buffer_sizes_[bid] = 0; // Nothing written
return;
}
// For easy reference
int64_t& tid = tile_slab_state_.current_tile_[aid];
size_t& buffer_offset = copy_state_.buffer_offsets_[bid];
size_t buffer_size = copy_state_.buffer_sizes_[bid];
char* buffer = (char*) copy_state_.buffers_[bid];
char* local_buffer = (char*) buffers_[copy_id_][bid];
ASRS_Data asrs_data = { aid, 0, this };
// Iterate over the tile slab cells
for(;;) {
// For easy reference
size_t cell_slab_size = tile_slab_info_[copy_id_].cell_slab_size_[aid][tid];
size_t& local_buffer_offset = tile_slab_state_.current_offsets_[aid];
// Handle overflow
if(buffer_offset + cell_slab_size > buffer_size) {
overflow_[aid] = true;
break;
}
// Copy cell slab
memcpy(
buffer + buffer_offset,
local_buffer + local_buffer_offset,
cell_slab_size);
// Update buffer offset
buffer_offset += cell_slab_size;
// Prepare for new cell slab
(*advance_cell_slab_)(&asrs_data);
// Terminating condition
if(tile_slab_state_.copy_tile_slab_done_[aid])
break;
}
// Set user buffer size
buffer_size = buffer_offset;
}
void ArraySortedReadState::copy_tile_slab_dense_var(int aid, int bid) {
// Exit if copy is done for this attribute
if(tile_slab_state_.copy_tile_slab_done_[aid]) {
copy_state_.buffer_sizes_[bid] = 0; // Nothing written
copy_state_.buffer_sizes_[bid+1] = 0; // Nothing written
return;
}
// For easy reference
int64_t& tid = tile_slab_state_.current_tile_[aid];
size_t cell_slab_size_var;
size_t& buffer_offset = copy_state_.buffer_offsets_[bid];
size_t& buffer_offset_var = copy_state_.buffer_offsets_[bid+1];
size_t buffer_size = copy_state_.buffer_sizes_[bid];
size_t buffer_size_var = copy_state_.buffer_sizes_[bid+1];
char* buffer = (char*) copy_state_.buffers_[bid];
char* buffer_var = (char*) copy_state_.buffers_[bid+1];
char* local_buffer_var = (char*) buffers_[copy_id_][bid+1];
size_t local_buffer_size = buffer_sizes_tmp_[copy_id_][bid];
size_t local_buffer_var_size = buffer_sizes_tmp_[copy_id_][bid+1];
size_t* local_buffer_s = (size_t*) buffers_[copy_id_][bid];
int64_t cell_num_in_buffer = local_buffer_size / sizeof(size_t);
size_t var_offset = buffer_offset_var;
ASRS_Data asrs_data = { aid, 0, this };
// For all overlapping tiles, in a round-robin fashion
for(;;) {
// For easy reference
size_t cell_slab_size =
tile_slab_info_[copy_id_].cell_slab_size_[aid][tid];
int64_t cell_num_in_slab = cell_slab_size / sizeof(size_t);
size_t& local_buffer_offset = tile_slab_state_.current_offsets_[aid];
// Handle overflow
if(buffer_offset + cell_slab_size > buffer_size) {
overflow_[aid] = true;
break;
}
// Calculate variable cell slab size
int64_t cell_start = local_buffer_offset / sizeof(size_t);
int64_t cell_end = cell_start + cell_num_in_slab;
cell_slab_size_var =
(cell_end == cell_num_in_buffer) ?
local_buffer_var_size - local_buffer_s[cell_start] :
local_buffer_s[cell_end] - local_buffer_s[cell_start];
// Handle overflow for the the variable-length buffer
if(buffer_offset_var + cell_slab_size_var > buffer_size_var) {
overflow_[aid] = true;
break;
}
// Copy fixed-sized offsets
for(int64_t i=cell_start; i<cell_end; ++i) {
memcpy(
buffer + buffer_offset,
&var_offset,
sizeof(size_t));
buffer_offset += sizeof(size_t);
var_offset += (i == cell_num_in_buffer-1) ?
local_buffer_var_size - local_buffer_s[i] :
local_buffer_s[i+1] - local_buffer_s[i];
}
// Copy variable-sized values
memcpy(
buffer_var + buffer_offset_var,
local_buffer_var + local_buffer_s[cell_start],
cell_slab_size_var);
buffer_offset_var += cell_slab_size_var;
// Prepare for new cell slab
(*advance_cell_slab_)(&asrs_data);
// Terminating condition
if(tile_slab_state_.copy_tile_slab_done_[aid])
break;
}
// Set user buffer sizes
buffer_size = buffer_offset;
buffer_size_var = buffer_offset_var;
}
void ArraySortedReadState::copy_tile_slab_sparse() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
// Copy tile slab for each attribute separately
for(int i=0, b=0; i<(int)attribute_ids_.size(); ++i) {
if(!array_schema->var_size(attribute_ids_[i])) { // FIXED
// Make sure not to copy coordinates if the user has not requested them
if(i != coords_attr_i_ || !extra_coords_)
copy_tile_slab_sparse(i, b);
++b;
} else { // VAR
copy_tile_slab_sparse_var(i, b);
b += 2;
}
}
}
void ArraySortedReadState::copy_tile_slab_sparse(int aid, int bid) {
// Exit if copy is done for this attribute
if(tile_slab_state_.copy_tile_slab_done_[aid]) {
copy_state_.buffer_sizes_[bid] = 0; // Nothing written
return;
}
// For easy reference
size_t cell_size = array_->array_schema()->cell_size(attribute_ids_[aid]);
size_t& buffer_offset = copy_state_.buffer_offsets_[bid];
size_t buffer_size = copy_state_.buffer_sizes_[bid];
char* buffer = (char*) copy_state_.buffers_[bid];
char* local_buffer = (char*) buffers_[copy_id_][bid];
size_t local_buffer_offset;
int64_t cell_num = buffer_sizes_tmp_[copy_id_][coords_buf_i_] / coords_size_;
int64_t& current_cell_pos = tile_slab_state_.current_cell_pos_[aid];
// Iterate over the remaining tile slab cells in a sorted order
for(; current_cell_pos<cell_num; ++current_cell_pos) {
// Handle overflow
if(buffer_offset + cell_size > buffer_size) {
overflow_[aid] = true;
break;
}
// Calculate new local buffer offset
local_buffer_offset = cell_pos_[current_cell_pos] * cell_size;
// Copy cell slab
memcpy(
buffer + buffer_offset,
local_buffer + local_buffer_offset,
cell_size);
// Update buffer offset
buffer_offset += cell_size;
}
// Mark tile slab as done
if(current_cell_pos == cell_num)
tile_slab_state_.copy_tile_slab_done_[aid] = true;
// Set user buffer size
buffer_size = buffer_offset;
}
void ArraySortedReadState::copy_tile_slab_sparse_var(int aid, int bid) {
// Exit if copy is done for this attribute
if(tile_slab_state_.copy_tile_slab_done_[aid]) {
copy_state_.buffer_sizes_[bid] = 0; // Nothing written
copy_state_.buffer_sizes_[bid+1] = 0; // Nothing written
return;
}
// For easy reference
size_t cell_size = sizeof(size_t);
size_t cell_size_var;
size_t& buffer_offset = copy_state_.buffer_offsets_[bid];
size_t& buffer_offset_var = copy_state_.buffer_offsets_[bid+1];
size_t buffer_size = copy_state_.buffer_sizes_[bid];
size_t buffer_size_var = copy_state_.buffer_sizes_[bid+1];
char* buffer = (char*) copy_state_.buffers_[bid];
char* buffer_var = (char*) copy_state_.buffers_[bid+1];
char* local_buffer_var = (char*) buffers_[copy_id_][bid+1];
size_t local_buffer_var_size = buffer_sizes_tmp_[copy_id_][bid+1];
size_t* local_buffer_s = (size_t*) buffers_[copy_id_][bid];
int64_t cell_num = buffer_sizes_tmp_[copy_id_][coords_buf_i_] / coords_size_;
int64_t& current_cell_pos = tile_slab_state_.current_cell_pos_[aid];
// Iterate over the remaining tile slab cells in a sorted order
for(; current_cell_pos<cell_num; ++current_cell_pos) {
// Handle overflow
if(buffer_offset + cell_size > buffer_size) {
overflow_[aid] = true;
break;
}
// Calculate variable cell size
int64_t cell_start = cell_pos_[current_cell_pos];
int64_t cell_end = cell_start + 1;
cell_size_var =
(cell_end == cell_num) ?
local_buffer_var_size - local_buffer_s[cell_start] :
local_buffer_s[cell_end] - local_buffer_s[cell_start];
// Handle overflow for the the variable-length buffer
if(buffer_offset_var + cell_size_var > buffer_size_var) {
overflow_[aid] = true;
break;
}
// Copy fixed-sized offset
memcpy(
buffer + buffer_offset,
&buffer_offset_var,
sizeof(size_t));
buffer_offset += sizeof(size_t);
// Copy variable-sized values
memcpy(
buffer_var + buffer_offset_var,
local_buffer_var + local_buffer_s[cell_start],
cell_size_var);
buffer_offset_var += cell_size_var;
}
// Mark tile slab as done
if(current_cell_pos == cell_num)
tile_slab_state_.copy_tile_slab_done_[aid] = true;
// Set user buffer sizes
buffer_size = buffer_offset;
buffer_size_var = buffer_offset_var;
}
int ArraySortedReadState::create_buffers() {
for(int j=0; j<2; ++j) {
buffers_[j] = (void**) malloc(buffer_num_ * sizeof(void*));
if(buffers_[j] == NULL) {
std::string errmsg = "Cannot create local buffers";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
for(int b=0; b < buffer_num_; ++b) {
buffers_[j][b] = malloc(buffer_sizes_[j][b]);
if(buffers_[j][b] == NULL) {
std::string errmsg = "Cannot allocate local buffer";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
}
}
// Success
return TILEDB_ASRS_OK;
}
void ArraySortedReadState::free_copy_state() {
if(copy_state_.buffer_offsets_ != NULL)
delete [] copy_state_.buffer_offsets_;
}
void ArraySortedReadState::free_tile_slab_info() {
// Do nothing in the case of sparse arrays
if(!array_->array_schema()->dense())
return;
// For easy reference
int anum = (int) attribute_ids_.size();
// Free
for(int i=0; i<2; ++i) {
int64_t tile_num = tile_slab_info_[i].tile_num_;
if(tile_slab_info_[i].cell_offset_per_dim_ != NULL) {
for(int j=0; j<tile_num; ++j)
delete [] tile_slab_info_[i].cell_offset_per_dim_[j];
delete [] tile_slab_info_[i].cell_offset_per_dim_;
}
for(int j=0; j<anum; ++j) {
if(tile_slab_info_[i].cell_slab_size_[j] != NULL)
delete [] tile_slab_info_[i].cell_slab_size_[j];
}
delete [] tile_slab_info_[i].cell_slab_size_;
if(tile_slab_info_[i].cell_slab_num_ != NULL)
delete [] tile_slab_info_[i].cell_slab_num_;
if(tile_slab_info_[i].range_overlap_ != NULL) {
for(int j=0; j<tile_num; ++j)
free(tile_slab_info_[i].range_overlap_[j]);
delete [] tile_slab_info_[i].range_overlap_;
}
for(int j=0; j<anum; ++j) {
if(tile_slab_info_[i].start_offsets_[j] != NULL)
delete [] tile_slab_info_[i].start_offsets_[j];
}
delete [] tile_slab_info_[i].start_offsets_;
delete [] tile_slab_info_[i].tile_offset_per_dim_;
}
}
void ArraySortedReadState::free_tile_slab_state() {
// For easy reference
int anum = (int) attribute_ids_.size();
// Clean up
if(tile_slab_state_.current_coords_ != NULL) {
for(int i=0; i<anum; ++i)
free(tile_slab_state_.current_coords_[i]);
delete [] tile_slab_state_.current_coords_;
}
if(tile_slab_state_.copy_tile_slab_done_ != NULL)
delete [] tile_slab_state_.copy_tile_slab_done_;
if(tile_slab_state_.current_offsets_ != NULL)
delete [] tile_slab_state_.current_offsets_;
if(tile_slab_state_.current_tile_ != NULL)
delete [] tile_slab_state_.current_tile_;
if(tile_slab_state_.current_cell_pos_ != NULL)
delete [] tile_slab_state_.current_cell_pos_;
}
template<class T>
int64_t ArraySortedReadState::get_cell_id(int aid) {
// For easy reference
const T* current_coords = (const T*) tile_slab_state_.current_coords_[aid];
int64_t tid = tile_slab_state_.current_tile_[aid];
const T* range_overlap =
(const T*) tile_slab_info_[copy_id_].range_overlap_[tid];
int64_t* cell_offset_per_dim =
tile_slab_info_[copy_id_].cell_offset_per_dim_[tid];
// Calculate cell id
int64_t cid = 0;
for(int i=0; i<dim_num_; ++i)
cid += (current_coords[i] - range_overlap[2*i]) * cell_offset_per_dim[i];
// Return tile id
return cid;
}
template<class T>
int64_t ArraySortedReadState::get_tile_id(int aid) {
// For easy reference
const T* current_coords = (const T*) tile_slab_state_.current_coords_[aid];
const T* tile_extents = (const T*) array_->array_schema()->tile_extents();
int64_t* tile_offset_per_dim = tile_slab_info_[copy_id_].tile_offset_per_dim_;
// Calculate tile id
int64_t tid = 0;
for(int i=0; i<dim_num_; ++i)
tid += (current_coords[i] / tile_extents[i]) * tile_offset_per_dim[i];
// Return tile id
return tid;
}
template<class T>
void ArraySortedReadState::handle_copy_requests_dense() {
// Handle copy requests indefinitely
for(;;) {
// Wait for AIO
wait_aio(copy_id_);
// Kill thread, after releasing any blocked resources
if(copy_thread_canceled_) {
copy_thread_running_ = false;
return;
}
// Reset the tile slab state
if(copy_tile_slab_done())
reset_tile_slab_state<T>();
// Start the copy
copy_tile_slab_dense();
// Wait in case of overflow
if(overflow()) {
block_overflow();
block_aio(copy_id_);
release_copy(0);
release_copy(1);
wait_overflow();
continue;
}
// Copy is done
block_aio(copy_id_);
release_copy(copy_id_);
copy_id_ = (copy_id_ + 1) % 2;
}
}
template<class T>
void ArraySortedReadState::handle_copy_requests_sparse() {
// Handle copy requests indefinitely
for(;;) {
// Wait for AIO
wait_aio(copy_id_);
// Kill thread, after releasing any blocked resources
if(copy_thread_canceled_) {
copy_thread_running_ = false;
return;
}
// Sort the cell positions
if(copy_tile_slab_done()) {
reset_tile_slab_state<T>();
sort_cell_pos<T>();
}
// Start the copy
copy_tile_slab_sparse();
// Wait in case of overflow
if(overflow()) {
block_overflow();
block_aio(copy_id_);
release_copy(0);
release_copy(1);
wait_overflow();
continue;
}
// Copy is done
block_aio(copy_id_);
release_copy(copy_id_);
copy_id_ = (copy_id_ + 1) % 2;
}
}
void ArraySortedReadState::init_aio_requests() {
for(int i=0; i<2; ++i) {
aio_data_[i] = { i, 0, this };
aio_request_[i] = {};
aio_request_[i].buffer_sizes_ = buffer_sizes_tmp_[i];
aio_request_[i].buffers_ = buffers_[i];
aio_request_[i].mode_ = TILEDB_ARRAY_READ;
aio_request_[i].subarray_ = tile_slab_[i];
aio_request_[i].completion_handle_ = aio_done;
aio_request_[i].completion_data_ = &(aio_data_[i]);
aio_request_[i].overflow_ = aio_overflow_[i];
aio_request_[i].status_ = &(aio_status_[i]);
}
}
void ArraySortedReadState::init_copy_state() {
copy_state_.buffer_sizes_ = NULL;
copy_state_.buffers_ = NULL;
copy_state_.buffer_offsets_ = new size_t[buffer_num_];
for(int i=0; i<buffer_num_; ++i)
copy_state_.buffer_offsets_[i] = 0;
}
void ArraySortedReadState::init_tile_slab_info() {
// Do nothing in the case of sparse arrays
if(!array_->array_schema()->dense())
return;
// For easy reference
int anum = (int) attribute_ids_.size();
// Initialize
for(int i=0; i<2; ++i) {
tile_slab_info_[i].cell_offset_per_dim_ = NULL;
tile_slab_info_[i].cell_slab_size_ = new size_t*[anum];
tile_slab_info_[i].cell_slab_num_ = NULL;
tile_slab_info_[i].range_overlap_ = NULL;
tile_slab_info_[i].start_offsets_ = new size_t*[anum];
tile_slab_info_[i].tile_offset_per_dim_ = new int64_t[dim_num_];
for(int j=0; j<anum; ++j) {
tile_slab_info_[i].cell_slab_size_[j] = NULL;
tile_slab_info_[i].start_offsets_[j] = NULL;
}
tile_slab_info_[i].tile_num_ = -1;
}
}
template<class T>
void ArraySortedReadState::init_tile_slab_info(int id) {
// Sanity check
assert(array_->array_schema()->dense());
// For easy reference
int anum = (int) attribute_ids_.size();
// Calculate tile number
int64_t tile_num = array_->array_schema()->tile_num(tile_slab_[id]);
// Initializations
tile_slab_info_[id].cell_offset_per_dim_ = new int64_t*[tile_num];
tile_slab_info_[id].cell_slab_num_ = new int64_t[tile_num];
tile_slab_info_[id].range_overlap_ = new void*[tile_num];
for(int64_t i=0; i<tile_num; ++i) {
tile_slab_info_[id].range_overlap_[i] = malloc(2*coords_size_);
tile_slab_info_[id].cell_offset_per_dim_[i] = new int64_t[dim_num_];
}
for(int i=0; i<anum; ++i) {
tile_slab_info_[id].cell_slab_size_[i] = new size_t[tile_num];
tile_slab_info_[id].start_offsets_[i] = new size_t[tile_num];
}
tile_slab_info_[id].tile_num_ = tile_num;
}
void ArraySortedReadState::init_tile_slab_state() {
// For easy reference
int anum = (int) attribute_ids_.size();
bool dense = array_->array_schema()->dense();
// Both for dense and sparse
tile_slab_state_.copy_tile_slab_done_ = new bool[anum];
for(int i=0; i<anum; ++i)
tile_slab_state_.copy_tile_slab_done_[i] = true; // Important!
// Allocations and initializations
if(dense) { // DENSE
tile_slab_state_.current_offsets_ = new size_t[anum];
tile_slab_state_.current_coords_ = new void*[anum];
tile_slab_state_.current_tile_ = new int64_t[anum];
tile_slab_state_.current_cell_pos_ = NULL;
for(int i=0; i<anum; ++i) {
tile_slab_state_.current_coords_[i] = malloc(coords_size_);
tile_slab_state_.current_offsets_[i] = 0;
tile_slab_state_.current_tile_[i] = 0;
}
} else { // SPARSE
tile_slab_state_.current_offsets_ = NULL;
tile_slab_state_.current_coords_ = NULL;
tile_slab_state_.current_tile_ = NULL;
tile_slab_state_.current_cell_pos_ = new int64_t[anum];
for(int i=0; i<anum; ++i)
tile_slab_state_.current_cell_pos_[i] = 0;
}
}
int ArraySortedReadState::lock_aio_mtx() {
if(pthread_mutex_lock(&aio_mtx_)) {
std::string errmsg = "Cannot lock AIO mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::lock_copy_mtx() {
if(pthread_mutex_lock(©_mtx_)) {
std::string errmsg = "Cannot lock copy mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::lock_overflow_mtx() {
if(pthread_mutex_lock(&overflow_mtx_)) {
std::string errmsg = "Cannot lock overflow mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Success
return TILEDB_ASRS_OK;
}
template<class T>
bool ArraySortedReadState::next_tile_slab_dense_col() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
const T* domain = static_cast<const T*>(array_schema->domain());
const T* tile_extents = static_cast<const T*>(array_schema->tile_extents());
T* tile_slab[2];
T* tile_slab_norm = static_cast<T*>(tile_slab_norm_[aio_id_]);
for(int i=0; i<2; ++i)
tile_slab[i] = static_cast<T*>(tile_slab_[i]);
int prev_id = (aio_id_+1)%2;
T tile_start;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][2*(dim_num_-1) + 1] == subarray[2*(dim_num_-1) + 1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][2*(dim_num_-1)] = subarray[2*(dim_num_-1)];
T upper = subarray[2*(dim_num_-1)] + tile_extents[dim_num_-1];
T cropped_upper =
(upper - domain[2*(dim_num_-1)]) / tile_extents[dim_num_-1] *
tile_extents[dim_num_-1] + domain[2*(dim_num_-1)];
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(cropped_upper - 1, subarray[2*(dim_num_-1)+1]);
// Leave the rest of the subarray extents intact
for(int i=0; i<dim_num_-1; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][2*(dim_num_-1)] =
tile_slab[aio_id_][2*(dim_num_-1)+1] + 1;
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(
tile_slab[aio_id_][2*(dim_num_-1)] + tile_extents[dim_num_-1] - 1,
subarray[2*(dim_num_-1)+1]);
}
// Calculate normalized tile slab
for(int i=0; i<dim_num_; ++i) {
tile_start =
((tile_slab[aio_id_][2*i] - domain[2*i]) / tile_extents[i]) *
tile_extents[i] + domain[2*i];
tile_slab_norm[2*i] = tile_slab[aio_id_][2*i] - tile_start;
tile_slab_norm[2*i+1] = tile_slab[aio_id_][2*i+1] - tile_start;
}
// Calculate tile slab info and reset tile slab state
calculate_tile_slab_info<T>(aio_id_);
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<class T>
bool ArraySortedReadState::next_tile_slab_dense_row() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
const T* domain = static_cast<const T*>(array_schema->domain());
const T* tile_extents = static_cast<const T*>(array_schema->tile_extents());
T* tile_slab[2];
T* tile_slab_norm = static_cast<T*>(tile_slab_norm_[aio_id_]);
for(int i=0; i<2; ++i)
tile_slab[i] = static_cast<T*>(tile_slab_[i]);
int prev_id = (aio_id_+1)%2;
T tile_start;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][1] == subarray[1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][0] = subarray[0];
T upper = subarray[0] + tile_extents[0];
T cropped_upper =
(upper - domain[0]) / tile_extents[0] * tile_extents[0] + domain[0];
tile_slab[aio_id_][1] = MIN(cropped_upper - 1, subarray[1]);
// Leave the rest of the subarray extents intact
for(int i=1; i<dim_num_; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][0] = tile_slab[aio_id_][1] + 1;
tile_slab[aio_id_][1] = MIN(
tile_slab[aio_id_][0] + tile_extents[0] - 1,
subarray[1]);
}
// Calculate normalized tile slab
for(int i=0; i<dim_num_; ++i) {
tile_start =
((tile_slab[aio_id_][2*i] - domain[2*i]) / tile_extents[i]) *
tile_extents[i] + domain[2*i];
tile_slab_norm[2*i] = tile_slab[aio_id_][2*i] - tile_start;
tile_slab_norm[2*i+1] = tile_slab[aio_id_][2*i+1] - tile_start;
}
// Calculate tile slab info and reset tile slab state
calculate_tile_slab_info<T>(aio_id_);
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<class T>
bool ArraySortedReadState::next_tile_slab_sparse_col() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
const T* domain = static_cast<const T*>(array_schema->domain());
const T* tile_extents = static_cast<const T*>(array_schema->tile_extents());
T* tile_slab[2];
for(int i=0; i<2; ++i)
tile_slab[i] = static_cast<T*>(tile_slab_[i]);
int prev_id = (aio_id_+1)%2;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][2*(dim_num_-1) + 1] == subarray[2*(dim_num_-1) + 1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][2*(dim_num_-1)] = subarray[2*(dim_num_-1)];
T upper = subarray[2*(dim_num_-1)] + tile_extents[dim_num_-1];
T cropped_upper =
(upper - domain[2*(dim_num_-1)]) / tile_extents[dim_num_-1] *
tile_extents[dim_num_-1] + domain[2*(dim_num_-1)];
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(cropped_upper - 1, subarray[2*(dim_num_-1)+1]);
// Leave the rest of the subarray extents intact
for(int i=0; i<dim_num_-1; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][2*(dim_num_-1)] =
tile_slab[aio_id_][2*(dim_num_-1)+1] + 1;
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(
tile_slab[aio_id_][2*(dim_num_-1)] + tile_extents[dim_num_-1] - 1,
subarray[2*(dim_num_-1)+1]);
}
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<>
bool ArraySortedReadState::next_tile_slab_sparse_col<float>() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const float* subarray = (const float*) subarray_;
const float* domain = (const float*) array_schema->domain();
const float* tile_extents = (const float*) array_schema->tile_extents();
float* tile_slab[2];
for(int i=0; i<2; ++i)
tile_slab[i] = (float*) tile_slab_[i];
int prev_id = (aio_id_+1)%2;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][2*(dim_num_-1) + 1] == subarray[2*(dim_num_-1) + 1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][2*(dim_num_-1)] = subarray[2*(dim_num_-1)];
float upper = subarray[2*(dim_num_-1)] + tile_extents[dim_num_-1];
float cropped_upper =
floor((upper - domain[2*(dim_num_-1)]) / tile_extents[dim_num_-1]) *
tile_extents[dim_num_-1] + domain[2*(dim_num_-1)];
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(cropped_upper - FLT_MIN, subarray[2*(dim_num_-1)+1]);
// Leave the rest of the subarray extents intact
for(int i=0; i<dim_num_-1; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][2*(dim_num_-1)] =
tile_slab[aio_id_][2*(dim_num_-1)+1] + FLT_MIN;
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(
tile_slab[aio_id_][2*(dim_num_-1)] +
tile_extents[dim_num_-1] - FLT_MIN,
subarray[2*(dim_num_-1)+1]);
}
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<>
bool ArraySortedReadState::next_tile_slab_sparse_col<double>() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const double* subarray = (const double*) subarray_;
const double* domain = (const double*) array_schema->domain();
const double* tile_extents = (const double*) array_schema->tile_extents();
double* tile_slab[2];
for(int i=0; i<2; ++i)
tile_slab[i] = (double*) tile_slab_[i];
int prev_id = (aio_id_+1)%2;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][2*(dim_num_-1) + 1] == subarray[2*(dim_num_-1) + 1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][2*(dim_num_-1)] = subarray[2*(dim_num_-1)];
double upper = subarray[2*(dim_num_-1)] + tile_extents[dim_num_-1];
double cropped_upper =
floor((upper - domain[2*(dim_num_-1)]) / tile_extents[dim_num_-1]) *
tile_extents[dim_num_-1] + domain[2*(dim_num_-1)];
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(cropped_upper - DBL_MIN, subarray[2*(dim_num_-1)+1]);
// Leave the rest of the subarray extents intact
for(int i=0; i<dim_num_-1; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][2*(dim_num_-1)] =
tile_slab[aio_id_][2*(dim_num_-1)+1] + DBL_MIN;
tile_slab[aio_id_][2*(dim_num_-1)+1] =
MIN(
tile_slab[aio_id_][2*(dim_num_-1)] +
tile_extents[dim_num_-1] - DBL_MIN,
subarray[2*(dim_num_-1)+1]);
}
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<class T>
bool ArraySortedReadState::next_tile_slab_sparse_row() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
const T* domain = static_cast<const T*>(array_schema->domain());
const T* tile_extents = static_cast<const T*>(array_schema->tile_extents());
T* tile_slab[2];
for(int i=0; i<2; ++i)
tile_slab[i] = static_cast<T*>(tile_slab_[i]);
int prev_id = (aio_id_+1)%2;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][1] == subarray[1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][0] = subarray[0];
T upper = subarray[0] + tile_extents[0];
T cropped_upper =
(upper - domain[0]) / tile_extents[0] * tile_extents[0] + domain[0];
tile_slab[aio_id_][1] = MIN(cropped_upper - 1, subarray[1]);
// Leave the rest of the subarray extents intact
for(int i=1; i<dim_num_; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][0] = tile_slab[aio_id_][1] + 1;
tile_slab[aio_id_][1] = MIN(
tile_slab[aio_id_][0] + tile_extents[0] - 1,
subarray[1]);
}
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<>
bool ArraySortedReadState::next_tile_slab_sparse_row<float>() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const float* subarray = (const float*) subarray_;
const float* domain = (const float*) array_schema->domain();
const float* tile_extents = (const float*) array_schema->tile_extents();
float* tile_slab[2];
for(int i=0; i<2; ++i)
tile_slab[i] = (float*) tile_slab_[i];
int prev_id = (aio_id_+1)%2;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][1] == subarray[1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][0] = subarray[0];
float upper = subarray[0] + tile_extents[0];
float cropped_upper =
floor((upper - domain[0]) / tile_extents[0]) * tile_extents[0] +
domain[0];
tile_slab[aio_id_][1] = MIN(cropped_upper - FLT_MIN, subarray[1]);
// Leave the rest of the subarray extents intact
for(int i=1; i<dim_num_; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][0] = tile_slab[aio_id_][1] + FLT_MIN;
tile_slab[aio_id_][1] =
MIN(
tile_slab[aio_id_][0] + tile_extents[0] - FLT_MIN,
subarray[1]);
}
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<>
bool ArraySortedReadState::next_tile_slab_sparse_row<double>() {
// Quick check if done
if(read_tile_slabs_done_)
return false;
// If the AIO needs to be resumed, exit (no need for a new tile slab)
if(resume_aio_) {
resume_aio_ = false;
return true;
}
// Wait for the previous copy on aio_id_ buffer to be consumed
wait_copy(aio_id_);
// Block copy
block_copy(aio_id_);
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const double* subarray = (const double*) subarray_;
const double* domain = (const double*) array_schema->domain();
const double* tile_extents = (const double*) array_schema->tile_extents();
double* tile_slab[2];
for(int i=0; i<2; ++i)
tile_slab[i] = (double*) tile_slab_[i];
int prev_id = (aio_id_+1)%2;
// Check again if done, this time based on the tile slab and subarray
if(tile_slab_init_[prev_id] &&
tile_slab[prev_id][1] == subarray[1]) {
read_tile_slabs_done_ = true;
return false;
}
// If this is the first time this function is called, initialize
if(!tile_slab_init_[prev_id]) {
// Crop the subarray extent along the first axis to fit in the first tile
tile_slab[aio_id_][0] = subarray[0];
double upper = subarray[0] + tile_extents[0];
double cropped_upper =
floor((upper - domain[0]) / tile_extents[0]) * tile_extents[0] +
domain[0];
tile_slab[aio_id_][1] = MIN(cropped_upper - DBL_MIN, subarray[1]);
// Leave the rest of the subarray extents intact
for(int i=1; i<dim_num_; ++i) {
tile_slab[aio_id_][2*i] = subarray[2*i];
tile_slab[aio_id_][2*i+1] = subarray[2*i+1];
}
} else { // Calculate a new slab based on the previous
// Copy previous tile slab
memcpy(
tile_slab[aio_id_],
tile_slab[prev_id],
2*coords_size_);
// Advance tile slab
tile_slab[aio_id_][0] = tile_slab[aio_id_][1] + DBL_MIN;
tile_slab[aio_id_][1] =
MIN(
tile_slab[aio_id_][0] + tile_extents[0] - DBL_MIN,
subarray[1]);
}
// Mark this tile slab as initialized
tile_slab_init_[aio_id_] = true;
// Success
return true;
}
template<class T>
int ArraySortedReadState::read() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
int mode = array_->mode();
if(mode == TILEDB_ARRAY_READ_SORTED_COL) {
if(array_schema->dense())
return read_dense_sorted_col<T>();
else
return read_sparse_sorted_col<T>();
} else if(mode == TILEDB_ARRAY_READ_SORTED_ROW) {
if(array_schema->dense())
return read_dense_sorted_row<T>();
else
return read_sparse_sorted_row<T>();
} else {
assert(0); // The code should never reach here
return TILEDB_ASRS_ERR;
}
}
template<class T>
int ArraySortedReadState::read_dense_sorted_col() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
// Check if this can be satisfied with a default read
if(array_schema->cell_order() == TILEDB_COL_MAJOR &&
array_schema->is_contained_in_tile_slab_row<T>(subarray))
return array_->read_default(
copy_state_.buffers_,
copy_state_.buffer_sizes_);
// Iterate over each tile slab
while(next_tile_slab_dense_col<T>()) {
// Read the next tile slab with the default cell order
if(read_tile_slab() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Handle overflow
if(resume_aio_)
break;
}
// Wait for copy to finish
int copy_id = (resume_aio_) ? aio_id_ : (aio_id_ + 1) % 2;
wait_copy(copy_id);
// Assign the true buffer sizes
for(int i=0; i<buffer_num_; ++i)
copy_state_.buffer_sizes_[i] = copy_state_.buffer_offsets_[i];
// The following will make the copy thread terminate
if(done()) {
copy_thread_canceled_ = true;
release_aio(aio_id_);
}
// Success
return TILEDB_ASRS_OK;
}
template<class T>
int ArraySortedReadState::read_dense_sorted_row() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
// Check if this can be satisfied with a default read
if(array_schema->cell_order() == TILEDB_ROW_MAJOR &&
array_schema->is_contained_in_tile_slab_col<T>(subarray))
return array_->read_default(
copy_state_.buffers_,
copy_state_.buffer_sizes_);
// Iterate over each tile slab
while(next_tile_slab_dense_row<T>()) {
// Read the next tile slab with the default cell order
if(read_tile_slab() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Handle overflow
if(resume_aio_)
break;
}
// Wait for copy and AIO to finish
int copy_id = (resume_aio_) ? aio_id_ : (aio_id_ + 1) % 2;
wait_copy(copy_id);
// Assign the true buffer sizes
for(int i=0; i<buffer_num_; ++i)
copy_state_.buffer_sizes_[i] = copy_state_.buffer_offsets_[i];
// The following will make the copy thread terminate
if(done()) {
copy_thread_canceled_ = true;
release_aio(aio_id_);
}
// Success
return TILEDB_ASRS_OK;
}
template<class T>
int ArraySortedReadState::read_sparse_sorted_col() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
// Check if this can be satisfied with a default read
if(array_schema->cell_order() == TILEDB_COL_MAJOR &&
array_schema->is_contained_in_tile_slab_row<T>(subarray))
return array_->read_default(
copy_state_.buffers_,
copy_state_.buffer_sizes_);
// Iterate over each tile slab
while(next_tile_slab_sparse_col<T>()) {
// Read the next tile slab with the default cell order
if(read_tile_slab() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Handle overflow
if(resume_aio_)
break;
}
// Wait for copy to finish
int copy_id = (resume_aio_) ? aio_id_ : (aio_id_ + 1) % 2;
wait_copy(copy_id);
// Assign the true buffer sizes
int buffer_num = buffer_num_ - (int) extra_coords_;
for(int i=0; i<buffer_num; ++i)
copy_state_.buffer_sizes_[i] = copy_state_.buffer_offsets_[i];
// The following will make the copy thread terminate
if(done()) {
copy_thread_canceled_ = true;
release_aio(aio_id_);
}
// Success
return TILEDB_ASRS_OK;
}
template<class T>
int ArraySortedReadState::read_sparse_sorted_row() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
const T* subarray = static_cast<const T*>(subarray_);
// Check if this can be satisfied with a default read
if(array_schema->cell_order() == TILEDB_ROW_MAJOR &&
array_schema->is_contained_in_tile_slab_col<T>(subarray))
return array_->read_default(
copy_state_.buffers_,
copy_state_.buffer_sizes_);
// Iterate over each tile slab
while(next_tile_slab_sparse_row<T>()) {
// Read the next tile slab with the default cell order
if(read_tile_slab() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Handle overflow
if(resume_aio_)
break;
}
// Wait for copy and AIO to finish
int copy_id = (resume_aio_) ? aio_id_ : (aio_id_ + 1) % 2;
wait_copy(copy_id);
// Assign the true buffer sizes
int buffer_num = buffer_num_ - (int) extra_coords_;
for(int i=0; i<buffer_num; ++i)
copy_state_.buffer_sizes_[i] = copy_state_.buffer_offsets_[i];
// The following will make the copy thread terminate
if(done()) {
copy_thread_canceled_ = true;
release_aio(aio_id_);
}
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::read_tile_slab() {
// We need to exit if the copy did no complete (due to overflow)
if(resume_copy_) {
resume_aio_ = true;
return TILEDB_ASRS_OK;
}
// Reset AIO overflow flags
reset_aio_overflow(aio_id_);
// Reset temporary buffer sizes
reset_buffer_sizes_tmp(aio_id_);
// Send AIO request
if(send_aio_request(aio_id_) != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Change aio_id_
aio_id_ = (aio_id_ + 1) % 2;
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::release_aio(int id) {
// Lock the AIO mutex
if(lock_aio_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Set AIO flag
wait_aio_[id] = false;
// Signal condition
if(pthread_cond_signal(&(aio_cond_[id]))) {
std::string errmsg = "Cannot signal AIO condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Unlock the AIO mutex
if(unlock_aio_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::release_copy(int id) {
// Lock the copy mutex
if(lock_copy_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Set copy flag
wait_copy_[id] = false;
// Signal condition
if(pthread_cond_signal(©_cond_[id])) {
std::string errmsg = "Cannot signal copy condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Unlock the copy mutex
if(unlock_copy_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::release_overflow() {
// Lock the overflow mutex
if(lock_overflow_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Set copy flag
resume_copy_ = false;
// Signal condition
if(pthread_cond_signal(&overflow_cond_)) {
std::string errmsg = "Cannot signal overflow condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Unlock the overflow mutex
if(unlock_overflow_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Success
return TILEDB_ASRS_OK;
}
void ArraySortedReadState::reset_aio_overflow(int aio_id) {
// For easy reference
int anum = (int) attribute_ids_.size();
// Reset aio_overflow_
for(int i=0; i<anum; ++i)
aio_overflow_[aio_id][i] = false;
}
void ArraySortedReadState::reset_buffer_sizes_tmp(int id) {
for(int i=0; i<buffer_num_; ++i)
buffer_sizes_tmp_[id][i] = buffer_sizes_[id][i];
}
void ArraySortedReadState::reset_copy_state(
void** buffers,
size_t* buffer_sizes) {
copy_state_.buffers_ = buffers;
copy_state_.buffer_sizes_ = buffer_sizes;
for(int i=0; i<buffer_num_; ++i)
copy_state_.buffer_offsets_[i] = 0;
}
void ArraySortedReadState::reset_overflow() {
for(int i=0; i<(int) attribute_ids_.size(); ++i)
overflow_[i] = false;
}
template<class T>
void ArraySortedReadState::reset_tile_coords() {
T* tile_coords = (T*) tile_coords_;
for(int i=0; i<dim_num_; ++i)
tile_coords[i] = 0;
}
template<class T>
void ArraySortedReadState::reset_tile_slab_state() {
// For easy reference
int anum = (int) attribute_ids_.size();
bool dense = array_->array_schema()->dense();
// Both dense and sparse
for(int i=0; i<anum; ++i)
tile_slab_state_.copy_tile_slab_done_[i] = false;
if(dense) { // DENSE
T** current_coords = (T**) tile_slab_state_.current_coords_;
const T* tile_slab = (const T*) tile_slab_norm_[copy_id_];
// Reset values
for(int i=0; i<anum; ++i) {
tile_slab_state_.current_offsets_[i] = 0;
tile_slab_state_.current_tile_[i] = 0;
for(int j=0; j<dim_num_; ++j)
current_coords[i][j] = tile_slab[2*j];
}
} else { // SPARSE
for(int i=0; i<anum; ++i)
tile_slab_state_.current_cell_pos_[i] = 0;
}
}
int ArraySortedReadState::send_aio_request(int aio_id) {
// Important!!
aio_request_[aio_id].id_ = aio_cnt_++;
// For easy reference
Array* array_clone = array_->array_clone();
// Sanity check
assert(array_clone != NULL);
// Send the AIO request to the clone array
if(array_clone->aio_read(&(aio_request_[aio_id])) != TILEDB_AR_OK) {
tiledb_asrs_errmsg = tiledb_ar_errmsg;
return TILEDB_ASRS_ERR;
}
// Success
return TILEDB_ASRS_OK;
}
template<class T>
void ArraySortedReadState::sort_cell_pos() {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
int dim_num = array_schema->dim_num();
int64_t cell_num = buffer_sizes_tmp_[copy_id_][coords_buf_i_] / coords_size_;
int mode = array_->mode();
const T* buffer = static_cast<const T*>(buffers_[copy_id_][coords_buf_i_]);
// Populate cell_pos
cell_pos_.resize(cell_num);
for(int i=0; i<cell_num; ++i)
cell_pos_[i] = i;
// Invoke the proper sort function, based on the mode
if(mode == TILEDB_ARRAY_READ_SORTED_ROW) {
// Sort cell positions
SORT(
cell_pos_.begin(),
cell_pos_.end(),
SmallerRow<T>(buffer, dim_num));
} else { // mode == TILEDB_ARRAY_READ_SORTED_COL
// Sort cell positions
SORT(
cell_pos_.begin(),
cell_pos_.end(),
SmallerCol<T>(buffer, dim_num));
}
}
int ArraySortedReadState::unlock_aio_mtx() {
if(pthread_mutex_unlock(&aio_mtx_)) {
std::string errmsg = "Cannot unlock AIO mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::unlock_copy_mtx() {
if(pthread_mutex_unlock(©_mtx_)) {
std::string errmsg = "Cannot unlock copy mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::unlock_overflow_mtx() {
if(pthread_mutex_unlock(&overflow_mtx_)) {
std::string errmsg = "Cannot unlock overflow mutex";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
// Success
return TILEDB_ASRS_OK;
}
template<class T>
void ArraySortedReadState::update_current_tile_and_offset(int aid) {
// For easy reference
int64_t& tid = tile_slab_state_.current_tile_[aid];
size_t& current_offset = tile_slab_state_.current_offsets_[aid];
int64_t cid;
// Calculate the new tile id
tid = get_tile_id<T>(aid);
// Calculate the cell id
cid = get_cell_id<T>(aid);
// Calculate new offset
current_offset =
tile_slab_info_[copy_id_].start_offsets_[aid][tid] +
cid * attribute_sizes_[aid];
}
int ArraySortedReadState::wait_aio(int id) {
// Lock AIO mutex
if(lock_aio_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Wait to be signaled
while(wait_aio_[id]) {
if(pthread_cond_wait(&(aio_cond_[id]), &aio_mtx_)) {
std::string errmsg = "Cannot wait on IO mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
}
// Unlock AIO mutex
if(unlock_aio_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::wait_copy(int id) {
// Lock copy mutex
if(lock_copy_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Wait to be signaled
while(wait_copy_[id]) {
if(pthread_cond_wait(&(copy_cond_[id]), ©_mtx_)) {
std::string errmsg = "Cannot wait on copy mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
}
// Unlock copy mutex
if(unlock_copy_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Success
return TILEDB_ASRS_OK;
}
int ArraySortedReadState::wait_overflow() {
// Lock overflow mutex
if(lock_overflow_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Wait to be signaled
while(overflow()) {
if(pthread_cond_wait(&overflow_cond_, &overflow_mtx_)) {
std::string errmsg = "Cannot wait on IO mutex condition";
PRINT_ERROR(errmsg);
tiledb_asrs_errmsg = TILEDB_ASRS_ERRMSG + errmsg;
return TILEDB_ASRS_ERR;
}
}
// Unlock overflow mutex
if(unlock_overflow_mtx() != TILEDB_ASRS_OK)
return TILEDB_ASRS_ERR;
// Success
return TILEDB_ASRS_OK;
}
// Explicit template instantiations
template int ArraySortedReadState::read_dense_sorted_col<int>();
template int ArraySortedReadState::read_dense_sorted_col<int64_t>();
template int ArraySortedReadState::read_dense_sorted_col<float>();
template int ArraySortedReadState::read_dense_sorted_col<double>();
template int ArraySortedReadState::read_dense_sorted_col<int8_t>();
template int ArraySortedReadState::read_dense_sorted_col<uint8_t>();
template int ArraySortedReadState::read_dense_sorted_col<int16_t>();
template int ArraySortedReadState::read_dense_sorted_col<uint16_t>();
template int ArraySortedReadState::read_dense_sorted_col<uint32_t>();
template int ArraySortedReadState::read_dense_sorted_col<uint64_t>();
template int ArraySortedReadState::read_dense_sorted_row<int>();
template int ArraySortedReadState::read_dense_sorted_row<int64_t>();
template int ArraySortedReadState::read_dense_sorted_row<float>();
template int ArraySortedReadState::read_dense_sorted_row<double>();
template int ArraySortedReadState::read_dense_sorted_row<int8_t>();
template int ArraySortedReadState::read_dense_sorted_row<uint8_t>();
template int ArraySortedReadState::read_dense_sorted_row<int16_t>();
template int ArraySortedReadState::read_dense_sorted_row<uint16_t>();
template int ArraySortedReadState::read_dense_sorted_row<uint32_t>();
template int ArraySortedReadState::read_dense_sorted_row<uint64_t>();
| [
"stavrosp@csail.mit.edu"
] | stavrosp@csail.mit.edu |
6fc3a72b98e674478987312549032da8c84aafad | 6f91c0a3a160bb68fc1232572c09a0b2af00caae | /src/windows/dx11/RenderTargetViewDX11.h | d293c1a3c356c90d33eac9406de0fb5a322922a2 | [] | no_license | mrlonelyjtr/forward | fb59c691ea666ad34c25f8705905a889ac7ac687 | c4b64dfb29cfccac6a437f443ec09628dbe735b8 | refs/heads/master | 2021-01-10T06:11:30.015557 | 2016-01-23T06:13:27 | 2016-01-23T06:13:27 | 47,819,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,128 | h | //--------------------------------------------------------------------------------
// RenderTargetViewDX11
//
//--------------------------------------------------------------------------------
#ifndef RenderTargetViewDX11_h
#define RenderTargetViewDX11_h
//--------------------------------------------------------------------------------
#include <wrl.h>
#include <d3d11_2.h>
//--------------------------------------------------------------------------------
namespace forward
{
typedef Microsoft::WRL::ComPtr<ID3D11RenderTargetView> RenderTargetViewComPtr;
class RenderTargetViewDX11
{
public:
RenderTargetViewDX11( RenderTargetViewComPtr pView );
~RenderTargetViewDX11();
ID3D11RenderTargetView* GetRTV();
protected:
RenderTargetViewComPtr m_pRenderTargetView;
friend class PipelineManagerDX11;
friend class OutputMergerStageDX11;
friend class RendererDX11;
};
};
//--------------------------------------------------------------------------------
#endif // RenderTargetViewDX11_h
//--------------------------------------------------------------------------------
| [
"296793179@qq.com"
] | 296793179@qq.com |
c6238104a63a7a18ca1b872014adf2786ff20a26 | 04f69fbb63338708338fa70bb7453da623eff993 | /test/unit/reduction/thread/testbed.h | 919839b3d647d3e92e3c3c6babf3adaf3ca5975b | [
"BSD-3-Clause"
] | permissive | denghuilu/cutlass | 570de4fc2ceaa8e7140cdf9cffe017da92cbeb76 | eb3488e9c836e65d5af4a00383d702ff80f3eb1d | refs/heads/master | 2020-12-09T08:25:27.010671 | 2020-06-29T19:49:15 | 2020-06-29T19:49:15 | 233,248,828 | 1 | 0 | BSD-3-Clause | 2020-06-25T09:06:24 | 2020-01-11T14:59:42 | null | UTF-8 | C++ | false | false | 6,610 | h | /***************************************************************************************************
* Copyright (c) 2017-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
* * 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 NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 TOR (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Unit tests for thread-level Reduction
*/
#pragma once
#include "cutlass/reduction/thread/reduce.h"
#include "cutlass/layout/vector.h"
#include "cutlass/util/host_tensor.h"
#include "cutlass/util/tensor_view_io.h"
#include "cutlass/util/reference/host/tensor_copy.h"
#include "cutlass/util/reference/host/tensor_fill.h"
#include "cutlass/util/reference/host/tensor_compare.h"
namespace test {
namespace reduction {
namespace thread {
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Structure to compute the reduction
template <
/// Data type of elements
typename Element,
/// Number of elements
int N
>
struct Testbed_reduce_host {
/// Thread-level reduction operator
using Reduce = cutlass::reduction::thread::Reduce<
cutlass::plus<Element>,
cutlass::Array<Element, N>
>;
//
// Data members
//
cutlass::Array<Element, N> tensor_in;
cutlass::Array<Element, 1> reduced_tensor_computed;
cutlass::Array<Element, 1> reduced_tensor_reference;
//
// Methods
//
/// Allocates workspace in device memory
Testbed_reduce_host() {
tensor_in.clear();
reduced_tensor_computed.clear();
reduced_tensor_reference.clear();
}
/// Runs the test
bool run() {
//
// initialize memory
//
for(int i = 0; i < N; i++)
tensor_in.at(i) = Element(i);
Reduce reduce;
cutlass::Array<Element, 1> *out_ptr = &reduced_tensor_computed;
out_ptr[0] = reduce(tensor_in);
//
// Reference implementation
//
Element e(0);
for (int i = 0; i < N; i++)
e = e + Element(i);
reduced_tensor_reference.at(0) = e;
//
// Verify equivalence
//
// compare
bool passed = reduced_tensor_reference[0] == reduced_tensor_computed[0];
EXPECT_TRUE(passed)
<< "Expected = " << float(reduced_tensor_reference.at(0)) << "\n\n"
<< "Actual = " << float(reduced_tensor_computed.at(0)) << "\n\n"
<< std::endl;
return passed;
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Thread-level reduction kernel
template <typename Element, int N>
__global__ void kernel_reduce(Element const *array_in, Element *result) {
/// Thread-level reduction operator
using Reduce = cutlass::reduction::thread::Reduce<
cutlass::plus<Element>,
cutlass::Array<Element, N>
>;
Reduce reduce;
auto ptr_in = reinterpret_cast<cutlass::Array<Element , N> const *>(array_in);
auto result_ptr = reinterpret_cast<cutlass::Array<Element , 1> *>(result);
auto in = *ptr_in;
result_ptr[0] = reduce(in);
}
/// Structure to compute the reduction
template <
/// Data type of elements
typename Element,
/// Number of elements
int N
>
struct Testbed_reduce_device {
using Layout = cutlass::layout::PackedVectorLayout;
//
// Data members
//
cutlass::HostTensor<Element, Layout> tensor_in;
cutlass::HostTensor<Element, Layout> reduced_tensor_computed;
cutlass::HostTensor<Element, Layout> reduced_tensor_reference;
//
// Methods
//
/// Allocates workspace in device memory
Testbed_reduce_device() {
tensor_in.reset(cutlass::make_Coord(N), true);
reduced_tensor_computed.reset(cutlass::make_Coord(1), true);
reduced_tensor_reference.reset(cutlass::make_Coord(1), true);
}
/// Runs the test
bool run() {
//
// initialize memory
//
cutlass::reference::host::TensorFill(
tensor_in.host_view(),
Element(1)
);
cutlass::reference::host::TensorFill(
reduced_tensor_computed.host_view(),
Element(0)
);
cutlass::reference::host::TensorFill(
reduced_tensor_reference.host_view(),
Element(N)
);
tensor_in.sync_device();
reduced_tensor_computed.sync_device();
reduced_tensor_reference.sync_device();
/// call the kernel
kernel_reduce<Element, N><<< dim3(1, 1), dim3(1, 1, 1) >>> (
tensor_in.device_data(),
reduced_tensor_computed.device_data()
);
// verify no errors
cudaError_t result = cudaDeviceSynchronize();
EXPECT_EQ(result, cudaSuccess) << "CUDA ERROR: " << cudaGetErrorString(result);
if (result != cudaSuccess) {
return false;
}
// Copy back results
reduced_tensor_computed.sync_host();
// Verify equivalence
bool passed = cutlass::reference::host::TensorEquals(
reduced_tensor_computed.host_view(),
reduced_tensor_reference.host_view()
);
EXPECT_TRUE(passed)
<< "Expected = " << reduced_tensor_reference.host_view() << "\n\n"
<< "Actual = " << reduced_tensor_computed.host_view() << "\n\n"
<< std::endl;
return passed;
}
};
} // namespace thread
} // namespace reduction
} // namespace test
| [
"noreply@github.com"
] | noreply@github.com |
04468b0897bed47ca2842c5e448afbf1293a2005 | 0f9dd1cbc3807d826b28865cbace66e42190f6a1 | /Framework/Settings/Util.cpp | 4e059633b1bd5cd624d414ed9bc10e696010ee89 | [] | no_license | Qazwar/badster-fix | 97db51dd119d0e0f4eba1e30cd1c89ccbecda513 | 54921920d6cf645da0fa9f45d82629a534323cd6 | refs/heads/master | 2021-05-04T20:09:24.542197 | 2017-09-23T12:34:03 | 2017-09-23T12:34:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,633 | cpp | #include "../SDK.h"
MsgFn U::PrintMessage = ( MsgFn )GetProcAddress( GetModuleHandleA( charenc( "tier0.dll" ) ), charenc( "Msg" ) );
SendClanTagFn U::SendClanTag;
ServerRankRevealAllFn U::ServerRankRevealAllEx;
InitKeyValuesFn U::InitKeyValuesEx;
LoadFromBufferFn U::LoadFromBufferEx;
IsReadyFn U::IsReady;
CL_FullUpdate_t U::CL_FullUpdate = NULL;
void U::SetupInterfaces()
{
I::Client = U::CaptureInterface<IBaseClientDll>( strenc( "client.dll" ), strenc( "VClient018" ) );
I::ClientMode = **( IClientModeShared*** ) ( ( *( DWORD** ) I::Client )[10] + 0x5 );
I::ClientEntList = U::CaptureInterface<IClientEntityList>( strenc( "client.dll" ), strenc( "VClientEntityList003" ) );
I::Cvar = U::CaptureInterface<ICVar>( strenc( "vstdlib.dll" ), strenc( "VEngineCvar007" ) );
I::Engine = U::CaptureInterface<IEngineClient>( strenc( "engine.dll" ), strenc( "VEngineClient014" ) );
I::EngineTrace = U::CaptureInterface<IEngineTrace>( strenc( "engine.dll" ), strenc( "EngineTraceClient004" ) );
I::InputSystem = U::CaptureInterface<IInputSystem>( strenc( "inputsystem.dll" ), strenc( "InputSystemVersion001" ) );
I::Globals = **( IGlobalVarsBase*** ) ( ( *( DWORD** ) I::Client )[0] + 0x1B);
I::Surface = U::CaptureInterface<ISurface>( strenc( "vguimatsurface.dll" ), strenc( "VGUI_Surface031" ) );
I::GameEvent = U::CaptureInterface<IGameEventManager2>(strenc("engine.dll"), strenc("GAMEEVENTSMANAGER002"));
I::VPanel = U::CaptureInterface<IVPanel>( strenc( "vgui2.dll" ), strenc( "VGUI_Panel009" ) );
I::RenderView = U::CaptureInterface<IVRenderView>( strenc( "engine.dll" ), strenc( "VEngineRenderView014" ) );
I::ModelRender = U::CaptureInterface<IVModelRender>( strenc( "engine.dll" ), strenc( "VEngineModel016" ) );
I::MaterialSystem = U::CaptureInterface<IMaterialSystem>( strenc( "materialsystem.dll" ), strenc( "VMaterialSystem080" ) );
I::ModelInfo = U::CaptureInterface<IVModelInfo>( strenc( "engine.dll" ), strenc( "VModelInfoClient004" ) );
I::GameMovement = U::CaptureInterface<IGameMovement>( strenc( "client.dll" ), strenc( "GameMovement001" ) );
I::Prediction = U::CaptureInterface<IPrediction>( strenc( "client.dll" ), strenc( "VClientPrediction001" ) );
I::Physprops = U::CaptureInterface<IPhysicsSurfaceProps>( strenc( "vphysics.dll" ), strenc( "VPhysicsSurfaceProps001" ) );
I::DebugOverlay = U::CaptureInterface<IVDebugOverlay>( strenc( "engine.dll" ), strenc( "VDebugOverlay004" ) );
I::StudioRender = U::CaptureInterface<IStudioRender>( strenc( "studiorender.dll" ), strenc( "VStudioRender026" ) );
I::MoveHelper = **(IMoveHelper***)(U::FindPattern("client.dll", "8B 0D ? ? ? ? 8B 46 08 68") + 2);
I::Ceffect = U::CaptureInterface<CEffects>(strenc("engine.dll"), strenc("VEngineEffects001"));
}
DWORD U::FindPattern( std::string moduleName, std::string pattern )
{
const char* pat = pattern.c_str();
DWORD firstMatch = 0;
DWORD rangeStart = ( DWORD )GetModuleHandleA( moduleName.c_str() );
MODULEINFO miModInfo; GetModuleInformation( GetCurrentProcess(), ( HMODULE )rangeStart, &miModInfo, sizeof( MODULEINFO ) );
DWORD rangeEnd = rangeStart + miModInfo.SizeOfImage;
for( DWORD pCur = rangeStart; pCur < rangeEnd; pCur++ )
{
if( !*pat )
return firstMatch;
if( *( PBYTE )pat == '\?' || *( BYTE* )pCur == getByte( pat ) )
{
if( !firstMatch )
firstMatch = pCur;
if( !pat[ 2 ] )
return firstMatch;
if( *( PWORD )pat == '\?\?' || *( PBYTE )pat != '\?' )
pat += 3;
else
pat += 2;
}
else
{
pat = pattern.c_str();
firstMatch = 0;
}
}
return NULL;
}
inline bool U::Compare(const uint8_t* data, const uint8_t* pattern, const char* mask) {
for (; *mask; ++mask, ++data, ++pattern)
if (*mask == 'x' && *data != *pattern)
return false;
return (*mask) == 0;
}
DWORD_PTR U::FindPattern3(std::string strModuleName, PBYTE pbPattern, std::string strMask, DWORD_PTR nCodeBase, DWORD_PTR nSizeOfCode)
{
BOOL bPatternDidMatch = FALSE;
HMODULE hModule = GetModuleHandleA(strModuleName.c_str());
if (!hModule)
return 0;
PIMAGE_DOS_HEADER pDsHeader = PIMAGE_DOS_HEADER(hModule);
PIMAGE_NT_HEADERS pPeHeader = PIMAGE_NT_HEADERS(LONG(hModule) + pDsHeader->e_lfanew);
PIMAGE_OPTIONAL_HEADER pOptionalHeader = &pPeHeader->OptionalHeader;
if (!nCodeBase)
nCodeBase = (ULONG)hModule + pOptionalHeader->BaseOfCode;
if (!nSizeOfCode)
nSizeOfCode = pOptionalHeader->SizeOfCode;
std::size_t nMaskSize = strMask.length();
if (!nCodeBase || !nSizeOfCode || !nMaskSize)
return 0;
for (DWORD_PTR i = nCodeBase; i <= nCodeBase + nSizeOfCode; i++)
{
for (size_t t = 0; t < nMaskSize; t++)
{
if (*((PBYTE)i + t) == pbPattern[t] || strMask.c_str()[t] == '?')
bPatternDidMatch = TRUE;
else
{
bPatternDidMatch = FALSE;
break;
}
}
if (bPatternDidMatch)
return i;
}
return 0;
}
uintptr_t U::FindPattern2(const char* module, const char* pattern_string, const char* mask) {
MODULEINFO module_info = {};
GetModuleInformation(GetCurrentProcess(), GetModuleHandleA(module), &module_info, sizeof MODULEINFO);
uintptr_t module_start = uintptr_t(module_info.lpBaseOfDll);
const uint8_t* pattern = reinterpret_cast<const uint8_t*>(pattern_string);
for (size_t i = 0; i < module_info.SizeOfImage; i++)
if (Compare(reinterpret_cast<uint8_t*>(module_start + i), pattern, mask))
return module_start + i;
return 0;
}
void U::StdReplaceStr(std::string& replaceIn, const std::string& replace, const std::string& replaceWith)
{
size_t const span = replace.size();
size_t const step = replaceWith.size();
size_t index = 0;
while (true)
{
index = replaceIn.find(replace, index);
if (index == std::string::npos)
break;
replaceIn.replace(index, span, replaceWith);
index += step;
}
}
CBaseEntity* U::GetLocalPlayer( )
{
return I::ClientEntList->GetClientEntity( I::Engine->GetLocalPlayer( ) );
}
CNetVarManager* U::NetVars = new CNetVarManager;
wchar_t* U::ConvertCharArrayToLPCWSTR( const char* charArray )
{
wchar_t* wString = new wchar_t[ 4096 ];
MultiByteToWideChar( CP_ACP, 0, charArray, -1, wString, 4096 );
return wString;
}
void U::ClipTraceToPlayers(const Vector& vecAbsStart, const Vector& vecAbsEnd, unsigned int mask, ITraceFilter* filter, trace_t* tr)
{
if ( !offsets.ClipTraceToPlayersFn )
return;
_asm
{
MOV EAX, filter
LEA ECX, tr
PUSH ECX
PUSH EAX
PUSH mask
LEA EDX, vecAbsEnd
LEA ECX, vecAbsStart
CALL offsets.ClipTraceToPlayersFn
ADD ESP, 0xC
}
}
void U::TraceLine( const Vector& vecAbsStart, const Vector& vecAbsEnd, unsigned int mask, CBaseEntity* ignore, trace_t* ptr )
{
Ray_t ray;
ray.Init( vecAbsStart, vecAbsEnd );
CTraceFilter filter;
filter.pSkip = ignore;
I::EngineTrace->TraceRay( ray, mask, &filter, ptr );
}
void U::ServerRankRevealAll()
{
static float fArray[ 3 ] = { 0.f, 0.f, 0.f };
U::ServerRankRevealAllEx = ( ServerRankRevealAllFn )( offsets.ServerRankRevealAllEx );
U::ServerRankRevealAllEx( fArray );
}
void U::InitKeyValues( KeyValues* pKeyValues, const char* name )
{
U::InitKeyValuesEx = ( InitKeyValuesFn )( offsets.InitKeyValuesEx );
U::InitKeyValuesEx( pKeyValues, name );
}
void U::LoadFromBuffer( KeyValues* pKeyValues, const char* resourceName, const char* pBuffer, void* pFileSystem, const char* pPathID, void* pfnEvaluateSymbolProc )
{
U::LoadFromBufferEx = ( LoadFromBufferFn )( offsets.LoadFromBufferEx );
U::LoadFromBufferEx( pKeyValues, resourceName, pBuffer, pFileSystem, pPathID, pfnEvaluateSymbolProc );
}
void U::SendPacket( byte toggle )
{
*( byte* )( offsets.SendPacket ) = toggle;
}
float U::RandomFloat( float min, float max )
{
assert( max > min );
float random = ( ( float )rand() ) / ( float )RAND_MAX;
float range = max - min;
return ( random*range ) + min;
}
void U::SetupHooks()
{
H::VPanel = new VTHook( ( DWORD** )I::VPanel );
H::ClientMode = new VTHook( ( DWORD** )I::ClientMode );
H::Client = new VTHook( ( DWORD** )I::Client );
H::ModelRender = new VTHook( ( DWORD** )I::ModelRender );
H::Surface = new VTHook( ( DWORD** )I::Surface );
H::GameEvent = new VTHook((DWORD**)I::GameEvent);
H::D3D9 = new VTHook( ( DWORD** )offsets.d3d9Device );
oPaintTraverse = ( PaintTraverseFn )H::VPanel->HookFunction( ( DWORD )Hooks::PaintTraverse, 41 );
oCreateMove = ( CreateMoveFn )H::ClientMode->HookFunction( ( DWORD )Hooks::CreateMove, 24 );
oFireEventClientSide = (FireEventClientSideFn)H::GameEvent->HookFunction((DWORD)Hooks::hkFireEventClientSide, 9);
oOverrideView = ( OverrideViewFn )H::ClientMode->HookFunction( ( DWORD )Hooks::OverrideView, 18 );
oFrameStageNotify = ( FrameStageNotifyFn )H::Client->HookFunction( ( DWORD )Hooks::FrameStageNotify, 36 );
oDrawModelExecute = ( DrawModelExecuteFn )H::ModelRender->HookFunction( ( DWORD )Hooks::DrawModelExecute, 21 );
oPlaySound = ( PlaySoundFn )H::Surface->HookFunction( ( DWORD )Hooks::PlaySound_CSGO, 82 );
oReset = ( ResetFn )H::D3D9->HookFunction( ( DWORD )Hooks::Reset, 16 );
oEndScene = ( EndSceneFn )H::D3D9->HookFunction( ( DWORD )Hooks::EndScene, 41 );
U::SendClanTag = (SendClanTagFn)U::FindPattern("engine.dll", "53 56 57 8B DA 8B F9 FF 15");
U::CL_FullUpdate = (CL_FullUpdate_t)U::FindPattern2("engine.dll", "\x56\x8B\x35\x00\x00\x00\x00\x83\xBE\x6C", "xxx????xxx");
}
void U::SetupOffsets()
{
U::NetVars->Initialize();
Offsets::GrabOffsets();
}
void U::SetupTextures()
{
visible_flat = I::MaterialSystem->CreateMaterial( true, false, false );
visible_tex = I::MaterialSystem->CreateMaterial( false, false, false );
hidden_flat = I::MaterialSystem->CreateMaterial( true, true, false );
hidden_tex = I::MaterialSystem->CreateMaterial( false, true, false );
}
void U::Setup()
{
U::SetupInterfaces();
U::SetupOffsets();
D::SetupFonts();
U::SetupTextures();
U::SetupHooks();
Config->Load();
if (lstrcmpA(I::Engine->GetProductVersionString(), CSGO_VERSION) != 0)
E::Misc->Panic();
}
long U::GetEpochTime()
{
auto duration = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
}
ImColor U::GetRainbowColor(float speed)
{
speed = 0.002f * speed;
long now = U::GetEpochTime();
float hue = (now % (int)(1.0f / speed)) * speed;
return ImColor::HSV(hue, 1.0f, 1.0f);
}
Color U::GetHealthColor(int hp)
{
return Color(
min(510 * (100 - hp) / 100, 255),
min(510 * hp / 100, 255),
25
);
}
Color U::GetHealthColor(CBaseEntity* player)
{
return Color(
min(510 * (100 - player->GetHealth()) / 100, 255),
min(510 * player->GetHealth() / 100, 255),
25
);
}
| [
"blastcraft@mail.ru"
] | blastcraft@mail.ru |
c325c46aad35abdc21d8a5f9ba71931af9200032 | f3902c121ee1cfbbd7ac41a549b3aac6bbddfa3f | /System/SystemConnector.cpp | 5b5ae7947f6fc5c5c6e70196fd56ae646968b904 | [] | no_license | syntelos/cc-tmtc-console | 896f2c891c23db7e8ea622b3757aada6cc4a47cf | 9e87293690efe22b02e6d2b8818df1d1b0f694e6 | refs/heads/master | 2021-03-27T14:33:38.809696 | 2014-01-28T15:52:52 | 2014-01-28T15:52:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,983 | cpp | /*
* Copyright 2014 John Pritchard, Syntelos. All rights reserved.
*/
#include <QDebug>
#include "SystemConnector.h"
const char *SystemConnector::NamePrefix = "SystemConnector(";
SystemConnector::SystemConnector()
: senderObject(0), receiverObject(0), connected(false)
{
}
SystemConnector::SystemConnector(const SystemConnector& sc)
: senderObject(sc.senderObject), receiverObject(sc.receiverObject),
senderId(sc.senderId), receiverId(sc.receiverId),
signal(sc.signal), slot(sc.slot),
connected(sc.connected)
{
}
SystemConnector::SystemConnector(const QByteArray& ba)
: senderObject(0), receiverObject(0), connected(false)
{
/*
* Very fast parse for ASCII characters
*
* <GS><RS>
* <FS><N><senderId>{N}
* <FS><N><receiverId>{N}
* <FS><N><signal>{N}
* <FS><N><slot>{N}
*/
const char* src = ba.constData();
const int srclen = ba.length();
if (10 <= srclen){
int ofs = 0, flen;
if (GS == src[ofs++] && RS == src[ofs++]){
if (FS == src[ofs++]){
flen = src[ofs++];
if (0 < flen){
senderId.set(&src[ofs],flen);
ofs += flen;
}
if (FS == src[ofs++]){
flen = src[ofs++];
if (0 < flen){
receiverId.set(&src[ofs],flen);
ofs += flen;
}
if (FS == src[ofs++]){
flen = src[ofs++];
if (0 < flen){
signal.set(&src[ofs],flen);
ofs += flen;
}
if (FS == src[ofs++]){
flen = src[ofs++];
if (0 < flen){
slot.set(&src[ofs],flen);
//ofs += flen;
}
}
}
}
}
}
}
}
SystemConnector::SystemConnector(const QString& signal, const QString& slot)
: senderObject(0), receiverObject(0),
signal(signal), slot(slot),
connected(false)
{
}
SystemConnector::SystemConnector(const QString& id, QObject* sender)
: senderObject(sender), receiverObject(0), senderId(id),
connected(false)
{
}
SystemConnector::SystemConnector(const QString& id, QObject* sender, const QString& signal)
: senderObject(sender), receiverObject(0), senderId(id),
signal(signal), slot(slot),
connected(false)
{
}
SystemConnector::SystemConnector(const QString& id, QObject* sender, const QString& signal, const QString& slot)
: senderObject(sender), receiverObject(0), senderId(id),
signal(signal), slot(slot),
connected(false)
{
if (isValidInput()){
connected = sender->property(name()).isValid();
}
}
SystemConnector::SystemConnector(const QString& senderId, QObject* sender,
const QString& signal, const QString& slot,
const QString& receiverId, QObject* receiver)
: senderObject(sender), receiverObject(receiver),
senderId(senderId), receiverId(receiverId),
signal(signal), slot(slot),
connected(false)
{
if (isValidInput()){
connected = sender->property(name()).isValid();
}
}
SystemConnector::~SystemConnector()
{
senderObject = 0;
receiverObject = 0;
}
bool SystemConnector::isConnected() const {
return connected;
}
bool SystemConnector::isValidInput() const {
return (senderObject && receiverObject &&
senderId.isNotInert() && receiverId.isNotInert() &&
signal.isNotInert() && slot.isNotInert());
}
bool SystemConnector::isValidInputSender() const {
return (senderObject && senderId.isNotInert() &&
signal.isNotInert() && slot.isNotInert());
}
bool SystemConnector::isValidOutput() const {
return (senderId.isNotInert() && receiverId.isNotInert() &&
signal.isNotInert() && slot.isNotInert());
}
SystemConnector& SystemConnector::sender(const QString& id, QObject* sender){
this->senderId.set(id);
nbuf.clear();
this->senderObject = sender;
if (isValidInput())
connected = sender->property(name()).isValid();
else
connected = false;
return *this;
}
SystemConnector& SystemConnector::receiver(const QString& id, QObject* receiver){
this->receiverId.set(id);
nbuf.clear();
this->receiverObject = receiver;
if (isValidInput())
connected = senderObject->property(name()).isValid();
else
connected = false;
return *this;
}
bool SystemConnector::connect(){
if (connected){
return true;
}
else if (isValidInput())
{
const char* signal = this->signal.signal(senderObject->metaObject());
const char* slot = this->slot.slot(receiverObject->metaObject());
if (signal && slot){
/*
* Connect
*/
if (QObject::connect(senderObject,signal,receiverObject,slot)){
connected = true;
/*
* Catalog
*
* The name and value arguments are copied into the
* sender QObject dynamic properties container.
*/
senderObject->setProperty(name(),value());
return true;
}
else {
return false;
}
}
else {
qDebug().nospace() << name() << ".connect failed to dereference signal or slot";
}
}
else {
qDebug().nospace() << name() << ".connect missing operands";
}
return false;
}
const SystemScriptSymbol& SystemConnector::getSenderId() const {
return senderId;
}
const SystemScriptSymbol& SystemConnector::getReceiverId() const {
return receiverId;
}
const SystemScriptSymbol& SystemConnector::getSignal() const {
return signal;
}
SystemConnector& SystemConnector::setSignal(const QString& signal){
this->signal.set(signal);
nbuf.clear();
return *this;
}
const SystemScriptSymbol& SystemConnector::getSlot() const {
return slot;
}
SystemConnector& SystemConnector::setSlot(const QString& slot){
this->slot.set(slot);
nbuf.clear();
return *this;
}
const char* SystemConnector::name() const {
if (0 == nbuf.length()){
nbuf += SystemConnector::NamePrefix;
nbuf += senderId;
nbuf += ", ";
nbuf += signal;
nbuf += ", ";
nbuf += receiverId;
nbuf += ", ";
nbuf += slot;
nbuf += ')';
}
return nbuf.constData();
}
const QVariant SystemConnector::value() const {
/*
* Generate
*/
QByteArray vbuf;
vbuf += GS;
vbuf += RS;
int flen;
unsigned char clen;
flen = senderId.length();
if (0 < flen && 255 > flen){
clen = flen;
vbuf += FS;
vbuf += clen;
vbuf += senderId;
}
else {
vbuf += FS;
vbuf += (char)0;
}
flen = receiverId.length();
if (0 < flen && 255 > flen){
clen = flen;
vbuf += FS;
vbuf += clen;
vbuf += receiverId;
}
else {
vbuf += FS;
vbuf += (char)0;
}
flen = signal.length();
if (0 < flen && 255 > flen){
clen = flen;
vbuf += FS;
vbuf += clen;
vbuf += signal;
}
else {
vbuf += FS;
vbuf += (char)0;
}
flen = slot.length();
if (0 < flen && 255 > flen){
clen = flen;
vbuf += FS;
vbuf += clen;
vbuf += slot;
}
else {
vbuf += FS;
vbuf += (char)0;
}
/*
*/
return vbuf;
}
QString SystemConnector::toString() const {
return name();
}
| [
"jdp@syntelos.org"
] | jdp@syntelos.org |
0c0ab3df9c1b93f22ef9d3d33d1f8162eebdcaeb | 3538f47e6662e6bc0e28e18a1c3a7f4d10c718b4 | /arena-master/src/qt/utilitydialog.cpp | 7e4e5cc3bd9ef58513f1394b3b928d666b17a9a7 | [
"MIT"
] | permissive | ArenaCoinDev/Arena | e95669d31d35121d13acf8767005997782b0babd | a9b7ed7eb197ddc62d344bce489179f555a6cb05 | refs/heads/master | 2020-03-28T19:28:46.361536 | 2018-12-09T06:09:38 | 2018-12-09T06:09:38 | 148,980,735 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,656 | cpp | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The Proton Core developers
// Copyright (c) 2018 The Arena Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "utilitydialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "intro.h"
#include "paymentrequestplus.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QTextTable>
#include <QTextCursor>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, HelpMode helpMode) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
QString version = tr("Arena Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
if (helpMode == about)
{
setWindowTitle(tr("About Arena Core"));
/// HTML-format the license message from the core
QString licenseInfo = QString::fromStdString(LicenseInfo());
QString licenseInfoHTML = licenseInfo;
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n\n", "<br><br>");
ui->aboutMessage->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + licenseInfo;
ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
ui->aboutMessage->setWordWrap(true);
ui->helpMessage->setVisible(false);
} else if (helpMode == cmdline) {
setWindowTitle(tr("Command-line options"));
QString header = tr("Usage:") + "\n" +
" arena-qt [" + tr("command-line options") + "] " + "\n";
QTextCursor cursor(ui->helpMessage->document());
cursor.insertText(version);
cursor.insertBlock();
cursor.insertText(header);
cursor.insertBlock();
std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
const bool showDebug = GetBoolArg("-help-debug", false);
strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
if (showDebug) {
strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS));
}
strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR));
strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString());
strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString());
strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString());
strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN));
strUsage += HelpMessageOpt("-resetguisettings", tr("Reset all settings changes made over the GUI").toStdString());
if (showDebug) {
strUsage += HelpMessageOpt("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM));
}
QString coreOptions = QString::fromStdString(strUsage);
text = version + "\n" + header + "\n" + coreOptions;
QTextTableFormat tf;
tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
tf.setCellPadding(2);
QVector<QTextLength> widths;
widths << QTextLength(QTextLength::PercentageLength, 35);
widths << QTextLength(QTextLength::PercentageLength, 65);
tf.setColumnWidthConstraints(widths);
QTextCharFormat bold;
bold.setFontWeight(QFont::Bold);
Q_FOREACH (const QString &line, coreOptions.split("\n")) {
if (line.startsWith(" -"))
{
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::PreviousCell);
cursor.movePosition(QTextCursor::NextRow);
cursor.insertText(line.trimmed());
cursor.movePosition(QTextCursor::NextCell);
} else if (line.startsWith(" ")) {
cursor.insertText(line.trimmed()+' ');
} else if (line.size() > 0) {
//Title of a group
if (cursor.currentTable())
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::Down);
cursor.insertText(line.trimmed(), bold);
cursor.insertTable(1, 2, tf);
}
}
ui->helpMessage->moveCursor(QTextCursor::Start);
ui->scrollArea->setVisible(false);
ui->aboutLogo->setVisible(false);
} else if (helpMode == pshelp) {
setWindowTitle(tr("PrivateSend information"));
ui->aboutMessage->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
ui->aboutMessage->setText(tr("\
<h3>PrivateSend Basics</h3> \
PrivateSend gives you true financial privacy by obscuring the origins of your funds. \
All the Arena in your wallet is comprised of different \"inputs\" which you can think of as separate, discrete coins.<br> \
PrivateSend uses an arenative process to mix your inputs with the inputs of two other people, without having your coins ever leave your wallet. \
You retain control of your money at all times..<hr> \
<b>The PrivateSend process works like this:</b>\
<ol type=\"1\"> \
<li>PrivateSend begins by breaking your transaction inputs down into standard denominations. \
These denominations are 0.01 ARENA, 0.1 ARENA, 1 ARENA and 10 ARENA -- sort of like the paper money you use every day.</li> \
<li>Your wallet then sends requests to specially configured software nodes on the network, called \"masternodes.\" \
These masternodes are informed then that you are interested in mixing a certain denomination. \
No identifiable information is sent to the masternodes, so they never know \"who\" you are.</li> \
<li>When two other people send similar messages, indicating that they wish to mix the same denomination, a mixing session begins. \
The masternode mixes up the inputs and instructs all three users' wallets to pay the now-transformed input back to themselves. \
Your wallet pays that denomination directly to itself, but in a different address (called a change address).</li> \
<li>In order to fully obscure your funds, your wallet must repeat this process a number of times with each denomination. \
Each time the process is completed, it's called a \"round.\" Each round of PrivateSend makes it exponentially more difficult to determine where your funds originated.</li> \
<li>This mixing process happens in the background without any intervention on your part. When you wish to make a transaction, \
your funds will already be anonymized. No additional waiting is required.</li> \
</ol> <hr>\
<b>IMPORTANT:</b> Your wallet only contains 1000 of these \"change addresses.\" Every time a mixing event happens, up to 9 of your addresses are used up. \
This means those 1000 addresses last for about 100 mixing events. When 900 of them are used, your wallet must create more addresses. \
It can only do this, however, if you have automatic backups enabled.<br> \
Consequently, users who have backups disabled will also have PrivateSend disabled. <hr>\
For more info see <a href=\"https://arenacoin.atlassian.net/wiki/display/DOC/PrivateSend\">https://arenacoin.atlassian.net/wiki/display/DOC/PrivateSend</a> \
"));
ui->aboutMessage->setWordWrap(true);
ui->helpMessage->setVisible(false);
ui->aboutLogo->setVisible(false);
}
// Theme dependent Gfx in About popup
QString helpMessageGfx = ":/images/" + GUIUtil::getThemeName() + "/about";
QPixmap pixmap = QPixmap(helpMessageGfx);
ui->aboutLogo->setPixmap(pixmap);
}
HelpMessageDialog::~HelpMessageDialog()
{
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
fprintf(stdout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f):
QWidget(parent, f)
{
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("Arena Core is shutting down...") + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
void ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new ShutdownWindow();
// We don't hold a direct pointer to the shutdown window after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
shutdownWindow->setAttribute(Qt::WA_DeleteOnClose);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
void ShutdownWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
}
| [
"mmoaeria@gmail.com"
] | mmoaeria@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.