blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
ffc562d8f073fca00de613754328b46fcb9b1e4c | C++ | killiad/chrono-star-coupling | /Terrain/TerrainCreator.h | UTF-8 | 702 | 2.640625 | 3 | [] | no_license | #ifndef TERRAIN_CREATOR_H
#define TERRAIN_CREATOR_H
#include <memory>
#include "chrono_vehicle/tracked_vehicle/vehicle/TrackedVehicle.h"
#include "chrono_vehicle/ChTerrain.h"
#include "chrono_vehicle/ChVehicleModelData.h"
namespace chrono{
namespace vehicle{
class TerrainCreator{
public:
TerrainCreator(std::string filename, std::shared_ptr<TrackedVehicle> veh) : file(filename), vehicle(veh) {}
virtual std::shared_ptr<ChTerrain> GetTerrain() = 0;
inline std::string GetTerrainFile() { return file; }
protected:
std::shared_ptr<TrackedVehicle> vehicle;
std::string file;
};
}//end namespace vehicle
}//end namespace chrono
#endif
| true |
015501501e0735d6869fb1397329e45f5fa92b2c | C++ | sudipta02/DSA | /Assignment_2_classplus.cpp | UTF-8 | 1,427 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool visited[100005];
vector<int> a[100005];
unordered_map<int, int> map_ans;
void dfs(int s, int &x, int count){
visited[s] = 1;
map_ans[s]++;
int i, j, k = a[s].size();
count++;
for(int i = 0; i < k; i++){
j = a[s][i];
if(!visited[j] && count <= x){
dfs(j, x, count);
}
}
}
int main(){
int n, h, x;
cin>>n;
cin>>h;
cin>>x;
//Input h integers below
vector<int> hotspots(h);
for(int i = 0; i < h; i++){
cin>>hotspots[i];
}
//Input n-1 lines denoting roads between city u and v
vector<vector<int>> roads(n-1, vector<int>(2));
for(int i = 0; i < n-1; i++){
for(int j = 0; j < 2; j++){
cin>>roads[i][j];
}
}
//Logic starts here
for(int i = 0; i <= n; i++){
a[i].clear();
visited[i] = 0;
}
for(int i = 0; i < n-1; i++){
a[roads[i][0]].push_back(roads[i][1]);
a[roads[i][1]].push_back(roads[i][0]);
}
map_ans.clear();
for(int i = 0; i < h; i++){
memset(visited, 0, sizeof(visited));
dfs(hotspots[i], x, 0);
}
int solution = 0;
for(auto itr = map_ans.begin(); itr != map_ans.end(); itr++){
if(itr->second == h){
solution++;
}
}
cout<<solution;
return 0;
} | true |
a78ac62561c825560042b7f4871fa6a613770dfc | C++ | geoo993/ComputerGraphicsWithOpenGL | /src/window/GameWindow.cpp | UTF-8 | 32,469 | 2.671875 | 3 | [] | no_license | #include "GameWindow.h"
#define SIMPLE_OPENGL_CLASS_NAME "simple_openGL_class_name"
CGameWindow::CGameWindow(const CGameWindow &other) {
this -> m_appName = other.m_appName;
this -> m_width = other.m_width;
this -> m_height = other.m_height;
this -> m_fullscreen = other.m_fullscreen;
}
CGameWindow &CGameWindow::operator=(const CGameWindow &other){
this -> m_appName = other.m_appName;
this -> m_width = other.m_width;
this -> m_height = other.m_height;
this -> m_fullscreen = other.m_fullscreen;
return *this;
}
CGameWindow::CGameWindow() {
this -> m_appName = "";
this -> m_width = 0;
this -> m_height = 0;
this -> m_fullscreen = false;
}
void CGameWindow::Set(const std::string &appName, const int &w, const int &h, const bool &fullscreen){
m_appName = appName;
m_width = w;
m_height = h;
m_fullscreen = fullscreen;
}
// Initialise GLEW and create the real game window
void CGameWindow::CreateWindow(const std::string &appName,
const int &w,
const int &h,
const bool &fullscreen)
{
Set(appName, w, h, fullscreen);
if(!InitGLFW()){
return;
}
CreateGameWindow(m_appName);
return;
}
// Create a dummy window, intialise GLEW, and then delete the dummy window
bool CGameWindow::InitGLFW()
{
static bool bGlewInitialized = false;
if(bGlewInitialized) {
return true;
}
// start GL context and O/S window using the GLFW helper library
if (!glfwInit()) {
fprintf(stderr, "ERROR: could not start GLFW3\n");
exit(EXIT_FAILURE);
return false;
}
GLFWwindow* fakeWindow = glfwCreateWindow(m_width, m_height, m_appName.c_str(), nullptr, nullptr); // Windowed
if (fakeWindow == nullptr) {
fprintf(stderr, "ERROR: could not open window with GLFW3\n");
glfwTerminate();
return false;
}
glfwMakeContextCurrent(fakeWindow);
bool bResult = true;
if(!bGlewInitialized)
{
if(glewInit() != GLEW_OK){
bResult = false;
throw std::runtime_error("Couldn't initialize GLEW!");
}
bGlewInitialized = true;
}
glfwMakeContextCurrent(nullptr);
glfwDestroyWindow(fakeWindow);
glfwTerminate();
return bResult;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
// Create the game window
void CGameWindow::CreateGameWindow(const std::string &appName)
{
// start GL context and O/S window using the GLFW helper library
if (!glfwInit()) {
fprintf(stderr, "ERROR: could not start GLFW3\n");
exit(EXIT_FAILURE);
return;
}
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_SAMPLES, 4); // Multi Sample Anti-Aliasing for smooth edges.
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
glfwWindowHint(GLFW_DEPTH_BITS, 24);
//glfwWindowHint(GLFW_STENCIL_BITS, 0);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//We don't want the old OpenGL and want the core profile
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
if (m_fullscreen){
m_window = glfwCreateWindow(m_width, m_height, appName.c_str(), glfwGetPrimaryMonitor(), nullptr);//// Windowed
}else{
m_window = glfwCreateWindow(m_width, m_height, appName.c_str(), nullptr, nullptr); // Fullscreen
}
glfwGetWindowSize(m_window, &m_width, &m_height);
if (m_window == nullptr) {
fprintf(stderr, "ERROR: could not open window with GLFW3\n");
glfwTerminate();
return ;
}
glfwMakeContextCurrent(m_window);
glfwSetFramebufferSizeCallback(m_window, framebuffer_size_callback);
glfwSwapInterval(1); ////<-- force interval (not guaranteed to work with all graphics drivers)
//start GLEW extension handler
if(InitOpenGL()){
SetCursorVisible(false);
CenterTheWindow();
return;
}
return;
}
void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
// Initialise OpenGL, including the pixel format descriptor and the OpenGL version
bool CGameWindow::InitOpenGL()
{
bool bError = false;
// start GLEW extension handler
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK){
throw std::runtime_error("glewInit failed");
bError = true;
}
if(!GLEW_VERSION_3_2){
throw std::runtime_error("OpenGL 3.2 API is not available.");
bError = true;
}
// get version info
const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer as a string
const GLubyte* version = glGetString(GL_VERSION); // "graphics griver version as a string
const GLubyte* vendor = glGetString(GL_VENDOR); // vendor as a string
const GLubyte* shaderLanguage = glGetString(GL_SHADING_LANGUAGE_VERSION); // shader lang as a string
// print out some info about the graphics drivers
std::cout << "OpenGL or Graphics Driver version supported: " << version << std::endl;
std::cout << "GLSL version: " << shaderLanguage << std::endl;
std::cout << "Renderer: " << renderer << std::endl;
std::cout << "Vendor: " << vendor << std::endl;
//3. Check for specific functionality
if (GLEW_ARB_vertex_array_object){
printf("genVertexArrays supported\n");
}
if (GLEW_APPLE_vertex_array_object){
printf("genVertexArrayAPPLE supported\n");
}
if(bError)
{
glfwSetErrorCallback(error_callback);
return bError;
}
GLint MaxTextureUnits;
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &MaxTextureUnits);
std::cout << "There are "<< MaxTextureUnits << " texture units supported by GPU. " << std::endl;
return bError;
}
void CGameWindow::SetInputs(const GLFWcursorenterfun &cbfunEnter,
const GLFWcursorposfun &cbfunMouseMove,
const GLFWmousebuttonfun &cbfunMouseClick,
const GLFWscrollfun &cbfunMouseScroll,
const GLFWkeyfun &cbfunKey){
//glfwSetWindowSizeCallback(m_window, ReshapeWindow);
//glfwSetWindowShouldClose(m_window, GLUS_TRUE);
glfwSetCursorEnterCallback(m_window, cbfunEnter);
glfwSetCursorPosCallback(m_window, cbfunMouseMove);
glfwSetMouseButtonCallback(m_window, cbfunMouseClick);
glfwSetScrollCallback(m_window, cbfunMouseScroll);
glfwSetKeyCallback(m_window, cbfunKey);
// https://www.youtube.com/watch?v=L2aiuDDFNIk
// what sticky keys is doing is it makes sure that the keys or keyboard events are polled, this means glfwPollEvents will handle these events
glfwSetInputMode(m_window, GLFW_STICKY_KEYS, 1);
SetCursorVisible(true);
}
void CGameWindow::SetCursorVisible( const bool &isVisible )
{
if( m_window == nullptr )
return;
// https://www.youtube.com/watch?v=EE5cS8EMT78
// tell GLFW to capture our mouse
if( isVisible ){
glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
//assert(glfwGetInputMode(m_window, GLFW_CURSOR) == GLFW_CURSOR_NORMAL);
}else{
glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
//assert(glfwGetInputMode(m_window, GLFW_CURSOR) == GLFW_CURSOR_HIDDEN);
}
//glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
//glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // to remove cursor
}
//Check whether window should close
bool CGameWindow::ShouldClose(){
return glfwWindowShouldClose(m_window);
}
// https://stackoverflow.com/questions/11335301/glfw-get-screen-height-width
void CGameWindow::CenterTheWindow(){
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwSetWindowPos(m_window, (mode->width - m_width) / 2, (mode->height - m_height) / 2);
}
//Get the Current framebuffer Size in pixels and Set the Viewport to it
void CGameWindow::SetViewport(){
//glfwGetWindowSize(window, &windowWidth, &windowHeight);
GLint width, height;
// returns the framebuffer size, not the window size.
glfwGetFramebufferSize(m_window, &width, &height);
glViewport( 0, 0, width, height);
}
//Get the Current framebuffer Size in pixels and Set the Viewport to it
void CGameWindow::SetViewport(const int & width, const int & height){
glViewport( 0, 0, width, height);
}
void CGameWindow::PreRendering(){
// configure global opengl states
glClearColor(0.1f, 0.1f, 0.1f, 1.0f); // Set background color to black
/* // https://www.khronos.org/opengl/wiki/Multisampling
Multisampling, also known as multisample antialiasing (MSAA), is one method for achieving full-screen antialiasing (FSAA). With multisampling, each pixel at the edge of a polygon is sampled multiple times. For each sample-pass, a slight offset is applied to all screen coordinates.
*/
/* Multisample Anti-Aliasing https://learnopengl.com/#!Advanced-OpenGL/Anti-Aliasing
There are quite a few techniques out there called anti-aliasing techniques that fight exactly this aliasing (jagged edges) behavior to produce more smooth edges.
At first we had a technique called super sample anti-aliasing (SSAA) that temporarily used a much higher resolution to render the scene in (super sampling) and when the visual output is updated in the framebuffer, the resolution was downsampled back to the normal resolution. This extra resolution was used to prevent these jagged edges. While it did provide us with a solution to the aliasing problem, it came with a major performance drawback since we had to draw a lot more fragments than usual. This technique therefore only had a short glory moment.
This technique did gave birth to a more modern technique called multisample anti-aliasing or MSAA that borrows from the concepts behind SSAA while implementing a much more efficient approach.
If we want to use MSAA in OpenGL we need to use a color buffer that is able to store more than one color value per pixel (since multisampling requires us to store a color per sample point). We thus need a new type of buffer that can store a given amount of multisamples and this is called a multisample buffer.
Most windowing systems are able to provide us a multisample buffer instead of a default color buffer. GLFW also gives us this functionality and all we need to do is hint GLFW that we'd like to use a multisample buffer with N samples instead of a normal color buffer by calling glfwWindowHint before creating the window:
glfwWindowHint(GLFW_SAMPLES, 4);
When we now call glfwCreateWindow the rendering window is created, this time with a color buffer containing 4 subsamples per screen coordinate. GLFW also automatically creates a depth and stencil buffer with 4 subsamples per pixel. This does mean that the size of all the buffers is increased by 4.
Now that we asked GLFW for multisampled buffers we need to enable multisampling by calling glEnable and enabling GL_MULTISAMPLE. On most OpenGL drivers, multisampling is enabled by default so this call is then a bit redundant, but it's usually a good idea to enable it anyways. This way all OpenGL implementations have multisampling enabled.
glEnable(GL_MULTISAMPLE);
Once the default framebuffer has multisampled buffer attachments, all we need to do to enable multisampling is just call glEnable and we're done. Because the actual multisampling algorithms are implemented in the rasterizer in your OpenGL drivers there's not much else we need to do.
*/
glEnable(GL_MULTISAMPLE);
glEnable(GL_TEXTURE_2D);
// https://www.ntu.edu.sg/home/ehchua/programming/opengl/CG_Examples.html
glClearDepth(1.0f); // Set background depth to farthest
glShadeModel(GL_SMOOTH); // Enable smooth shading
//https://learnopengl.com/#!Advanced-OpenGL/Depth-testing
// Depth testing is done in screen space after the fragment shader has run (and after stencil testing has run). The screen space coordinates relate directly to the viewport defined by OpenGL's glViewport function and can be accessed via GLSL's built-in gl_FragCoord variable in the fragment shader. The x and y components of gl_FragCoord represent the fragment's screen-space coordinates (with (0,0) being the bottom-left corner). The gl_FragCoord also contains a z-component which contains the actual depth value of the fragment. This z value is the value that is compared to the depth buffer's content.
// Depth testing is disabled by default so to enable depth testing we need to enable it with the GL_DEPTH_TEST option:
glEnable(GL_DEPTH_TEST); // enable depth-testing, only draw fragments with a depth value of 1.
//GL_DEPTH_TEST is to be enabled to avoid ugly artifacts that depend on the angle of view and drawing order (otherwise ie. if back of the cube is drawn last, if will appear "above" the front of the cube).
//So yes, both GL_CULL_FACE and GL_DEPTH_TEST should be enabled.
//OpenGL allows us to disable writing to the depth buffer by setting its depth mask to GL_FALSE: glDepthMask(GL_FALSE).
// Note that this only has effect if depth testing is enabled.
glDepthMask(GL_FALSE);
//OpenGL allows us to modify the comparison operators it uses for the depth test. This allows us to control when OpenGL should pass or discard fragments and when to update the depth buffer. We can set the comparison operator (or depth function) by calling glDepthFunc:
/*
glEnable(GL_DEPTH_CLAMP);
// When Using GL_DEPTH_CLAMP change the depth test from the default GL_LESS to GL_LEQUAL. This is cause when opengl clamps a poligon, it puts the poligon exactly in the far plane, so z=1 (ranging from -1 to 1). And the depth of the pixels of the polygon is 1 (from 0 to 1). And when you clear the depth buffer you fill it with 1. So the depth func must be GL_LEQUAL.
glDepthFunc(GL_LEQUAL);
*/
glDepthFunc(GL_LESS); // depth-testing interprets a smaller value as "closer"
//The function accepts several comparison operators that are listed in the table below:
/*
Function Description
GL_ALWAYS The depth test always passes.
GL_NEVER The depth test never passes.
GL_LESS Passes if the fragment's depth value is less than the stored depth value.
GL_EQUAL Passes if the fragment's depth value is equal to the stored depth value.
GL_LEQUAL Passes if the fragment's depth value is less than or equal to the stored depth value.
GL_GREATER Passes if the fragment's depth value is greater than the stored depth value.
GL_NOTEQUAL Passes if the fragment's depth value is not equal to the stored depth value.
GL_GEQUAL Passes if the fragment's depth value is greater than or equal to the stored depth value.
*/
// OpenGL allows us to disable writing to the depth buffer by setting its depth mask to GL_FALSE:
// glDepthMask(GL_FALSE);
/* Why we have znear and zfar
The depth buffer contains depth values between 0.0 and 1.0 and it compares its content with z-value of all the objects in the scene as seen from the viewer. These z-values in view space can be any value between the projection frustum's near and far value. We thus need some way to transform these view-space z-values to the range of [0,1] and one way is to linearly transform them to the [0,1] range.
*/
/*
Once the fragment shader has processed the fragment a so called stencil test is executed that, just like the depth test, has the possibility of discarding fragments
Then the remaining fragments get passed to the depth test that could possibly discard even more fragments. The stencil test is based on the content of yet another buffer called the stencil buffer that we're allowed to update during rendering to achieve interesting effects.
When using stencil buffers you can get as crazy as you like, but the general outline is usually as follows:
- Enable writing to the stencil buffer.
- Render objects, updating the content of the stencil buffer.
- Disable writing to the stencil buffer.
- Render (other) objects, this time discarding certain fragments based on the content of the stencil buffer.
*/
// https://learnopengl.com/#!Advanced-OpenGL/Stencil-testing
// You can enable stencil testing by enabling GL_STENCIL_TEST. From that point on, all rendering calls will influence the stencil buffer in one way or another
glEnable(GL_STENCIL_TEST);
/*
Also, just like the depth testing's glDepthMask function, there is an equivalent function for the stencil buffer. The function glStencilMask allows us to set a bitmask that is ANDed with the stencil value about to be written to the buffer. By default this is set to a bitmask of all 1s unaffecting the output, but if we were to set this to 0x00 all the stencil values written to the buffer end up as 0s. This is equivalent to depth testing's glDepthMask(GL_FALSE):
*/
// glStencilMask(0xFF); // each bit is written to the stencil buffer as is
// glStencilMask(0x00); // each bit ends up as 0 in the stencil buffer (disabling writes)
// Most of the cases you'll just be writing 0x00 or 0xFF as the stencil mask, but it's good to know there are options to set custom bit-masks.
// There are a total of two functions we can use to configure stencil testing: glStencilFunc and glStencilOp.
/*
The glStencilFunc(GLenum func, GLint ref, GLuint mask) has three parameters:
- func: sets the stencil test function. This test function is applied to the stored stencil value and the glStencilFunc's ref value. Possible options are: GL_NEVER, GL_LESS, GL_LEQUAL, GL_GREATER, GL_GEQUAL, GL_EQUAL, GL_NOTEQUAL and GL_ALWAYS. The semantic meaning of these is similar to the depth buffer's functions.
- ref: specifies the reference value for the stencil test. The stencil buffer's content is compared to this value.
- mask: specifies a mask that is ANDed with both the reference value and the stored stencil value before the test compares them. Initially set to all 1s.
glStencilFunc(GL_EQUAL, 1, 0xFF);
*/
glStencilFunc(GL_NOTEQUAL, 1, 0xFF); // uncomment this for outline
/*
The glStencilOp(GLenum sfail, GLenum dpfail, GLenum dppass) contains three options of which we can specify for each option what action to take:
- sfail: action to take if the stencil test fails.
- dpfail: action to take if the stencil test passes, but the depth test fails.
- dppass: action to take if both the stencil and the depth test pass.
Then for each of the options you can take any of the following actions:
Action Description
GL_KEEP The currently stored stencil value is kept.
GL_ZERO The stencil value is set to 0.
GL_REPLACE The stencil value is replaced with the reference value set with glStencilFunc.
GL_INCR The stencil value is increased by 1 if it is lower than the maximum value.
GL_INCR_WRAP Same as GL_INCR, but wraps it back to 0 as soon as the maximum value is exceeded.
GL_DECR The stencil value is decreased by 1 if it is higher than the minimum value.
GL_DECR_WRAP Same as GL_DECR, but wraps it to the maximum value if it ends up lower than 0.
GL_INVERT Bitwise inverts the current stencil buffer value.
*/
// By default the glStencilOp function is set to (GL_KEEP, GL_KEEP, GL_KEEP) so whatever the outcome of any of the tests, the stencil buffer keeps its values. The default behavior does not update the stencil buffer, so if you want to write to the stencil buffer you need to specify at least one different action for any of the options.
// glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// If any of the tests fail we do nothing, we simply keep the currently stored value that is in the stencil buffer. If both the stencil test and the depth test succeed however, we want to replace the stored stencil value with the reference value set via glStencilFunc which we later set to 1.
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
/* Object Outlining technique
Object outlining does exactly what it says it does. For each object (or only one) we're creating a small colored border around the (combined) objects. This is a particular useful effect when you want to select units in a strategy game for example and need to show the user which of the units were selected. The routine for outlining your objects is as follows:
1- Set the stencil func to GL_ALWAYS before drawing the (to be outlined) objects, updating the stencil buffer with 1s wherever the objects' fragments are rendered.
2- Render the objects.
3- Disable stencil writing and depth testing.
4- Scale each of the objects by a small amount.
5- Use a different fragment shader that outputs a single (border) color.
6- Draw the objects again, but only if their fragments' stencil values are not equal to 1.
7- Enable stencil writing and depth testing again.
*/
// https://learnopengl.com/#!Advanced-OpenGL/Blending
//If you want blending to occur after the texture has been applied, then use the OpenGL blending feature. Use this: glEnable (GL_BLEND);
// To render images with different levels of transparency we have to enable blending. Like most of OpenGL's functionality we can enable blending by enabling GL_BLEND:
glEnable (GL_BLEND);
/*
Blending in OpenGL is done with the following equation:
C¯result = C¯source ∗ Fsource + C¯destination ∗ Fdestination
C¯source: the source color vector. This is the color vector that originates from the texture.
C¯destination: the destination color vector. This is the color vector that is currently stored in the color buffer.
Fsource: the source factor value. Sets the impact of the alpha value on the source color.
Fdestination: the destination factor value. Sets the impact of the alpha value on the destination color.
After the fragment shader has run and all the tests have passed, this blend equation is let loose on the fragment's color output and with whatever is currently in the color buffer (previous fragment color stored before the current fragment). The source and destination colors will automatically be set by OpenGL, but the source and destination factor can be set to a value of our choosing.
//You might want to use the alpha values that result from texture mapping in the blend function. If so, (GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) is always a good function to start with.
// The glBlendFunc(GLenum sfactor, GLenum dfactor) function expects two parameters that set the option for the source and destination factor. OpenGL defined quite a few options for us to set of which we'll list the most common options below. Note that the constant color vector C¯constantC¯constant can be separately set via the glBlendColor function.
Option Value
GL_ZERO Factor is equal to 00.
GL_ONE Factor is equal to 11.
GL_SRC_COLOR Factor is equal to the source color vector C¯sourceC¯source.
GL_ONE_MINUS_SRC_COLOR Factor is equal to 11 minus the source color vector: 1−C¯source1−C¯source.
GL_DST_COLOR Factor is equal to the destination color vector C¯destinationC¯destination
GL_ONE_MINUS_DST_COLOR Factor is equal to 11 minus the destination color vector: 1−C¯destination1−C¯destination.
GL_SRC_ALPHA Factor is equal to the alphaalpha component of the source color vector C¯sourceC¯source.
GL_ONE_MINUS_SRC_ALPHA Factor is equal to 1−alpha1−alpha of the source color vector C¯sourceC¯source.
GL_DST_ALPHA Factor is equal to the alphaalpha component of the destination color vector C¯destinationC¯destination.
GL_ONE_MINUS_DST_ALPHA Factor is equal to 1−alpha1−alpha of the destination color vector C¯destinationC¯destination.
GL_CONSTANT_COLOR Factor is equal to the constant color vector C¯constantC¯constant.
GL_ONE_MINUS_CONSTANT_COLOR Factor is equal to 11 - the constant color vector C¯constantC¯constant.
GL_CONSTANT_ALPHA Factor is equal to the alphaalpha component of the constant color vector C¯constantC¯constant.
GL_ONE_MINUS_CONSTANT_ALPHA Factor is equal to 1−alpha1−alpha of the constant color vector C¯constantC¯constant.
*/
// To get the blending result we have to take the alpha of the source color vector for the source factor and 1−alpha for the destination factor. This translates to the glBlendFunc as follows:
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// It is also possible to set different options for the RGB and alpha channel individually using glBlendFuncSeparate:
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); // This function sets the RGB components as we've set them previously, but only lets the resulting alpha component be influenced by the source's alpha value.
/*
OpenGL gives us even more flexibility by allowing us to change the operator between the source and destination part of the equation. Right now, the source and destination components are added together, but we could also subtract them if we want. glBlendEquation(GLenum mode) allows us to set this operation and has 3 possible options:
- GL_FUNC_ADD: the default, adds both components to each other: C¯result = Src + Dst.
- GL_FUNC_SUBTRACT: subtracts both components from each other: C¯result = Src − Dst.
- GL_FUNC_REVERSE_SUBTRACT: subtracts both components, but reverses order: C¯result = Dst − Src.
*/
/*
// When drawing a scene with non-transparent and transparent objects the general outline is usually as follows:
- Draw all opaque objects first.
- Sort all the transparent objects.
- Draw all the transparent objects in sorted order.
One way of sorting the transparent objects is to retrieve the distance of an object from the viewer's perspective. This can be achieved by taking the distance between the camera's position vector and the object's position vector.
*/
// https://learnopengl.com/#!Advanced-OpenGL/Face-culling
// Winding order
// When we define a set of triangle vertices we're defining them in a certain winding order that is either clockwise or counter-clockwise. Each triangle consists of 3 vertices and we specify those 3 vertices in a winding order as seen from the center of the triangle.
/*
1 1
| |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
|_______________| |______________|
3 2 2 3
ClockWise Counter-ClockWise
1->2->3 1->3->2
*/
// Now that we know how to set the winding order of the vertices we can start using OpenGL's face culling option which is disabled by default.
// To enable face culling we only have to enable OpenGL's GL_CULL_FACE option:
glEnable(GL_CULL_FACE);//only front facing poligons are rendered, for faces having a clock wise or counter clock wise order
// GL_CULL_FACE is to be enabled for performance reasons, as it easily removes half of the triangles to draw, normally without visual artifacts if your geometry is watertight, and CCW.
// OpenGL allows us to change the type of face we want to cull as well. What if we want to cull front faces and not the back faces? We can define this behavior by calling glCullFace:
// glCullFace(GL_FRONT);
// Needed when rendering the shadow map. This will avoid artifacts.
glPolygonOffset(1.0f, 0.0f);
/*
The glCullFace function has three possible options:
GL_BACK: Culls only the back faces.
GL_FRONT: Culls only the front faces.
GL_FRONT_AND_BACK: Culls both the front and back faces.
*/
// The initial default value of glCullFace is GL_BACK.
glCullFace(GL_BACK);
// Aside from the faces to cull we can also tell OpenGL we'd rather prefer clockwise faces as the front-faces instead of counter-clockwise faces via glFrontFace:
glFrontFace(GL_CCW); // this allow us to render in counter clockwise maner, by default opengl renders in this counter colockwise manner.
// The default value is GL_CCW that stands for counter-clockwise ordering with the other option being GL_CW which (obviously) stands for clockwise ordering.
// enable seamless cubemap sampling for lower mip levels in the pre-filter map.
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
}
void CGameWindow::PostRendering()
{
glfwPollEvents();
}
void CGameWindow::ClearBuffers(const ClearBuffersType &bufferType){
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
switch (bufferType) {
case ClearBuffersType::COLORDEPTHSTENCIL:
//// CLEAR Buffers, The default clear value for the depth is 1.0f, which is equal to the depth of your far clipping plane
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); ////<-- CLEAR WINDOW
glClearDepth(1.0f); // same as glClear, we are simply specificaly clearing the depthbuffer
// enable depth testing (is disabled for rendering screen-space quad post processing)
glEnable(GL_DEPTH_TEST);
glEnable(GL_STENCIL_TEST);
// comment out if stencil buffer is not used
// glStencilMask(0xFF); // each bit is written to the stencil buffer as is
// glStencilMask(0x00); // each bit ends up as 0 in the stencil buffer (disabling writes)
// Most of the cases you'll just be writing 0x00 or 0xFF as the stencil mask, but it's good to know there are options to set custom bit-masks.
glStencilMask(0x00);
break;
case ClearBuffersType::COLORDEPTH:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ////<-- CLEAR WINDOW
glClearDepth(1.0f); // same as glClear, we are simply specificaly clearing the depthbuffer
glEnable(GL_DEPTH_TEST);
break;
case ClearBuffersType::COLORSTENCIL:
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); ////<-- CLEAR WINDOW
break;
case ClearBuffersType::DEPTH:
glClear(GL_DEPTH_BUFFER_BIT); ////<-- CLEAR WINDOW
glEnable(GL_DEPTH_TEST);
break;
}
}
//Swap front and back buffers
void CGameWindow::SwapBuffers(){
//glfwSwapInterval(1);
glfwSwapBuffers(m_window);
}
//Destroy the window, // Deinitialise the window and rendering context
void CGameWindow::DestroyWindow(){
glfwMakeContextCurrent(nullptr);
glfwDestroyWindow(m_window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
// Deinitialise the window and rendering context
CGameWindow::~CGameWindow(){
DestroyWindow();
SetCursorVisible(true);
}
| true |
b129b52ee1cd6898a6a3e5e3e234c2650984a032 | C++ | avshab/KochSnowflakes | /KochSnowflakes/src/KochTriangle.h | UTF-8 | 883 | 2.828125 | 3 | [] | no_license | #pragma once
#include "KochSegment.h"
#include "RandomAS.h"
class KochTriangle
{
public:
KochTriangle( const KochSegment& s1, const KochSegment& s2, const KochSegment& s3, int iter_order );
KochTriangle( const BasePoint& p1, const BasePoint& p2, const BasePoint& p3, int iter_order );
KochTriangle(){};
std::vector<BasePoint> GetPoints() const;
std::vector<KochSegment> GetSegments() const;
std::vector<KochTriangle> GetIterTriangles();
KochTriangle GetInternalTriangle() const;
void SetColor( Color color );
Color GetColor() const;
void SetCentralPoint();
private:
void SetChildsTriangles();
Color color;
std::vector<BasePoint> versus;
std::vector<KochSegment> segs;
std::vector<KochTriangle> childs;
bool was_iterating;
int iter_order;
RandomAS rand;
BasePoint central_point;
}; | true |
fee49cdd2f4f2e8aba2cbe9ef63962951fa7e20f | C++ | navidkpr/Competitive-Programming | /CodeForces/kbl_didi_ridi/518/A[ Vitaly and Strings ].cpp | UTF-8 | 933 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
string s1[3];
int main()
{
string s, t;
cin >> s >> t;
int n = s.size();
for (int i = 0; i < n; i++)
if (s[i] == t[i])
continue;
else if (s[i] < t[i])
break;
else
{
cout << "No such string" << endl;
return 0;
}
for (int i = n - 1; i >= 0; i--)
if (s[i] != 'z')
{
s1[0] = s;
s1[1] = t;
s1[2] = s;
s1[2][i] = s1[2][i] + 1;
string ans = s1[2];
sort(s1, s1 + 3);
if (s1[1] == ans && s1[1] != s1[0] && s1[1] != s1[2])
{
cout << s1[1] << endl;
return 0;
}
}
for (int i = n - 1; i >= 0; i--)
if (t[i] != 'a')
{
s1[0] = s;
s1[1] = t;
s1[2] = t;
s1[2][i] = s1[2][i] - 1;
string ans = s1[2];
sort(s1, s1 + 3);
if (s1[1] == ans && s1[1] != s1[0] && s1[1] != s1[2])
{
cout << s1[1] << endl;
return 0;
}
}
cout << "No such string" << endl;
return 0;
}
| true |
faba03dbc8df3d58252f7a71ad046dff9317bf45 | C++ | alesegdia/ecscpp | /src/lib/ecs/system/System.h | UTF-8 | 455 | 2.703125 | 3 | [] | no_license | #ifndef __SYSTEM_H__
#define __SYSTEM_H__
#include <memory>
#include <ecs/entity/EntityObserver.h>
class GameWorld;
/**
* @brief The System class represents a piece of logic to be executed
* on each world step. Systems will be executed on insert order, but
* a scheduer could be done to delegate this task.
*/
class System
{
public:
System();
virtual ~System()= 0 ;
/**
* @brief step to be executed
*/
virtual void process() ;
};
#endif
| true |
a7236b97781f861f40b89c6f99bb9a6dcfb4b68a | C++ | shenyute/self-practice | /cpp/trace_monitor_use.cpp | UTF-8 | 503 | 2.71875 | 3 | [] | no_license | #include "trace_monitor.h"
#include <stdio.h>
#include <unistd.h>
int main()
{
TraceMonitor monitor;
// block open system call, you can reference syscallent.h
std::set<int> blockCalls = {2};
monitor.BlockSysCall(blockCalls);
monitor.StartTrace();
printf("child start\n");
FILE* fp = fopen("oo", "w");
for (int i = 0; i < 100; i++)
fprintf(fp, "oo");
printf("child done\n");
monitor.EndTrace();
printf("child end\n");
sleep(20);
printf("child sleep end\n");
return 0;
}
| true |
52c5f01bad4a360174bfaf4da80330844c0fa44f | C++ | mariosbikos/ShipSimulation | /ShipSimulationProject/ShipSimulationProject/Ships/Ship.h | UTF-8 | 1,163 | 2.75 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include <string>
#include <vector>
enum ShipType : int;
enum MoveDirection : int;
class GridPoint;
class OceanMap;
class Position2D;
using namespace std;
class Ship
{
public:
Ship();
virtual ~Ship();
void SetupOceanMap(OceanMap* InOceanMap);
void Action();
void Move();
static int NumOfShips; //Total Num of ships of all types
static Ship* CreateShip(ShipType ShipChoice); //Factory Method
GridPoint* GetShipGridPoint() const;
void SetShipGridPoint(GridPoint* InGridPoint);
bool MoveToNewPosition(const Position2D& NewPosition);
void ChangeGold(const double GoldAmount);
double GetCurrentGold() const;
double GetCurrentDurability() const;
double GetMaxDurability() const;
bool IsDamaged() const;
void ChangeDurability(const int DurabilityValue);
void RepairShipDurabilityFromPort();
std::string GetShipName() const;
friend ostream& operator<<(ostream& os, const Ship& dt);
protected:
double CurrentDurability;
double MaxDurability;
int Speed;
double Gold=0;
std::string Name;
GridPoint* ShipGridPoint = nullptr;
OceanMap* CurrentOceanMap = nullptr;
virtual void DoAction() = 0;
};
| true |
c836409f9d2dd0347cd3f40dd15622547def4ddc | C++ | shenxin-karl/MinSTL | /heap_algorithm.hpp | UTF-8 | 6,203 | 2.8125 | 3 | [] | no_license | #ifndef HEAP_ALGORITHP_HPP
#define HEAP_ALGORITHP_HPP
#include "iterator.hpp"
#include <utility>
namespace sx {
template<typename RandomIterator>
void push_heap(RandomIterator const &, RandomIterator const &);
template<typename RandomIterator, typename Compare>
void push_heap(RandomIterator const &, RandomIterator const &, Compare const &);
template<typename RandomIterator, typename Compare>
void __push_heap_aux(RandomIterator, RandomIterator, Compare, sx::random_access_iterator_tag);
template<typename RandomIterator>
void pop_heap(RandomIterator const &first, RandomIterator const &end);
template<typename RandomIterator, typename Compare>
void pop_heap(RandomIterator const &, RandomIterator const &, Compare const &);
template<typename RandomIterator, typename Compare>
void __pop_heap_aux(RandomIterator const &, RandomIterator const &, Compare const &, sx::random_access_iterator_tag);
template<typename RandomIterator>
void sort_heap(RandomIterator first, RandomIterator end);
template<typename RandomIterator, typename Compare>
void sort_heap(RandomIterator first, RandomIterator end, Compare comp);
template<typename RandomIterator, typename Compare>
void make_heap(RandomIterator const &first, RandomIterator const &, Compare const &);
template<typename RandomIterator, typename Compare>
void make_heap(RandomIterator const &first, RandomIterator const &);
template<typename RandomIterator, typename Compare>
void __make_heap_aux(RandomIterator, RandomIterator, Compare, sx::random_access_iterator_tag);
template<typename RandomIterator, typename Compare>
void __adjust_heap(RandomIterator first, int hole_index, int len, Compare comp);
template<typename RandomIterator>
void push_heap(RandomIterator const &first, RandomIterator const &end) {
using iterator_category = typename iterator_traits<RandomIterator>::iterator_category;
sx::__push_heap_aux(first, end, std::greater<>{}, iterator_category{});
}
template<typename RandomIterator, typename Compare>
void push_heap(RandomIterator const &first, RandomIterator const &end, Compare const &comp) {
using iterator_category = typename iterator_traits<RandomIterator>::iterator_category;
sx::__push_heap_aux(first, end, comp, iterator_category{});
}
template<typename RandomIterator, typename Compare> inline
void __push_heap_aux(RandomIterator begin, RandomIterator end, Compare comp, sx::random_access_iterator_tag) {
using distance_type = typename iterator_traits<RandomIterator>::difference_type;
using value_type = typename iterator_traits<RandomIterator>::value_type;
distance_type hole_index = end - begin - 1;
distance_type parent_index = (hole_index - 1) / 2;
value_type value = std::move(begin[hole_index]);
while (hole_index >= 1) {
/* 如果满足条件, 父结点移动下来 */
if (comp(value, begin[parent_index])) {
begin[hole_index] = std::move(begin[parent_index]);
hole_index = parent_index;
parent_index = (parent_index - 1) / 2;
}
else
break;
}
begin[hole_index] = std::move(value);
}
template<typename RandomIterator>
void pop_heap(RandomIterator const &first, RandomIterator const &end) {
using iterator_category = typename iterator_traits<RandomIterator>::iterator_category;
sx::__pop_heap_aux(first, end, std::greater<>{}, iterator_category{});
}
template<typename RandomIterator, typename Compare> inline
void pop_heap(RandomIterator const &first, RandomIterator const &end, Compare const &comp) {
using iterator_category = typename iterator_traits<RandomIterator>::iterator_category;
sx::__pop_heap_aux(first, end, comp, iterator_category{});
}
template<typename RandomIterator, typename Compare> inline
void __pop_heap_aux(RandomIterator const &first, RandomIterator const &end, Compare const &comp, sx::random_access_iterator_tag) {
if (first == end || first + 1 == end)
return;
using std::swap;
using difference_type = typename iterator_traits<RandomIterator>::difference_type;
difference_type len = sx::distance(first, end);
swap(first[0], first[len - 1]);
sx::__adjust_heap(first, 0, --len, comp);
}
template<typename RandomIterator, typename Compare>
void __adjust_heap(RandomIterator first, int hole_index, int len, Compare comp) {
using difference_type = typename iterator_traits<RandomIterator>::difference_type;
using value_type = typename iterator_traits<RandomIterator>::value_type;
value_type value = std::move(*(first + hole_index));
difference_type child;
for (; (2 * hole_index + 1) < len; hole_index = child) {
child = (2 * hole_index) + 1;
if (child != len - 1 && comp(first[child + 1], first[child]))
++child;
if (comp(first[child], value))
first[hole_index] = std::move(first[child]);
else
break;
}
first[hole_index] = std::move(value);
}
template<typename RandomIterator>
void sort_heap(RandomIterator first, RandomIterator end) {
while (end - first > 1)
sx::pop_heap(first, end--);
}
template<typename RandomIterator, typename Compare>
void sort_heap(RandomIterator first, RandomIterator end, Compare comp) {
while (end - first > 1)
sx::pop_heap(first, end--, comp);
}
template<typename RandomIterator, typename Compare>
void make_heap(RandomIterator const &first, RandomIterator const &end, Compare const &comp) {
using iterator_category = typename iterator_traits<RandomIterator>::iterator_category;
sx::__make_heap_aux(first, end, comp, iterator_category{});
}
template<typename RandomIterator>
void make_heap(RandomIterator const &first, RandomIterator const &end) {
using iterator_category = typename iterator_traits<RandomIterator>::iterator_category;
sx::__make_heap_aux(first, end, std::greater<>{}, iterator_category{});
}
template<typename RandomIterator, typename Compare>
void __make_heap_aux(RandomIterator first, RandomIterator end, Compare comp, sx::random_access_iterator_tag) {
using difference_type = typename iterator_traits<RandomIterator>::difference_type;
difference_type len = sx::distance(first, end);
difference_type hole_index = (len - 1) / 2; /* 找到第一个非叶子结点 */
while (hole_index >= 0) {
sx::__adjust_heap(first, hole_index, len, comp);
--hole_index;
}
}
} // !namespace sx
#endif // !M_HEAP_ALGORITHM_HPP
| true |
b3c0174945054f59a4b5eaed0566cc70dbd6b666 | C++ | Redestroy/MRS | /Simulations/MRS_Spacial_Tasks/Default_world/controllers/EPuck_Robot/SerialCommunication.cpp | UTF-8 | 2,649 | 2.5625 | 3 | [] | no_license | #include "SerialCommunication.h"
int SerialCommunication::DEVICE_NUMBER = 0;
SerialCommunication::SerialCommunication() : CommunicationDevice(DEVICE_NUMBER)
{
emiter = nullptr;
reciever = nullptr;
isMaster = false;
DEVICE_NUMBER++;
}
SerialCommunication::SerialCommunication(webots::Robot * robot) : CommunicationDevice(DEVICE_NUMBER)
{
emiter = robot->getEmitter("emitter");
reciever = robot->getReceiver("receiver");
TIME_STEP = 4;
isMaster = false;
DEVICE_NUMBER++;
emiter->setChannel(3);
reciever->enable(TIME_STEP);
//printf("Type reciever: %s \n", reciever->);
reciever->setChannel(3);
packet = new std::string("");
SetID(DEVICE_NUMBER);
}
SerialCommunication::~SerialCommunication()
{
delete packet;
}
bool SerialCommunication::SwitchToMaster()
{
isMaster = true;
return isMaster;
}
bool SerialCommunication::SwitchToSlave()
{
isMaster = false;
return isMaster;
}
void SerialCommunication::FindNearbyDevices(const char * deviceList)
{
// send discovery notice
// for discovery time
// if(time >= i*delta) resend discovery notice
// if(queue>0) Add to device list
}
void SerialCommunication::ConnectTo(long id)
{
// change method to int
// if(isMaster)
// brodcast pair request
// wait for ack
// if ack setChannel to id
// send handshake
// if ok return 1
// else return -1
// else return -1
// else
// setChannel to local ID
// wait for handshake
// if ok return 1
// else return -1
}
void SerialCommunication::Disconnect()
{
// sendNotice
// if !isMaster wait for ack
// disconnect
//
}
void SerialCommunication::SendMessage(const char * message, int size)
{
emiter->send((void *)message, size);
}
void SerialCommunication::SendMessage(char * message, int size)
{
emiter->send((void *)message, size);
}
void SerialCommunication::WaitForReply(const char *)
{
//not sure, might be obsolete
}
int SerialCommunication::RequestDataCode(int)
{
//add later
return 0;
}
int SerialCommunication::GetNumberOfPackets()
{
return reciever->getQueueLength();
}
std::string * SerialCommunication::ReturnLastPacket()
{
if (reciever->getQueueLength() > 0) {
packet->clear();
packet->append(std::string((char *)reciever->getData(), reciever->getDataSize()));
reciever->nextPacket();
return packet;
}
else return nullptr;
}
void SerialCommunication::Update()
{
//also nothing to do here
}
void SerialCommunication::SwitchChannel(int ch)
{
emiter->setChannel(ch);
reciever->setChannel(ch);
channel = ch;
}
int SerialCommunication::GetChannel()
{
return channel;
}
void SerialCommunication::SetID(int idNum)
{
id = idNum;
}
int SerialCommunication::GetID()
{
return id;
}
| true |
9d2c0d2189fb4f16b6860d421032bf4127b9c45a | C++ | aldebjer/pysim | /pysim/cppsource/CppSimulation.cpp | UTF-8 | 7,442 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "CppSimulation.hpp"
#include <boost/numeric/odeint.hpp>
#include <functional>
#include <algorithm>
#include <vector>
#include <exception>
namespace pysim{
struct EarlyBreakException : public std::exception {
virtual const char* what() const throw() {
return "A comparison resulted in an early break of the simulation";
}
}earlybreak;
Simulation::Simulation(void)
:currentTime(0) {
}
Simulation::~Simulation(void) {
}
void Simulation::doGenericStep(const std::vector< double > &state,
std::vector< double > &der,
double time) {
// Copy the state variables to the actual systems
auto si = states.cbegin();
for (auto i = state.cbegin(); i != state.cend(); ++i) {
**si++ = *i;
}
// Copy state outputs from all systems to their respective inputs
// Since they are states, and constant input to this function this
// is done before the timestep calulations.
for ( auto syst = systems.begin(); syst != systems.end(); ++syst ) {
(*syst)->preStep();
(*syst)->copystateoutputs();
(*syst)->copyoutputs();
}
// Do the time step for all systems, and copy the variable
// outputs after the time step.
for ( auto syst = systems.begin(); syst != systems.end(); ++syst ) {
(*syst)->doStep(time);
(*syst)->copyoutputs();
}
// Copy the systems derivate variables to the
// solvers (the input to this function).
auto di = der.begin();
for ( auto i = ders.cbegin(); i != ders.cend(); ++i ) {
*(di++) = **i;
}
}
void Simulation::observer(const std::vector<double> &state, double time) {
currentTime = time;
// Copy the state variables to the actual systems
auto si = states.cbegin();
for (auto i = state.cbegin(); i != state.cend(); ++i) {
**si++ = *i;
}
for ( auto syst = systems.cbegin(); syst != systems.end(); ++syst ) {
(*syst)->postStep();
(*syst)->doStoreStep(time);
}
for ( auto syst = discreteSystems.cbegin();
syst != discreteSystems.end();
++syst) {
(*syst)->postStep();
(*syst)->doStoreStep(time);
}
bool compare_break = false;
for (auto syst = systems.cbegin(); syst != systems.end(); ++syst) {
if ((*syst)->do_comparison()) {
compare_break = true;
}
}
if (compare_break) {
throw earlybreak;
}
}
void Simulation::prepare_first_sim() {
// Copy system states to this objects list
for ( auto syst = systems.cbegin(); syst != systems.end(); ++syst ) {
(*syst)->preSim();
std::vector<double*> sp = (*syst)->getStatePointers();
std::copy(sp.cbegin(), sp.cend(), std::back_inserter(states));
std::vector<double*> dp = (*syst)->getDerPointers();
std::copy(dp.cbegin(), dp.cend(), std::back_inserter(ders));
if (ders.size() != states.size()) {
throw std::runtime_error("Unequal states and ders");
}
}
for ( auto syst = discreteSystems.cbegin();
syst != discreteSystems.end();
++syst) {
(*syst)->preSim();
}
}
bool myfn(SimulatableSystemInterface* i, SimulatableSystemInterface* j) {
return i->getNextUpdateTime() < j->getNextUpdateTime();
}
void Simulation::simulate(double duration,
double dt,
char* solvername,
double abs_err,
double rel_err,
bool dense_output) {
if (currentTime == 0.0) {
prepare_first_sim();
}
double endtime = currentTime + duration;
if (discreteSystems.size() > 0) {
auto si = std::min_element(discreteSystems.begin(),
discreteSystems.end(),
myfn);
double inter_endtime = (*si)->getNextUpdateTime();
while (inter_endtime < endtime) {
if (inter_endtime > 0) {
setup_odeint(inter_endtime, dt, solvername,
abs_err, rel_err, dense_output);
}
do {
(*si)->doStep(currentTime);
std::vector<double*> states = (*si)->getStatePointers();
std::vector<double*> ders = (*si)->getDerPointers();
//Copy states to der
auto state_iter = states.begin();
auto der_iter = ders.begin();
while (state_iter != states.end()) {
**state_iter++ = **der_iter++;
}
(*si)->copystateoutputs();
(*si)->copyoutputs();
si = std::min_element(discreteSystems.begin(),
discreteSystems.end(),
myfn);
} while ((*si)->getNextUpdateTime() == inter_endtime);
si = std::min_element(discreteSystems.begin(),
discreteSystems.end(),
myfn);
inter_endtime = (*si)->getNextUpdateTime();
}
}
setup_odeint(endtime, dt, solvername, abs_err, rel_err, dense_output);
}
void Simulation::setup_odeint(double endtime,
double dt,
char* solvername,
double abs_err,
double rel_err,
bool dense_output) {
using namespace boost::numeric::odeint;
using std::vector;
namespace pl = std::placeholders;
auto ff = std::bind(&Simulation::doGenericStep,
this,
pl::_1, pl::_2, pl::_3);
auto sf = std::bind(&Simulation::observer, this, pl::_1, pl::_2);
vector< double > state;
for ( auto i = states.cbegin(); i != states.cend(); ++i ) {
state.push_back(**i);
}
try {
if (strcmp(solvername, "rk4") == 0) {
runge_kutta4<vector< double > > stepper;
integrate_const(stepper, ff, state, currentTime, endtime, dt, sf);
} else if (strcmp(solvername, "ck54") == 0) {
typedef runge_kutta_cash_karp54<vector<double> > error_stepper_type;
auto cs = make_controlled <error_stepper_type>(abs_err, rel_err);
integrate_adaptive(cs, ff, state, currentTime, endtime, dt, sf);
} else if (strcmp(solvername, "dp5") == 0) {
typedef runge_kutta_dopri5<vector<double> > error_stepper_type;
if (dense_output) {
auto cs = make_dense_output(abs_err, rel_err, error_stepper_type());
integrate_const(cs, ff, state, currentTime, endtime, dt, sf);
} else {
auto cs = make_controlled <error_stepper_type>(abs_err, rel_err);
integrate_adaptive(cs, ff, state, currentTime, endtime, dt, sf);
}
} else {
char errmsg[50];
snprintf(errmsg, sizeof(errmsg), "Unknown solver: %s", solvername);
throw std::invalid_argument(errmsg);
}
} catch (EarlyBreakException &eb) {
printf("%s\n",eb.what());
}
}
void Simulation::addSystem(SimulatableSystemInterface* system) {
if (system->getDiscrete()) {
discreteSystems.push_back(system);
} else {
systems.push_back(system);
}
}
}
| true |
290392db5a1d75218b8b9a7848a294114f23b9c4 | C++ | davidwahbi-playrix/practice_game | /GameTestProj/GameTestProj/Profile.cpp | UTF-8 | 1,568 | 2.609375 | 3 | [] | no_license | #include "Profile.h"
Profile::Profile()
{
_currentLevel = 1;
}
Profile::~Profile()
{
}
void Profile::NewGame(bool &running)
{
if (_currentLevel == FIRSTLEVEL)
{
_levelLoader.LoadPlayer2(_smartPlayer);
}
else
{
if (_currentLevel < MAXLEVEL)
{
_levelLoader.SetPlayerStartPos2(_currentLevel, _smartPlayer);
}
}
_levelLoader.LoadLevel3(_currentLevel, running, _board, _smartGameItems, _smartEnemies);
if (_currentLevel == FIRSTLEVEL || _currentLevel == VICTORY || _currentLevel == GAMEOVER)
{
_board.Display2();
}
}
int Profile::GetLevel() const
{
return _currentLevel;
}
int& Profile::GetLevel2()
{
return _currentLevel;
}
void Profile::SetLevel(const int level)
{
_currentLevel = level;
}
void Profile::GameOver(bool& running)
{
_currentLevel = 99;
NewGame(running);
}
bool Profile::CanPlayerEquip() const
{
return (GetSmartPlayer2().GetEquipInd() < GetSmartPlayer2().GetSmartInventory2().Size());
}
SmartPlayer & Profile::GetSmartPlayer2()
{
return _smartPlayer;
}
SmartPlayer Profile::GetSmartPlayer2() const
{
return _smartPlayer;
}
SmartInventory& Profile::GetSmartGameItems()
{
return _smartGameItems;
}
Board Profile::GetBoard() const
{
return _board;
}
Board & Profile::GetBoard2()
{
return _board;
}
std::vector<std::shared_ptr<Enemy>> Profile::GetSmartEnemies() const
{
return _smartEnemies;
}
std::vector<std::shared_ptr<Enemy>>& Profile::GetSmartEnemies2()
{
return _smartEnemies;
}
LevelLoader Profile::GetLevelLoader() const
{
return _levelLoader;
}
void Profile::IncreseLevel()
{
_currentLevel++;
}
| true |
699ad4f697f59d208e10450ae453a2041dcf085f | C++ | m80126colin/Judge | /before2020/TIOJ/TIOJ 1016.cpp | UTF-8 | 1,174 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
bool ox[18];
int out,base[2][4];
inline void clear() {
int i;
for (i=0;i<3;i++) base[(out/3)&1][i]=0;
return;
}
inline void home() {
int i;
base[(out/3)&1][3]++;
for (i=0;i<3;i++) base[(out/3)&1][3]+=base[(out/3)&1][i];
clear();
return;
}
inline void hit(int x) {
int i;
for (i=3-x;i<3;i++) base[(out/3)&1][3]+=base[(out/3)&1][i];
for (i=2;i>=x;i--) base[(out/3)&1][i]=base[(out/3)&1][i-x];
for (i=x-1;i>=0;i--) base[(out/3)&1][i]=0;
base[(out/3)&1][x-1]++;
return;
}
inline void walk() {
int i;
base[(out/3)&1][0]++;
for (i=1;i<4;i++) if (base[(out/3)&1][i-1]>1) base[(out/3)&1][i-1]--,base[(out/3)&1][i]++;
return;
}
int main() {
int i;
string s;
while (getline(cin,s)) {
for (i=0;i<18;i++) ox[i]=1;
for (out=base[0][3]=base[1][3]=i=0;i<s.size();i++) {
if (!(out%3)&&ox[out/3]) clear(),ox[out/3]=0;
if (s[i]=='K'||s[i]=='O') out++;
else if (s[i]=='H') home();
else if (s[i]=='S') hit(1);
else if (s[i]=='D') hit(2);
else if (s[i]=='T') hit(3);
else walk();
}
printf("%d %d\n",base[0][3],base[1][3]);
}
} | true |
094bc44bc3c06abe2c351891801b9c620b6362d5 | C++ | BSU2016gr09/ShavekoIvan | /first_term/2-2.cpp | UTF-8 | 1,318 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
void createArray(int a[], int N)
// Массив целых чисел размера N проинициализировать случайными числами из промежутка от -N до N. Циклически сдвинуть элементы массива вправо на 1 элемент (последний элемент станет первым, 1-й станет 2-м, 2-й станет 3-м и т.д.) потом циклически сдвинуть элементы массива влево на 1 элемент (первый элемент станет последним, 2-й станет 1-м и т.д)
{
int i = 0;
while (i < N)
{
a[i] = rand() % (2 * N + 1) - N;
i++;
}
}
void leftArray(int a[], int N)
{
int i = 0;
while (i < N-1)
{
swap(a[i], a[i + 1]);//без swap просили
i++;
}
}
void rightArray(int a[], int N)
{
int i = N-1;
while (i > 0)
{
swap(a[i], a[i-1]);//без swap просили
i--;
}
}
void coutArray(int a[], int N)
{
int i = 0;
while(i<N)
{
cout << a[i]<<' ';
i++;
}
cout << endl;
}
int main()
{
const int N = 9;
int arr[N];
createArray(arr, N);
coutArray(arr, N);
rightArray(arr, N);
coutArray(arr, N);
leftArray(arr, N);
coutArray(arr, N);
system("pause");
}
| true |
94b54d2d20e31cb4a0c4924792baa5c7517eea88 | C++ | srl-ethz/3d-soft-trunk-contact | /JugglerOptiTrackMbedEsconSolution/SerialCommunicatorClassTest/main.cpp | UTF-8 | 778 | 2.59375 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <cstdio>
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
//#include <windows.h>
//#include <math.h>
#include "SerialCommunicator.h"
int main()
{
SerialCommunicator serialComm;
float rpmMeasured = 0;
float rpmSent = 0;
//serialComm.sendMotorRpm(0);
//std::this_thread::sleep_for(std::chrono::milliseconds(2));
while (true)
{
serialComm.sendMotorRpm(rpmSent);
//printf("Diff: %.4f, Meas: %.4f, Sent: %.4f \n", (rpmMeasured - rpmSent), rpmMeasured, rpmSent);
if (rpmSent > RPM_MAX)
rpmSent = -RPM_MAX;
else
rpmSent = rpmSent + 1;
std::this_thread::sleep_for(std::chrono::milliseconds(3));
rpmMeasured = serialComm.readMotorRpm();
}
return 0;
} | true |
93a9c7193cd4068a6ce0d050571d05a86179b787 | C++ | josephbradleyCS/CS515 | /3P/image.cpp | UTF-8 | 6,983 | 3.140625 | 3 | [] | no_license | #include <iostream> // cout, cerr
#include <fstream> // ifstream
#include <sstream> // stringstream
#include <string.h>
using namespace std;
int main(int argc, char ** argv) {
if (argc != 4) {
cout << "Usage: image <input image> <neg image> <rotate image>" << endl;
exit(1);
}
stringstream ss;
ifstream infile;
infile.open(argv[1]);
if (!infile) {
"Can not open argv for input";
}
if (infile.fail()) {
cout << "Can not open: " << argv[1] << " for input";
exit(1);
}
ss << infile.rdbuf();
string p2;
int rows;
int cols;
ss >> p2;
ss >> cols >> rows;
int greyscale;
ss >> greyscale;
greyscale = 255;
int **arr = new int*[cols];
int i;
for (i = 0; i < rows; i++) {
arr[i] = new int[cols];
}
for (i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
ss >> arr[i][j];
}
}
infile.close();
ofstream inout;
inout.open(argv[3]);
if (inout.fail()) {
cout << "Failed to open: " << argv[3];
exit(1);
}
int inCols = rows;
int inRows = cols;
inout << "P2" << endl << rows << " " << cols << endl << greyscale << endl;
int **inarr = new int*[cols];
for (i = 0; i < cols; i++) {
inarr[i] = new int[rows];
}
cout << "arr is an array with \n\twidth: " << cols << "\n\tlenth: " << rows << endl;
cout << "inarr is an array with \n\twidth: " << rows << "\n\tlenth: " << cols << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
inarr[j][rows - i -1] = arr[i][j];
}
}
for (int i = 0; i < inRows; i++) {
for (int j = 0; j < inCols; j++) {
inout << inarr[i][j] << " ";
}
inout << endl;
}
inout.close();
//////////////////Negative image below///////////////////////////
ofstream negOut;
negOut.open(argv[2]);
if (negOut.fail()) {
cout << "Failed to open: " << argv[2];
exit(1);
}
int negCols = cols;
int negRows = rows;
negOut << "P2" << endl << cols << " " << rows << endl << greyscale << endl;
for (i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
negOut << (greyscale - arr[i][j]) << " ";
}
negOut << endl;
}
negOut.close();
// int **inarr = new int*[cols];
for (int i = 0; i < cols; i++) {
delete[] inarr[i];
}
for (i = 0; i < rows; i++) {
//delete[] inarr[i];
delete[] arr[i];
}
delete[] inarr;
delete[] arr;
return 0;
////////////////// NON_SQUARE IMAGE //////////////////////////////////
// } else {
//
// cout << "Non-Square Image:" << endl;
//
// int greyscale;
// ss >> greyscale;
// greyscale = 255;
//
// //cout << "\t-source arr initialized" << endl; //
// int **arr = new int*[cols];
// for (int i = 0; i < rows; i++) {
// arr[i] = new int[cols];
// }
//
//
//
// //cout << "\t-populating source arr" << endl; //
// for (int i = 0; i < rows; i++) {
// for (int j = 0; j < cols; j++) {
// ss >> arr[i][j];
// //cout << arr[i][j];
// }
// }
// infile.close();
//
// // init negative array //
// //cout << "\t-negative array initialized" << endl; //
//
// int **narr = new int*[cols];
//
// for (int i = 0; i < rows; i++) {
// narr[i] = new int[cols];
// }
//
// // populate negative array //
// //cout << "\t-negative array poplulated" << endl; //
//
// for (int i = 0; i < rows; i++) {
// for (int j = 0; j < cols; j++) {
// narr[i][j] = greyscale - arr[i][j];
// }
// }
//
// // init rotate array //
// //cout << "\t-rotate array initialized" << endl; //
//
// int **rarr = new int*[rows];
// for (int i = 0; i < rows; i++) {
// rarr[i] = new int[cols];
// }
//
// // populate rotate array //
// //cout << "\t-rotate array poplulated" << endl;
// //cout << "yeah here";
// for (int i = 0; i < rows; i++) {
// //cout << "Hello world";
// for (int j = 0; j < cols; j++) {
// //cout << "-";
// rarr[i][j] = greyscale - arr[i][j];
// }
// }
//
//
// /////////////////////// non square rotated image below ////////////////////////////
//
// // open rotate file /////////////
// //cout << "\tOpening:" << argv[3] << endl;
//
// ofstream rOut;
// //cout << "\tofstream initialized" << endl;
//
// rOut.open(argv[3]);
// //cout << "file preliminarily opened\n";
// if (rOut.fail()) {
// //cout << "Failed to open: " << argv[3] << endl;
// exit(1);
// }
//
// //cout << "\trotate file opened" << endl; //
//
//
// // roate file opened //////////
//
// rOut << "P2" << endl << rows << " " << cols << endl << greyscale << endl;
//
//
//
// for (int i = 0; i < rows; i++) {
// for (int j = 0; j < cols; j++) {
// rOut << narr[i][j] << " ";
// }
// rOut << endl;
// }
//
//
// rOut.close();
// //////////////////rotate image above ////////////////////////
//
// //////////////////Negative image below///////////////////////////
//
// // Neg-image file opening //////////////////////
// ofstream negOut;
// negOut.open(argv[2]);
//
// if (negOut.fail()) {
// cout << "Failed to open: " << argv[2];
// exit(1);
// }
//
// //cout << "\n\tneg file opened" << endl; //
//
//
// // Neg image opened ///////////////////////////
//
// // Insert
// negOut << "P2" << endl << rows << " " << cols << endl << greyscale << endl;
//
// for (int i = 0; i < cols; i++) {
// for (int j = 0; j < rows; j++) {
// negOut << narr[i][j] << " ";
// }
// negOut << endl;
// }
//
// negOut.close();
//
// // Negative image end ///////////////////////////////////
//
// for (int i = 0; i < rows; i++) {
// //delete[] rarr[i];
// delete[] narr[i];
// delete[] arr[i];
// }
// for (int i = 0; i < cols; i++) {
// delete[] rarr[i];
// }
// delete[] narr;
// delete[] rarr;
// delete[] arr;
//
// return 0;
// }
}
| true |
fca84c2ef951c2db5c31dea5fc5071122b04cee8 | C++ | win18216001/tpgame | /GServerEngine/Public/BaseEntity.h | UTF-8 | 294 | 2.828125 | 3 | [] | no_license | #pragma once
class CBaseEntity
{
public:
CBaseEntity( int id )
{
SetId( id );
}
virtual ~CBaseEntity(void);
virtual void Update() = 0;
int GetId()const { return m_id ; }
private:
static long m_iNextValidId;
int m_id;
void SetId( int val );
};
| true |
1ef175599f814d77cd23cc81892d4e8697847776 | C++ | jlandy99/naturalSelectionSim | /Orgs.hpp | UTF-8 | 2,538 | 3.265625 | 3 | [] | no_license | //
// Org.hpp
// naturalSelectionSim
//
// Created by John Landy on 4/30/19.
// Copyright © 2019 John Landy. All rights reserved.
//
#ifndef Orgs_hpp
#define Orgs_hpp
#include <stdio.h>
#include <vector>
#include <cstdlib>
#include <iostream>
// Class containing the group of organisms and their interactions
class Orgs {
public:
// Constructor
Orgs(int numOrgs, int dimensions);
// Base function for organisms to interact
void interact(int iterationNum, bool simple);
// Function to print the stats/metadata for the organisms and their environment
void printStats(int it, bool simple);
private:
// Class for the Grid the organisms interact on
class Grid {
public:
// Constructor
Grid(int dimensions_in);
// Function to retrieve dimensions
int getDimensions();
// Function for Grid to reset the food particles between iterations
void setFood();
// Public member var to store food count per round
int foodCount;
private:
int dimensions;
// Tile struct
struct Tile {
int x;
int y;
bool isFood;
bool isOrg;
};
public:
// Actual Grid data structure
std::vector<std::vector<Tile> > grid;
};
// Class for each individual organism
class Org {
public:
// Constructor
Org();
// Function to randomly set initial location of an organism each day
void setLoc(int dimensions);
// Function that determines where each organism will move.
// There is no limit to the number of organisms per grid tile, but if a tile
// has food, only the first organism there can eat it
void move(Grid g);
// Energy getter
int getEnergy();
// Food getter
int getFood();
// Size getter
int getSize();
// Speed getter
int getSpeed();
// Energy cost getter
int getEnergyCost();
// Food setter
void setFood(int val);
// Energy setter
void setEnergy(int val);
private:
// Location
int xLoc;
int yLoc;
// Org Traits
int speed;
int energy;
int food;
int size;
int senseDist;
int energyCost;
};
// Vector of eaten Orgs in each round
std::vector<int> eaten;
// Data structure to hold all of the Orgs
std::vector<Org> orgs;
// Grid object
Grid g;
};
#endif /* Org_hpp */
| true |
759865bc704424035f45eb4119cc3ed5aa88933d | C++ | tempbottle/stunclient | /stun/Discovery.cpp | UTF-8 | 11,489 | 2.71875 | 3 | [] | no_license | //
// Discovery.cpp
// ppio
//
// Created by Maoxu Li on 2/11/12.
// Copyright (c) 2012 PPEngine. All rights reserved.
//
#include "Discovery.h"
#include <stun/Buffer.h>
#include <iostream>
STUN_BEGIN
Discovery::Discovery(const std::string& host, unsigned short port, int timeout)
: _host(host)
, _port(port)
, _timeout(timeout)
, _socket(host, port)
{
}
Discovery::~Discovery()
{
}
void Discovery::setRemoteAddress(const std::string& host, unsigned short port)
{
_socket.setRemoteAddress(host, port);
}
void Discovery::setRemoteAddress(const struct sockaddr_in& sin)
{
_socket.setRemoteAddress(sin);
}
sockaddr_in Discovery::remoteAddress()
{
return _socket.remoteAddress();
}
bool Discovery::isLocalAddress(const struct sockaddr_in& sin)
{
std::vector<struct in_addr> addrs = network::getLocalAddress();
for(int i = 0; i < addrs.size(); i++)
{
std::cout << "Local IP: " << inet_ntoa(addrs[i]) << "\n";
if(addrs[i].s_addr == sin.sin_addr.s_addr)
{
return true;
}
}
return false;
}
bool Discovery::isSameAddress(const struct sockaddr_in& a, const struct sockaddr_in& b)
{
return (a.sin_addr.s_addr == b.sin_addr.s_addr) && (a.sin_port == b.sin_port);
}
// Send stun request mesage
void Discovery::sendMessage(Message* msg)
{
assert(msg != NULL);
//std::cout << ">> " << msg->toString() << "\n";
_tid = msg->tid();
network::Buffer buf;
msg->toBuffer(&buf);
_socket.write(buf.read(), buf.readable());
}
Message* Discovery::receiveMessage(int timeout)
{
network::Buffer buf;
buf.reserve(512);
long len = _socket.read(buf.write(), buf.writable(), timeout);
if(len > 0)
{
buf.write(len);
Message* msg = MessageFactory::fromBuffer(&buf);
//std::cout << "<< " << msg->toString() << "\n";
if(msg != NULL && msg->tid() == _tid)
{
return msg;
}
}
return NULL;
}
/*
In this scenario, a user is running a multimedia application which
needs to determine which of the following scenarios applies to it:
o On the open Internet
o Firewall that blocks UDP
o Firewall that allows UDP out, and responses have to come back to
the source of the request (like a symmetric NAT, but no
translation. We call this a symmetric UDP Firewall)
o Full-cone NAT
o Symmetric NAT
o Restricted cone or restricted port cone NAT
The flow makes use of three tests. In test I, the client sends a
STUN Binding Request to a server, without any flags set in the
CHANGE-REQUEST attribute, and without the RESPONSE-ADDRESS attribute.
This causes the server to send the response back to the address and
port that the request came from. In test II, the client sends a
Binding Request with both the "change IP" and "change port" flags
from the CHANGE-REQUEST attribute set. In test III, the client sends
a Binding Request with only the "change port" flag set.
The client begins by initiating test I. If this test yields no
response, the client knows right away that it is not capable of UDP
connectivity. If the test produces a response, the client examines
the MAPPED-ADDRESS attribute. If this address and port are the same
as the local IP address and port of the socket used to send the
request, the client knows that it is not natted. It executes test
II.
If a response is received, the client knows that it has open access
to the Internet (or, at least, its behind a firewall that behaves
like a full-cone NAT, but without the translation). If no response
is received, the client knows its behind a symmetric UDP firewall.
In the event that the IP address and port of the socket did not match
the MAPPED-ADDRESS attribute in the response to test I, the client
knows that it is behind a NAT. It performs test II. If a response
is received, the client knows that it is behind a full-cone NAT. If
no response is received, it performs test I again, but this time,
does so to the address and port from the CHANGED-ADDRESS attribute
from the response to test I. If the IP address and port returned in
the MAPPED-ADDRESS attribute are not the same as the ones from the
first test I, the client knows its behind a symmetric NAT. If the
address and port are the same, the client is either behind a
restricted or port restricted NAT. To make a determination about
which one it is behind, the client initiates test III. If a response
is received, its behind a restricted NAT, and if no response is
received, its behind a port restricted NAT.
*/
//
// +--------+
// | Test |
// | I |
// +--------+
// |
// |
// V
// /\ /\
// N / \ Y / \ Y +--------+
// UDP <-------/Resp\--------->/ IP \------------->| Test |
// Blocked \ ? / \Same/ | II |
// \ / \? / +--------+
// \/ \/ |
// | N |
// | V
// V /\
// +--------+ Sym. N / \
// | Test | UDP <---/Resp\
// | II | Firewall \ ? /
// +--------+ \ /
// | \/
// V |Y
// /\ /\ |
//Symmetric N / \ +--------+ N / \ V
// NAT <--- / IP \<-----| Test |<--- /Resp\ Open
// \Same/ | I | \ ? / Internet
// \? / +--------+ \ /
// \/ \/
// | |Y
// | |
// | V
// | Full
// | Cone
// V /\
// +--------+ / \ Y
// | Test |------>/Resp\---->Restricted
// | III | \ ? /
// +--------+ \ /
// \/
// |N
// | Port
// +------>Restricted
//
void Discovery::discover()
{
// TEST I
// Send binding request with no change address request attribute
setRemoteAddress(_host, _port);
std::cout << "TEST I to " << network::addressToString(remoteAddress()) << "\n";
BindingResponse* t1_response = binding();
if(t1_response == NULL) // TEST I -> No Response
{
std::cout << "TEST I -> No Response.\n";
std::cout << "You are behind a firewall that blocks UDP.\n";
}
else // TEST I -> Yes Response
{
sockaddr_in sin = t1_response->mappedAddress();
std::cout << "Mapped address: " << network::addressToString(sin) << "\n";
if(isLocalAddress(sin)) // IP same Yes
{
std::cout << "TEST I -> Mapped IP is same as local one.\n";
// TEST II
std::cout << "TEST II to " << network::addressToString(remoteAddress()) << "\n";
BindingResponse* t2_response = binding(true, true);
if(t2_response == NULL) // TEST II -> No Response
{
std::cout << "TEST II -> No Response.\n";
std::cout << "You are behind a symmetric UDP Firewall.\n";
}
else // TEST II -> Yes Response
{
std::cout << "TEST II -> Yes Response.\n";
std::cout << "You have a open Internet access.\n";
}
}
else // IP same No
{
std::cout << "TEST I -> Mapped IP is different from local one.\n";
// TEST II
std::cout << "TEST II to " << network::addressToString(remoteAddress()) << "\n";
BindingResponse* t2_response = binding(true, true);
if(t2_response != NULL) // TEST II -> Yes Response
{
std::cout << "TEST II -> Yes Response.\n";
std::cout << "You are behind a full cone NAT.\n";
}
else // TEST II -> No Response
{
std::cout << "TEST II -> No Response.\n";
// TEST I again
// To TEST I mapped address
_socket.setRemoteAddress(t1_response->changedAddress());
std::cout << "TEST I again to " << network::addressToString(remoteAddress()) << "\n";
BindingResponse* t12_response = binding();
if(t12_response == NULL) // TEST I(2) -> No Response
{
assert(false);
std::cout << "ERROR!\n";
std::cout << "TEST I again -> No Response.\n";
}
else // TEST I(2) -> Yes Response
{
sockaddr_in sin = t12_response->mappedAddress();
std::cout << "Mapped address: " << network::addressToString(sin) << "\n";
if(!isSameAddress(sin, t1_response->mappedAddress()))
{
std::cout << "TEST I again -> Mapped port is different from first test.\n";
std::cout << "You are behind a symmetric NAT.\n";
}
else
{
std::cout << "TEST I again -> Mapped port is same as first test.\n";
// TEST III
std::cout << "TEST III to " << network::addressToString(remoteAddress()) << "\n";
BindingResponse* t3_response = binding(true);
if(t3_response != NULL) // TEST III -> Yes Response
{
std::cout << "TEST III -> Yes Response.\n";
std::cout << "You are behind a restricted cone NAT.\n";
}
else // TEST III -> No Response
{
std::cout << "TEST III -> No Response.\n";
std::cout << "You are behind a restricted port cone NAT.\n";
}
}
}
}
}
}
}
BindingResponse* Discovery::binding(bool portChange, bool ipChange)
{
BindingRequest request;
if(ipChange || portChange)
{
request.setChangeRequest(portChange, ipChange);
}
sendMessage(&request);
// Receive and resend every 200 ms until timeout
Message* response = NULL;
for(int i = 0; i < _timeout/200; i++)
{
response = receiveMessage(200);
if(response == NULL)
{
sendMessage(&request);
}
else
{
break;
}
}
return dynamic_cast<BindingResponse*>(response);
}
STUN_END
| true |
1b4f7a8f34fe9b27e671e79395ed31e8740bb350 | C++ | fallen/NetBSD6 | /regress/usr.bin/c++/static_destructor/static_destructor.cc | UTF-8 | 617 | 2.9375 | 3 | [] | no_license | /* $NetBSD: static_destructor.cc,v 1.1 2007/09/17 17:37:49 drochner Exp $ */
/*
* Tests proper order of destructor calls
* (must be in reverse order of constructor completion).
* from the gcc mailing list
*/
#include <iostream>
using namespace std;
class A
{
public:
int i;
A(int j) : i(j) { cout << "constructor A" << endl; }
~A() { cout << "destructor A : i = " << i << endl; }
};
class B
{
public:
A *n;
B() {
static A p(1);
n = &p;
cout << "constructor B" << endl;
}
~B() {
cout << "destructor B : i = " << n->i << endl;
n->i = 10;
}
};
class B x1;
int main (void) { return 0; }
| true |
c50866a00c9e0a6e41fe4fb02ea1d3a2874fde53 | C++ | Siwwyy/3_Studying_Year | /ADVANCED_PROGRAMMING_II/!C++/zadanie6_fabryka_finalna/zadanie6_fabryka_finalna/_MORSE_BEEP.h | UTF-8 | 4,441 | 2.75 | 3 | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | // _MORSE_BEEP_H_ standard header
/*
* Copyright (c) by Damian Andrysiak. All rights reserved.
* *** WERSJA FINALNA ***
* *** Koniec: 04/01/2019 ***
* Klasa ma za zadanie:
* 1. Klasa pochodna po klasie Morse Base
* 2. Produktem klasy jest mors dzwiekowy
*/
#ifndef _MORSE_BEEP_H_
#define _MORSE_BEEP_H_
/*
OUTSIDE FILES .h / .hpp
*/
#include "_MORSE_BASE.h"
//////////////////////////////////////
class _MORSE_BEEP final :
public _MORSE_BASE
{
private:
/*
ZMIENNE PRIVATE
*/
int m__Freq; //Frequency
int m__Pause; //Pause
int m__DotTime; //DotTime
int m__DashTime; //DashTime
int m__CharPause; //CharPause
//////////////////////////////////////////////////////////////////////////////
/*
KONSTRUKTORY PRIVATE
*/
//////////////////////////////////////////////////////////////////////////////
/*
FUNKCJE PRIVATE
*/
//////////////////////////////////////////////////////////////////////////////
/*
SETTERY PRIVATE
*/
//////////////////////////////////////////////////////////////////////////////
/*
GETTERY PRIVATE
*/
//////////////////////////////////////////////////////////////////////////////
/*
OPERATORY PRIVATE
*/
//JEDNOARGUMENTOWE
//////////////////////////////////////////////////////////////////////////////
protected:
/*
ZMIENNE PROTECTED
*/
//////////////////////////////////////////////////////////////////////////////
/*
KONSTRUKTORY PROTECTED
*/
//////////////////////////////////////////////////////////////////////////////
/*
FUNKCJE PUBLIC PROTECTED
*/
//////////////////////////////////////////////////////////////////////////////
/*
SETTERY PROTECTED
*/
//////////////////////////////////////////////////////////////////////////////
/*
GETTERY PROTECTED
*/
//////////////////////////////////////////////////////////////////////////////
/*
OPERATORY PROTECTED
*/
//JEDNOARGUMENTOWE
//////////////////////////////////////////////////////////////////////////////
public:
/*
ZMIENNE PUBLIC
*/
//////////////////////////////////////////////////////////////////////////////
/*
KONSTRUKTORY PUBLIC
*/
_MORSE_BEEP(); //konstruktor bezparametrowy
explicit _MORSE_BEEP(const std::string & name_morse); //konstruktor z jednym parametrem
explicit _MORSE_BEEP(const _MORSE_BEEP & Object); //konstruktor kopiujacy
//////////////////////////////////////////////////////////////////////////////
/*
FUNKCJE PUBLIC
*/
virtual void ExternalInfo(const std::string & chain) override; //Funkcja otrzymujaca "ExterlanInfo" z fabryki i ustawiajaca nasze zmienne
virtual void Morse_Feature(const std::string & from_Converter_fun) override; //Funkcja ktora tworzy nasz chciany produkt(tutaj sygnaly dzwiekowe)
void Beep_fun(const int time) const noexcept; //funkcja "Beepania"
void Pause_fun(const int time) const noexcept; //funkcja pauzy
//////////////////////////////////////////////////////////////////////////////
/*
SETTERY PUBLIC
*/
void setFrequency(int __Freq); //setter czestotliwosci
void setPause(int __Pause); //setter pauzy miedzy . lub -
void setDotTime(int __DotTime); //setter dlugosci .
void setDashTime(int __DashTime); //setter dlugosci -
void setCharPause(int __CharPause); //setter pauzy miedzy znakami np. S (charpause) O (charpause) S
//////////////////////////////////////////////////////////////////////////////
/*
GETTERY PUBLIC
*/
virtual const std::string & get_name_morse(void) const; //getter nazwy morsa
const int get__Freq(void) const; //getter zwracajacy czestotliwosc
const int get__Pause(void) const; //getter zwracajacy pauze
const int get__DotTime(void) const; //getter zwracajacy dlugosc .
const int get__DashTime(void) const; //getter zwracajacy dlugosc -
const int get__CharPause(void) const; //getter zwracajacy dlugosc pauzy miedzy znakami
//////////////////////////////////////////////////////////////////////////////
/*
OPERATORY PUBLIC
*/
//JEDNOARGUMENTOWE
_MORSE_BEEP & operator=(const _MORSE_BEEP & Object); //operator przypisania
//////////////////////////////////////////////////////////////////////////////
/*
DESTRUKTOR
*/
virtual ~_MORSE_BEEP(); //wirtualny destruktor
//////////////////////////////////////////////////////////////////////////////
};
#endif /* _MORSE_BEEP_H_ */ | true |
0a7f6f0432377b5fee8dc7f28210eb6225f34577 | C++ | AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen | /GPU Pro1/02_Geometry Manipulation/02_Rule-based Geometry/RuleBasedGeometry/ModuleOperation.h | UTF-8 | 3,821 | 2.6875 | 3 | [
"MIT"
] | permissive | /*
**********************************************************************
* Demo program for
* Rule-based Geometry Synthesis in Real-time
* ShaderX 8 article.
*
* @author: Milan Magdics
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted for any non-commercial programs.
*
* Use it for your own risk. The author(s) do(es) not take
* responsibility or liability for the damages or harms caused by
* this software.
**********************************************************************
*/
#pragma once
#pragma warning(disable:4995) // disable warnings indicating deprecated codes in cstdio
#include <vector>
#include <map>
#pragma warning(default:4995)
#include "GrammarBasicTypes.h"
////////////////////////////////////////////////////////////////////
// OperatorParameter struct - represents a parameter of an operator
////////////////////////////////////////////////////////////////////
struct OperatorParameter
{
AttributeName name;
AttributeType type;
bool isRequired;
OperatorParameter():isRequired(true) {}
};
typedef std::vector<OperatorParameter> OperatorParameterVector;
typedef std::map<AttributeName,unsigned int> OperatorParameterMap;
//////////////////////////////////////////////////////////////////////
// OperatorSignature struct - represents the signature of an operator
//////////////////////////////////////////////////////////////////////
struct OperatorSignature
{
// we store parameters both in a vector (to determine their order) and a map (for faster search)
// TODO: it would be much more clever to use indices only in the map :)
OperatorParameterVector parameters;
OperatorParameterMap parameterMap;
// true if the return value of the implemented operator depends on the parent (predecessor) module
bool useParent;
OperatorSignature():useParent(false) {}
void addParameter( const OperatorParameter& parameter )
{
parameters.push_back(parameter);
parameterMap[parameter.name] = parameters.size()-1;
}
unsigned int parameterNumber() const { return parameters.size(); }
OperatorParameter& getParameter( unsigned int index ) { return parameters[index]; }
OperatorParameter& getParameter( const AttributeName& attributeName ) { return getParameter(parameterMap[attributeName]); }
bool hasParameter( const AttributeName& attributeName ) const { return parameterMap.count(attributeName) > 0; }
unsigned int getParameterIndex( const AttributeName& attributeName ) { return parameterMap[attributeName]; }
void clear() { parameters.clear(); parameterMap.clear(); }
};
/////////////////////////////////////////////////////////////////////
// ModuleOperation class
// - represents operators (calls) with their actual parameter values
/////////////////////////////////////////////////////////////////////
const unsigned int maxParameters = 30;
class ModuleOperation
{
public:
ModuleOperation(void);
~ModuleOperation(void);
String& getParameter( unsigned int index ) { return parameterValues[index]; }
String& getAnimationMin( unsigned int index ) { return animationMin[index]; }
String& getAnimationMax( unsigned int index ) { return animationMax[index]; }
String& getPeriodLength( unsigned int index ) { return period_length[index]; }
String& getRandomMin( unsigned int index ) { return randomMin[index]; }
String& getRandomMax( unsigned int index ) { return randomMax[index]; }
public:
OperatorName operatorName;
bool animated;
bool randomized;
protected:
String parameterValues[maxParameters];
String animationMin[maxParameters];
String animationMax[maxParameters];
String period_length[maxParameters];
String randomMin[maxParameters];
String randomMax[maxParameters];
};
// a sequence of operators is represented as a vector
typedef std::vector<ModuleOperation> ModuleOperationVector;
| true |
656aa3837abcd0075c8719fa6275404031642a7e | C++ | Renleilei1992/Live_platform | /Junk/PracticeCpp/func14_addNum.cpp | UTF-8 | 336 | 2.78125 | 3 | [] | no_license |
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc,char **argv)
{
int i = 10;
int j = 0;
cout<<"Plz input the num: ";
cin>>j;
int ans = j/i;
cout<<"Answer= ["<<ans<<"]"<<endl;
ans = 11%1;
cout<<"Answer= ["<<ans<<"]"<<endl;
ans = -1078;
cout<<"abs(ans)= ["<<abs(ans)<<"]"<<endl;
return 0;
}
| true |
ad1476bfc5059d4151da9ac546e995c25648ac93 | C++ | oceancx/mhxy | /include/Astar.h | WINDOWS-1252 | 811 | 2.609375 | 3 | [] | no_license | #pragma once
#include "GameMap.h"
#include <string>
#include <list>
class Astar
{
public:
struct MapNode
{
int x, y;
int F, G, H;
MapNode* parant;
};
Astar();
~Astar();
MapNode *mPs, *mPe;
std::list<MapNode*> mOpenList;
std::list<MapNode*> mCloseList;
// J K L I
int dir_x[8] = { 0, 1, 0, -1, 1, 1, -1, -1 };
int dir_y[8] = { -1, 0, 1, 0,-1, 1, 1,-1 };
MapNode* NewNode(int x, int y);
void PrintMap(std::string filename, int w, int h, int** mMap);
bool IsInCloseList(int x, int y);
bool IsInOpenList(int x, int y);
std::list<MapNode*>::iterator FindInOpenList(int x, int y);
std::list<MapNode*>::iterator PopLowestF();
bool PathFinding(int sx, int sy, int ex, int ey, int width, int height, int** map,
std::list<GameMap::Pos>& posList);
};
| true |
cee6df019bc4bcf73c5c6cad551e7482032bb426 | C++ | pgoodman/Grail-Plus | /grail/include/cfg/compute_follow_set.hpp | UTF-8 | 2,442 | 2.53125 | 3 | [
"MIT"
] | permissive | /*
* compute_follow_set.hpp
*
* Created on: Jan 25, 2012
* Author: petergoodman
* Version: $Id$
*/
#ifndef Grail_Plus_COMPUTE_FOLLOW_SET_HPP_
#define Grail_Plus_COMPUTE_FOLLOW_SET_HPP_
#include <cassert>
#include <vector>
#include "fltl/include/CFG.hpp"
namespace grail { namespace cfg {
/// compute the follow sets for a CFG.
template <typename AlphaT>
void compute_follow_set(
const fltl::CFG<AlphaT> &cfg,
const std::vector<bool> &nullable,
const std::vector<std::vector<bool> *> &first,
std::vector<std::vector<bool> *> &follow
) throw() {
FLTL_CFG_USE_TYPES(fltl::CFG<AlphaT>);
follow.assign(cfg.num_variables_capacity() + 2, 0);
variable_type V;
variable_type A;
symbol_string_type s;
generator_type variables(cfg.search(~V));
generator_type syms_following_V(cfg.search((~A) --->* cfg.__ + V + ~s));
// initialize each follow bitset as the empty set of the appropriate
// size.
for(; variables.match_next(); ) {
follow[V.number()] = new std::vector<bool>(cfg.num_terminals() + 2U, false);
}
for(bool updated(true); updated; ) {
updated = false;
for(variables.rewind(); variables.match_next(); ) {
for(syms_following_V.rewind(); syms_following_V.match_next(); ) {
for(unsigned i(0); i < s.length(); ++i) {
if(s.at(i).is_terminal()) {
terminal_type u(s.at(i));
(*(follow[V.number()]))[u.number()] = true;
goto next_production;
}
variable_type U(s.at(i));
if(U == V) {
continue;
}
updated = detail::union_into(follow[V.number()], first[U.number()]) || updated;
if(!nullable[U.number()]) {
goto next_production;
}
}
// reached the end of the production
updated = detail::union_into(follow[V.number()], first[A.number()]) || updated;
next_production:
continue;
}
}
}
}
}}
#endif /* Grail_Plus_COMPUTE_FOLLOW_SET_HPP_ */
| true |
65ec6b3b2604f9bd5f0ca8afbb893864f501cf91 | C++ | tarunluthra123/Competitive-Programming | /CP Online - CB/Recursion/N-Queen Hard.cpp | UTF-8 | 889 | 3.46875 | 3 | [] | no_license | /*
N-QUEEN HARD
You are given an empty chess board of size N*N. Find the number of ways to place N queens on the board, such that no two queens can kill each other in one move. A queen can move vertically, horizontally and diagonally.
Input Format:
A single integer N, denoting the size of chess board.
Constraints:
1 = N < 15
Output Format
A single integer denoting the count of solutions.
Sample Input
4
Sample Output
2
*/
#include <iostream>
using namespace std;
int n;
int ans = 0;
int DONE;
void solve(int rowMask, int ld, int rd) {
if(rowMask == DONE) {
ans++;
return ;
}
int safe = DONE&(~(rowMask|ld|rd));
while(safe) {
int p = safe&(-safe) ;
safe = safe - p;
solve(rowMask|p, (ld|p)<<1, (rd|p)>>1);
}
}
int main() {
cin >> n;
DONE = (1<<n) - 1;
solve(0,0,0);
cout << ans;
return 0;
}
| true |
e54dc2f55a3b9af53d202a9119be9e3b1e43c30b | C++ | jinsub1999/cppAlgorithm | /programmers/MonthlyCodeChallS2/2/3.cpp | UTF-8 | 2,874 | 2.9375 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
vector<string> solution(vector<string> s)
{
vector<string> answer;
for (auto elem : s)
{
string prev = "";
stack<char> St;
stack<char> Qu;
int count110 = 0;
for (auto it = elem.rbegin(); it != elem.rend(); it++)
St.push(*it);
while (St.size() >= 3)
{
string part = "";
part += St.top();
St.pop();
part += St.top();
St.pop();
part += St.top();
St.pop();
if (part == "110")
{
for (int i = 0; i < 2; i++)
{
if (Qu.empty())
continue;
St.push(Qu.top());
Qu.pop();
}
count110++;
}
else
{
St.push(part[2]);
St.push(part[1]);
Qu.push(part[0]);
}
}
while (!Qu.empty())
{
prev += Qu.top();
Qu.pop();
}
reverse(prev.begin(), prev.end());
while (!St.empty())
{
prev += St.top();
St.pop();
}
bool flag = true;
for (int i = 0; i < prev.length(); i++)
{
if (prev[i] == '0')
flag = false;
}
if (flag)
{
string s110 = "";
while (count110--)
s110 += "110";
answer.push_back(s110 + prev);
}
else
{
int countOne = 0;
string s110 = "";
bool found = false;
string ANS = "";
while (count110--)
s110 += "110";
for (int i = 0; i < prev.length(); i++)
{
if (prev[i] == '1')
{
countOne++;
if (countOne == 3)
{
ANS = string(prev.begin(), prev.begin() + i - 2) + s110 + string(prev.begin() + i - 2, prev.end());
found = true;
break;
}
}
else
{
countOne = 0;
}
}
if (!found)
{
ANS = string(prev.begin(), prev.end() - countOne) + s110 + string(prev.end() - countOne, prev.end());
}
answer.push_back(ANS);
}
}
return answer;
}
int main(void)
{
auto V = solution({"10110", "01110", "0111110110", "10111111100"});
string S = "123456";
cout << S.substr(2) << '\n';
cout << S.substr(2, 3) << '\n';
} | true |
e97ddda3f97dff8e4eb01e713846b4d9a23445ec | C++ | salmandotexe/Codeforces | /George and Accommodation.cpp | UTF-8 | 266 | 2.75 | 3 | [] | no_license | //https://codeforces.com/problemset/problem/467/A
#include <iostream>
using namespace std;
int main()
{
int n,a,b;
cin >> n;
int res=0;
while(n--)
{
cin >> a >> b;
if(b-a>=2)
res++;
}
cout << res << endl;
}
| true |
8dae9e3c5e0335d8ba10972bc24280a08fb0da79 | C++ | muktadirkhan889/cp-practice | /leetcode/number-of-steps-to-reduce-a-number-to-zero.cpp | UTF-8 | 566 | 3.703125 | 4 | [] | no_license | /* https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero */
// Recursive
class Solution {
public:
int numberOfSteps (int num) {
if(num==0) {
return 0;
}
return 1 + numberOfSteps(num%2==0 ? num/2 : num-1);
}
};
// Iterative
class Solution {
public:
int numberOfSteps (int num) {
int count = 0;
while(num>0) {
if(num%2==0) {
num/=2;
} else {
num-=1;
}
count++;
}
return count;
}
};
| true |
8445c1f675f43d7aa3f50f63da56811614ee35cd | C++ | Meeeeeow/Sorting_Algorithms | /Codeforces-800/BoringApartments.cpp | UTF-8 | 410 | 2.625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(void)
{
int t;
cin>>t;
while(t--)
{
string s;
int sum =0;
cin>>s;
if(s.size()<4)
{
sum +=((s[0]-'0')-1)*10;
for(int i=1;i<=s.size();i++)
sum+=i;
cout<<sum<<endl;
}
else
cout<<((s[0]-'0')*10)<<endl;
}
return 0;
}
| true |
11f9ac60bc1440e45f89ced2c4247c7cedcc6de0 | C++ | xusx1024/cpp-learning | /练习/4.9练习.cpp | UTF-8 | 1,454 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
/* 4.28
cout << "int:"<< sizeof(int) << endl;
cout << "char:"<< sizeof(char) << endl;
cout << "long:"<< sizeof(long) << endl;
cout << "short:"<< sizeof(short) << endl;
cout << "double:"<< sizeof(double) << endl;
cout << "boolean:"<< sizeof(bool) << endl;
cout << "wchar_t:"<< sizeof(wchar_t) << endl;
cout << "char16_t:"<< sizeof(char16_t) << endl;
cout << "char32_t:"<< sizeof(char32_t) << endl;
cout << "long long:"<< sizeof(long long) << endl;
cout << "float:"<< sizeof(float) << endl;
cout << "long double:"<< sizeof(long double) << endl;
*/
/*4.29
int x[10];
int *p = x;
cout << sizeof(x) / sizeof(*x) << endl;//40 / 4 = 10
cout << sizeof(p) / sizeof(*p) << endl;//4 / 4 = 1
// int 每个元素占4个字节,32位. 10个元素一共40个字节. *x是数组的第一个元素,占4个字节.
// x对象是有10个int元素的数组,占40个字节
// 指针是int类型,所以占4个字节
// 指针解引用,指向的是x数组的首个int元素,占4个字节
*/
// 4.30 sizeof满足右结合律
(a) sizeof x + y 等价于 (sizeof x)+y
(b) sizeof p->mem[i] 等价于 sizeof (p -> mem[i])
(c) sizeof a < b 等价于 (sizeof a) < b
(d) sizeof f() 等价于 sizeof (f())
return 0;
}
| true |
0fbc8f210d134ba954d38f4f9f17fd3020212bc8 | C++ | momchiltues19/Classroom | /oop/copy_constructor.cpp | UTF-8 | 1,603 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <exception>
using namespace std;
class Stack
{
const static int chunk_ = 2;
int size_;
int *data_;
int top_;
public:
Stack()
: size_(chunk_), data_(new int[chunk_]), top_(-1) {}
Stack(const Stack& other)
: top_(other.top_), size_(other.size_), data_(new int[size_])
{
cout << "copying" << endl;
for (int i = 0; i <= top_; ++i)
{
data_[i] = other.data_[i];
}
}
~Stack()
{
cout << "destroying" << endl;
delete [] data_;
}
Stack& operator=(const Stack& other)
{
if(this != other)
{
delete [] data_;
top_ = other.top_;
size_ = other.size_;
data_ = new int [size_];
for(int i = 0; i <= top_; ++i)
{
data_[i] = other.data_[i];
}
}
return *this;
}
bool empty() const {
return top_ == -1;
}
void push(int v)
{
if (top_ >= (size_-1))
{
resize();
}
data_[++top_] = v;
}
int pop()
{
if(top_ < 0)
{
throw exception();
}
return data_[top_--];
}
private:
void resize()
{
int *temp = data_;
data_ = new int[chunk_ + size_];
for(int i = 0; i < size_; i++)
{
data_[i] = temp[i];
}
delete [] temp;
size_ += chunk_;
}
};
int sum(Stack st)
{
int s = 0;
while(!st.empty())
{
s += st.pop();
}
return s;
}
int main()
{
Stack mystk;
for(int i = 0; i < 10; i++)
{
mystk.push(i);
}
cout << sum(mystk) << endl;
Stack stk;
stk = mystk;
cout << sum(stk) << endl;
try
{
while (!mystk.empty())
{
cout << mystk.pop() << endl;
}
} catch (const exception & e) {
cout << "sth went wrong" << endl;
}
return 0;
}
| true |
86c167bdc50defadf7d967545a2e580c80e7e0dd | C++ | yenluu2506/C | /LapTrinhC/Quan Ly Sinh Vien KTX.cpp | UTF-8 | 9,683 | 2.703125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<windows.h>
/*struct Sinhvien {
char masinhvien[30];
char hoten[30];
char gioitinh[40];
char noisinh[30];
int namsinh;
int sohopdong;
};
void nhap(Sinhvien* sinhvien);
void xuat(Sinhvien* sinhvien);
void nhap(Sinhvien*& danhsach, int& soluong);
void xuat(Sinhvien* danhsach, int soluong);
void sapXepTheoTinh(Sinhvien* danhsach, int soluong);
void hienthiThongtin(Sinhvien* danhsach, int soluong);
void thongKeTheoTinh(Sinhvien* danhsach, int soluong);
void sapXepTheoTen(Sinhvien* danhsach, int soluong);
void timKiemTheoTinh(Sinhvien* danhsach, int soluong);
void ghiFile(Sinhvien* danhsach, int soluong);
void menu(Sinhvien* danhsach, int soluong);
void SetColor(WORD color);
void pressAnyKey();
int main() {
Sinhvien* danhsach;
int soluong;
system("color 73");
SetColor(76);
menu(danhsach, soluong);
free(danhsach);
}
void SetColor(WORD color) {
HANDLE hConsoleOutput;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
GetConsoleScreenBufferInfo(hConsoleOutput, &screen_buffer_info);
WORD wAttributes = screen_buffer_info.wAttributes;
color &= 0x000f;
wAttributes &= 0xfff0; wAttributes |= color;
SetConsoleTextAttribute(hConsoleOutput, wAttributes);
}
void nhap(Sinhvien* sinhvien) {
fflush(stdin);
printf("\n--Thong tin sinh vien--");
printf("\n");
printf("\nHo va Ten: ");
gets_s(sinhvien->hoten);
printf("Ma sinh vien: ");
gets_s(sinhvien->masinhvien);
printf("Gioi tinh: ");
gets_s(sinhvien->gioitinh);
printf("Noi sinh: ");
gets_s(sinhvien->noisinh);
printf("Nam sinh: ");
scanf_s("%d", &sinhvien->namsinh);
printf("So hop dong: ");
scanf_s("%d", &sinhvien->sohopdong);
}
void xuat(Sinhvien* sinhvien) {
fflush(stdin);
printf("\n--Thong tin sinh vien da nhap--");
printf("\n");
printf("\nHo va Ten: %s", sinhvien->hoten);
printf("\nMa sinh vien: %s", sinhvien->masinhvien);
printf("\nGioi tinh: %s", sinhvien->gioitinh);
printf("\nNoi sinh: %s", sinhvien->noisinh);
printf("\nNam sinh: %d", sinhvien->namsinh);
printf("\nSo hop dong: %d", sinhvien->sohopdong);
}
void nhap(Sinhvien*& danhsach, int& soluong) {
danhsach = (Sinhvien*)malloc(soluong * sizeof(Sinhvien));
for (int i = 0; i < soluong; i++) {
printf("\nNhap sinh vien thu %d: \n", i + 1);
nhap(&*(danhsach + i));
}
}
void xuat(Sinhvien* danhsach, int soluong) {
printf("\n---Danh sach sinh vien---");
printf("\n");
for (int i = 0; i < soluong; i++) {
printf("\nSinh vien thu: %d", i + 1);
xuat(danhsach + i);
}
}
void hienthiThongtin(Sinhvien* danhsach, int soluong) {
for (int i = 0; i < soluong; i++) {
printf("\n%-15s %-15s %-15d %-15s %-15s %-15d\n", (danhsach + i)->masinhvien, (danhsach + i)->hoten, (danhsach + i)->namsinh, (danhsach + i)->gioitinh, (danhsach + i)->noisinh, (danhsach + i)->sohopdong);
}
}
void sapXepTheoTinh(Sinhvien* danhsach, int soluong) {
Sinhvien tam;
for (int i = 0; i < soluong - 1; i++) {
for (int j = i + 1; j < soluong; j++) {
if (strcmp((danhsach + i)->noisinh, (danhsach + j)->noisinh) < 0) {
tam = *(danhsach + i);
*(danhsach + i) = *(danhsach + j);
*(danhsach + j) = tam;
}
}
}
}
void thongKeTheoTinh(Sinhvien* danhsach, int soluong) {
sapXepTheoTinh(danhsach, soluong);
int dem = 1;
for (int i = 0; i < soluong; i++) {
if (strcmp((danhsach + i)->noisinh, (danhsach + i + 1)->noisinh) == 0) {
dem++;
}
else {
printf("\n%s co %d sinh vien", (danhsach + i)->noisinh, dem);
dem = 1;
}
}
}
void sapXepTheoTen(Sinhvien* danhsach, int soluong) {
Sinhvien tam;
for (int i = 0; i < soluong; i++) {
for (int j = i + 1; j < soluong; j++) {
if (strcmp((danhsach + i)->hoten, (danhsach + j)->hoten) > 0) {
tam = *(danhsach + i);
*(danhsach + i) = *(danhsach + j);
*(danhsach + j) = tam;
}
}
}
}
void timKiemTheoTinh(Sinhvien* danhsach, int soluong) {
char tentinh[20];
printf("\nNhap ten tinh: ");
fflush(stdin);
gets_s(tentinh);
int tim = 0;
for (int i = 0; i < soluong; i++) {
if (strcmp(tentinh, ((danhsach + i)->noisinh)) == 0) {
tim++;
if (tim == 1) {
printf("\n%-15s %-15s %-15s %-15s %-15s %-15s\n", "Ma sinh vien", "Ho va Ten", "Nam sinh", "Gioi tinh", "Noi sinh", "So hop dong");
}
hienthiThongtin(danhsach + i, 1);
}
}
if (tim == 0) {
printf("\nKhong tim thay sinh vien theo tinh %s nhu yeu cau.", tentinh);
}
}
void ghiFile(Sinhvien* danhsach, int soluong) {
getchar();
char fName[26];
char fPath[100] = "./src/data/";
printf("\nNhap ten file: ");
gets_s(fName);
printf("\n");
strcat(fPath, fName);
printf("%s", fPath);
FILE* fOut = fopen(fPath, "wb");
for (int i = 0; i < soluong; i++) {
fprintf(fOut, "%-15s %-10s %-10d %-10s %-10s %-10d\n", (danhsach + i)->masinhvien, (danhsach + i)->hoten, (danhsach + i)->namsinh, (danhsach + i)->gioitinh, (danhsach + i)->noisinh, (danhsach + i)->sohopdong);
}
fclose(fOut);
}
void pressAnyKey() {
printf("\n\nBam phim bat ky de tiep tuc...");
getch();
system("cls");
}
void menu(Sinhvien* danhsach, int soluong) {
int key;
int flat = 1;
bool daNhap = false;
do {
printf("\nNhap so luong Sinh Vien: ");
scanf_s("%d", &soluong);
} while (soluong <= 0);
while (flat) {
system("cls");
printf("***************************************************************************\n");
printf("** CHUONG TRINH QUAN LY SINH VIEN KTX **\n");
printf("** 1. Nhap du lieu **\n");
printf("** 2. In danh sach sinh vien **\n");
printf("** 3. Sap xep thong ke va hien thi thong tin sinh vien theo tinh. **\n");
printf("** 4. Sap xep va hien thi thong tin sinh vien theo ten. **\n");
printf("** 5. Tim sinh vien theo tinh. **\n");
printf("** 6. Ghi vao tap tin nhi phan **\n");
printf("** 0. Thoat **\n");
printf("***************************************************************************\n");
printf("** Nhap lua chon cua ban **\n");
scanf_s("%d", &key);
switch (key) {
case 1:
printf("\nBan da chon nhap danh sach Sinh Vien!");
printf("\n");
nhap(danhsach, soluong);
printf("\nBan da nhap thanh cong!");
printf("\n");
daNhap = true;
pressAnyKey();
break;
case 2:
if (daNhap) {
printf("\nBan da chon xuat DS sinh vien!");
xuat(danhsach, soluong);
}
else {
printf("\nNhap danh sach Sinh Vien truoc!!!!");
}
pressAnyKey();
break;
case 3:
if (daNhap) {
printf("\nBan da chon sap sep thong ke va hien thi thong tin chi tiet cua tung sinh vien theo tinh.\n");
printf("\n");
printf("\n%-15s %-15s %-15s %-15s %-15s %-15s\n", "Ma sinh vien", "Ho va Ten", "Nam sinh", "Gioi tinh", "Noi sinh", "So hop dong");
sapXepTheoTinh(danhsach, soluong);
hienthiThongtin(danhsach, soluong);
thongKeTheoTinh(danhsach, soluong);
}
else {
printf("\nNhap danh sach Sinh Vien truoc!!!!");
}
pressAnyKey();
break;
case 4:
if (daNhap) {
printf("\nBan da chon sap xep theo ten!");
printf("\n");
printf("\n%-15s %-15s %-15s %-15s %-15s %-15s\n", "Ma sinh vien", "Ho va Ten", "Nam sinh", "Gioi tinh", "Noi sinh", "So hop dong");
sapXepTheoTen(danhsach, soluong);
hienthiThongtin(danhsach, soluong);
}
else {
printf("\nNhap danh sach Sinh Vien truoc!!!!");
}
pressAnyKey();
break;
case 5:
if (daNhap) {
printf("\nBan da chon tim sinh vien theo tinh.");
timKiemTheoTinh(danhsach, soluong);
}
else {
printf("\nNhap danh sach Sinh Vien truoc!!!!");
}
pressAnyKey();
break;
case 6:
if (daNhap) {
printf("\nBan da chon ghi vao tap tin nhi phan");
ghiFile(danhsach, soluong);
}
else {
printf("\nNhap danh sach Sinh Vien truoc!!!!");
}
pressAnyKey();
break;
default:
printf("\nKhong co chuc nang nay!");
printf("\nBam phim bat ky de tiep tuc!");
printf("\n");
getch();
break;
case 0:
printf("\nBan da chon thoat chuong trinh!");
flat = 0;
false;
}
}
}*/ | true |
58d970da7e015b570068fd5656c299c9cf4a5d10 | C++ | malharDeshpande/bu-met | /cs789/lib/BigUnsigned.h | UTF-8 | 2,250 | 3.359375 | 3 | [] | no_license | #ifndef TGL_BIGUNSIGNED_H
#define TGL_BIGUNSIGNED_H
#include <ostream>
#include <vector>
#include <string>
namespace tgl {
/// Describe an unsigned of many many digits
class BigUnsigned {
public:
enum Comparison { less = -1, equal = 0, greater = 1 };
// Default constructor
BigUnsigned();
/// Construct from an unsigned long.
BigUnsigned(unsigned long n);
/// Constructor from a std::string
BigUnsigned(const std::string &str);
/// Copy constructor
BigUnsigned(const BigUnsigned &x);
/// Assignment operator
void operator=(const BigUnsigned &x);
Comparison compareTo(const BigUnsigned &x) const;
/// Equality operator
bool operator==(const BigUnsigned &x) const;
/// Imequality operator
bool operator!=(const BigUnsigned &x) const {
return !operator ==(x);
};
bool operator<(const BigUnsigned &x) const { return compareTo(x) == less; };
bool operator<=(const BigUnsigned &x) const { return compareTo(x) != greater; };
bool operator>=(const BigUnsigned &x) const { return compareTo(x) != less; };
bool operator>(const BigUnsigned &x) const { return compareTo(x) == greater; };
void operator++();
void operator++(int);
void operator--();
void operator--(int);
void add(const BigUnsigned &a, const BigUnsigned &b);
void subtract(const BigUnsigned &a, const BigUnsigned &b);
void multiply(const BigUnsigned &a, const BigUnsigned &b);
void modWithQuotient(const BigUnsigned &b, BigUnsigned &x);
void zapLeadingZeros();
size_t length() const { return _value.size(); };
/// Return value at index, does not check for overrun of std::vector!
unsigned long value(size_t index) const { return _value[index]; };
/// Set to zero.
void zero() { _value.clear(); };
bool isZero() const;
protected:
private:
std::vector<unsigned long> _value;
friend std::ostream &operator<<(std::ostream &out, const BigUnsigned &x);
};
std::string convert2str(const BigUnsigned &x);
inline std::ostream &operator<<(std::ostream &out, const BigUnsigned &x) {
std::string s = convert2str(x);
out << s;
return out;
}
}
#endif // #ifndef TGL_BIGUNSIGNED_H
| true |
a4cd423e9e31449d4ba95577dd0ea486166e5f0d | C++ | rdmytruk/BasicGame | /BasicGame/RenderContext.cpp | UTF-8 | 6,322 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "RenderContext.h"
#include <GL/glew.h>
#include <GL\wglew.h>
#include "WindowsWrapper.h"
RenderContext::RenderContext()
{
this->glrc = nullptr;
this->hdc = nullptr;
this->hinstance = nullptr;
this->hwnd = nullptr;
}
bool RenderContext::CreateApplicationWindow(glm::ivec2 position, glm::ivec2 resolution)
{
const wchar_t * className = L"BasicGame C++ YEG demo RDmytruk";
const wchar_t * titleName = L"Basic Game Demo";
WNDCLASS wc; // Window class structure
DWORD dwExStyle; // Window extended style
DWORD dwStyle; // Window style
// Windows screen coordinates are left->right, top->bottom
// OpenGL screen coordinates are left->right, bottom->top
RECT windowRect;
windowRect.left = static_cast<long>(position.x);
windowRect.right = static_cast<long>(position.x + resolution.x);
windowRect.top = static_cast<long>(position.y);
windowRect.bottom = static_cast<long>(position.y + resolution.y);
hinstance = GetModuleHandle(NULL); // Grab an instance for the window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw on move, and own direct context for the window
wc.lpfnWndProc = WindowsWrapper::WndProc; // WndProc handles messages
wc.cbClsExtra = 0; // No extra window data
wc.cbWndExtra = 0; // No extra window data
wc.hInstance = hinstance; // Set the instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load the default icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load the default arrow pointer
wc.hbrBackground = NULL; // No background required (we paint ourselves)
wc.lpszMenuName = NULL; // No menu
wc.lpszClassName = className; // Set the class name
// Register the class
if (!RegisterClass(&wc))
{
MessageBox(NULL, TEXT("Failed to register the window class."), TEXT("ERROR"), MB_OK | MB_ICONINFORMATION);
return FALSE;
}
dwExStyle = WS_EX_APPWINDOW; // Window extended style
//dwStyle = WS_OVERLAPPEDWINDOW; // Windows style
dwStyle = WS_OVERLAPPED |
WS_CAPTION |
WS_SYSMENU |
WS_THICKFRAME | // disabled resizing borders
WS_MINIMIZEBOX |
WS_MAXIMIZEBOX;
// calculates how large of a window we should request based off of our target resolution
AdjustWindowRectEx(
&windowRect,
dwStyle,
FALSE, // No windows menu
dwExStyle); // Adjust window to requested size
if (!(hwnd = CreateWindowEx(
dwExStyle, // Extended style for the window
className, // Class name
titleName, // Window title
WS_CLIPSIBLINGS | WS_CLIPCHILDREN | dwStyle, // Required, required, selected windows style
windowRect.left, // Window x-pos
windowRect.top, // Window y-pos
windowRect.right - windowRect.left, // Adjusted window width
windowRect.bottom - windowRect.top, // Adjusted window height
NULL, // No parent window
NULL, // No menu
hinstance, // Instance
NULL))) // Don't pass anything to WM_CREATE
{
KillGLWindow(); // Reset the display
MessageBox(NULL, TEXT("Window creation error."), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}
return true;
}
bool RenderContext::CreateGLWindow()
{
BYTE bits_per_pixel = 32;
BYTE depth_buffer_bits = 24;
BYTE stencil_buffer_bits = 0;
static PIXELFORMATDESCRIPTOR pfd = // pfd tells windows how we want things to be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size of this pixel format descriptor
1, // Version number
PFD_DRAW_TO_WINDOW | // Format must support window
PFD_SUPPORT_OPENGL | // Format must support OpenGL
PFD_DOUBLEBUFFER, // Must support double buffering
PFD_TYPE_RGBA, // Request an RGBA format
bits_per_pixel, // Select our color depth
0, 0, 0, 0, 0, 0, // Color bits ignored
8, // 8-bit alpha buffer
0, // Shift bit ignored
0, // No accumulation buffer
0, 0, 0, 0, // Accumulation bits ignored
depth_buffer_bits, // depth buffer bits
stencil_buffer_bits, // stencil buffer bits
0, // No auxiliary buffer
PFD_MAIN_PLANE, // Main drawing layer
0, // Reserved
0, 0, 0 // Layer masks ignored
};
// Get device context
if (!(hdc = GetDC(hwnd)))
{
KillGLWindow();
MessageBox(NULL, TEXT("Can't create a GL device context."), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION);
return false;
}
// Windows chooses pixel format
int pixel_format;
if (!(pixel_format = ChoosePixelFormat(hdc, &pfd)))
{
KillGLWindow();
MessageBox(NULL, TEXT("Can't find a suitable PixelFormat."), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION);
return false;
}
// Set pixel format
if (!SetPixelFormat(hdc, pixel_format, &pfd))
{
KillGLWindow();
MessageBox(NULL, TEXT("Can't set the PixelFormat."), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION);
return false;
}
// render context
if (!(glrc = wglCreateContext(hdc)))
{
KillGLWindow();
MessageBox(NULL, TEXT("Can't create a GL rendering context."), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION);
return false;
}
if (!wglMakeCurrent(hdc, glrc))
{
KillGLWindow();
MessageBox(NULL, TEXT("Can't activate the GL rendering context."), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION);
return false;
}
// initialize glew
glewExperimental = GL_TRUE;
GLenum error = glewInit();
return true;
}
void RenderContext::ShowApplicationWindow()
{
ShowWindow(hwnd, SW_SHOW); // show the window
SetForegroundWindow(hwnd); // slightly higher priority
SetFocus(hwnd); // sets input focus to the window
}
void RenderContext::KillGLWindow()
{
if (glrc)
{
// there is a render context
try
{
if (!wglMakeCurrent(NULL, NULL)) // Are we able to release the device and rendering contexts?
{
MessageBox(NULL, TEXT("Release of Device Context and Rendering Context Failed."), TEXT("SHUTDOWN ERROR"), MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(glrc)) // Are we able to delete the rendering context?
{
MessageBox(NULL, TEXT("Release Rendering Context Failed."), TEXT("SHUTDOWN ERROR"), MB_OK | MB_ICONINFORMATION);
}
}
catch (...)
{
// catch errors but for now don't care about reporting
}
glrc = nullptr;
}
}
void RenderContext::SwapBuffer()
{
SwapBuffers(hdc);
}
void RenderContext::SetVSync(bool enabled)
{
// requires wgl
if (enabled)
wglSwapIntervalEXT(1);
else
wglSwapIntervalEXT(0);
}
| true |
06b5c870fe508a892384fc08d39d985e42234b31 | C++ | Igoresku/Hermes | /src/Job_Queue.cpp | UTF-8 | 1,229 | 2.796875 | 3 | [] | no_license | //
// Created by Igor Duric on 11/25/19.
//
#include "../include/Job_Queue.h"
Job_Queue::Job_Queue() {
pthread_mutex_init(&mutex, nullptr);
pthread_cond_init(¬_empty, nullptr);
} /// Job_Queue : END
void Job_Queue::Add_Job(Job* job) {
RAII scope_key(&mutex);
auto new_job = new Job_List_Element(job);
if (head == nullptr)
head = new_job;
else
tail->next = new_job;
tail = new_job;
pthread_cond_broadcast(¬_empty);
} /// Add_Job : END
Job* Job_Queue::Get_Job() {
RAII scope_key(&mutex);
while (head == nullptr)
pthread_cond_wait(¬_empty, &mutex);
auto job = head->payload;
auto temp = head;
head = head->next;
if (head == nullptr)
tail = nullptr;
delete temp;
return job;
} /// Get_Job : END
Job_Queue::~Job_Queue() {
auto iterator = head;
Job_List_Element* scout;
while (iterator != tail) {
scout = iterator->next;
delete iterator->payload;
delete iterator;
iterator = scout;
}
if (iterator != nullptr) {
delete iterator->payload;
delete iterator;
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(¬_empty);
} /// Job_Queue : END | true |
9794c7030cca1d14ad6e70b7ede4e17f87d8e753 | C++ | Nguyenxuanthuan2409/BT_CSLT | /Bangcuuchuong2.cpp | UTF-8 | 245 | 2.65625 | 3 | [] | no_license | // ct in bang cuu chuong 2
#include<iostream>
#include <iomanip>
using namespace std;
int main ()
{
int d = 10;
int r = 5;
for ( int i = 1; i<= 10; i++)
{
cout << " 2 x " << i << " = " << 2 * i << endl;
}
system ("pause");
return 0;
} | true |
3eb379279f850afde8539d834c99ee3a005e16ef | C++ | NaufalF121/New-folder | /pemilu.cpp | UTF-8 | 477 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
class gfg
{
public :
unsigned long long gcd(unsigned long long a, unsigned long long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to return LCM of two numbers
unsigned long long lcm(unsigned long long a, unsigned long long b)
{
return (a*b)/gcd(a, b);
}
} ;
int main (){
gfg g;
unsigned long long a, b ;
cin >> a >> b;
cout << g.lcm(a, b) << endl;
}
| true |
09f47449fb9dba3b799a8ad50aebacf01dbe0567 | C++ | Aarati21/Leetcode | /148.cpp | UTF-8 | 705 | 3.09375 | 3 | [] | no_license | /*148. Sort List
Medium
2468
121
Add to List
Share
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
multiset <int> gq;
ListNode temp(0);
ListNode* newl = &temp;
while (head!=nullptr){
gq.insert(head->val);
head = head->next;
}
for (auto it = gq.begin(); it != gq.end(); it++){
newl->next = new ListNode(*it);
newl = newl->next;
}
return temp.next;
}
};
| true |
8a9da67296d7ebab779ad028777d76bdd12bb979 | C++ | fzls/OJ | /PAT/Advanced/1022/1022/source.cpp | UTF-8 | 11,977 | 2.640625 | 3 | [] | no_license | /*
+----------------------------------------------------------
*
* @authors: 风之凌殇 <fzls.zju@gmail.com>
* @FILE NAME: source.cpp
* @version: v1.0
* @Time: 2016-02-25 15:33:52
* @Description:
Logo 风之凌殇 [编辑资料] [登出]
主页
题目集
基本信息
题目列表
提交列表
排名
帮助
1022. Digital Library (30)
时间限制
1000 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
A Digital Library contains millions of books, stored according to their titles, authors, key words of their abstracts, publishers, and published years. Each book is assigned an unique 7-digit number as its ID. Given any query from a reader, you are supposed to output the resulting books, sorted in increasing order of their ID's.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the total number of books. Then N blocks follow, each contains the information of a book in 6 lines:
Line #1: the 7-digit ID number;
Line #2: the book title -- a string of no more than 80 characters;
Line #3: the author -- a string of no more than 80 characters;
Line #4: the key words -- each word is a string of no more than 10 characters without any white space, and the keywords are separated by exactly one space;
Line #5: the publisher -- a string of no more than 80 characters;
Line #6: the published year -- a 4-digit number which is in the range [1000, 3000].
It is assumed that each book belongs to one author only, and contains no more than 5 key words; there are no more than 1000 distinct key words in total; and there are no more than 1000 distinct publishers.
After the book information, there is a line containing a positive integer M (<=1000) which is the number of user's search queries. Then M lines follow, each in one of the formats shown below:
1: a book title
2: name of an author
3: a key word
4: name of a publisher
5: a 4-digit number representing the year
Output Specification:
For each query, first print the original query in a line, then output the resulting book ID's in increasing order, each occupying a line. If no book is found, print "Not Found" instead.
Sample Input:
3
1111111
The Testing Book
Yue Chen
test code debug sort keywords
ZUCS Print
2011
3333333
Another Testing Book
Yue Chen
test code sort keywords
ZUCS Print2
2012
2222222
The Testing Book
CYLL
keywords debug book
ZUCS Print2
2011
6
1: The Testing Book
2: Yue Chen
3: keywords
4: ZUCS Print
5: 2011
3: blablabla
Sample Output:
1: The Testing Book
1111111
2222222
2: Yue Chen
1111111
3333333
3: keywords
1111111
2222222
3333333
4: ZUCS Print
1111111
5: 2011
1111111
2222222
3: blablabla
Not Found
提交代码
*
+----------------------------------------------------------
*/
#define _CRT_SECURE_NO_DEPRECATE
#pragma comment(linker, "/STACK:66777216")
#include <algorithm>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <cstring>
#include <cstdio>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#pragma region DebugSetting
//#define DEBUG
#ifdef DEBUG
#define debug(format, ...) printf("[line:%d:@%s] "format, __LINE__, __FUNCTION__, ##__VA_ARGS__)
#else
#define debug(...)
#endif
#pragma endregion
//struct Book {
// int id;
// string title;
// string author;
// vector<string> keywords;
// string publisher;
// string year;
//};
//
//struct Title {
// string title;
// vector<int> ids;
//};
//struct Author {
// string author;
// vector<int> ids;
//};
//struct Keyword {
// string keyword;
// vector<int> ids;
//};
//struct Publisher {
// string publisher;
// vector<int> ids;
//};
//struct Year {
// string year;
// vector<int> ids;
//};
//enum CMD {
// TITLE = '1',
// AUTHOR = '2',
// KEY_WORD = '3',
// PUBLISHER = '4',
// YEAR = '5'
//};
//
//
//int main() {
// #pragma region GET_INPUT
// {
//#ifndef ONLINE_JUDGE
// freopen("test.in", "r", stdin);
// freopen("test.out", "w", stdout);
//#endif
// }
// #pragma endregion
// int n;
// cin >> n;
// vector<Book> books;
// vector<Title> titles;
// map<string, int> util_title;
// vector<Author> authors;
// map<string, int> util_author;
// vector<Keyword> keywords;
// map<string, int> util_keyword;
// vector<Publisher> publishers;
// map<string, int> util_publisher;
// vector<Year> years;
// map<string, int> util_year;
//
// for (int i = 0; i < n; ++i) {
// Book tmp;
// cin >> tmp.id;
// cin.ignore();
// getline(cin, tmp.title);
//
// if (util_title.find(tmp.title) != util_title.end()) {
// int index = util_title[tmp.title];
// titles[index].ids.push_back(tmp.id);
// } else {
// Title t;
// t.title = tmp.title;
// t.ids.push_back(tmp.id);
// titles.push_back(t);
// util_title[tmp.title] = titles.size() - 1;
// }
//
// getline(cin, tmp.author);
//
// if (util_author.find(tmp.author) != util_author.end()) {
// int index = util_author[tmp.author];
// authors[index].ids.push_back(tmp.id);
// } else {
// Author t;
// t.author = tmp.author;
// t.ids.push_back(tmp.id);
// authors.push_back(t);
// util_author[tmp.author] = authors.size() - 1;
// }
//
// //keywords
// string key_words;
// getline(cin, key_words);
// int pos, last = 0;
// string key_word;
//
// while ((pos = key_words.find(' ', last)) != -1) {
// key_word = key_words.substr(last, pos - last);
// tmp.keywords.push_back(key_word);
// last = pos + 1;
// }
//
// //last keyword
// key_word = key_words.substr(last);
// tmp.keywords.push_back(key_word);
//
// for (auto keyword : tmp.keywords) {
// if (util_keyword.find(keyword) != util_keyword.end()) {
// int index = util_keyword[keyword];
// keywords[index].ids.push_back(tmp.id);
// } else {
// Keyword t;
// t.keyword = keyword;
// t.ids.push_back(tmp.id);
// keywords.push_back(t);
// util_keyword[keyword] = keywords.size() - 1;
// }
// }
//
// getline(cin, tmp.publisher);
//
// if (util_publisher.find(tmp.publisher) != util_publisher.end()) {
// int index = util_publisher[tmp.publisher];
// publishers[index].ids.push_back(tmp.id);
// } else {
// Publisher t;
// t.publisher = tmp.publisher;
// t.ids.push_back(tmp.id);
// publishers.push_back(t);
// util_publisher[tmp.publisher] = publishers.size() - 1;
// }
//
// getline(cin, tmp.year);
//
// if (util_year.find(tmp.year) != util_year.end()) {
// int index = util_year[tmp.year];
// years[index].ids.push_back(tmp.id);
// } else {
// Year t;
// t.year = tmp.year;
// t.ids.push_back(tmp.id);
// years.push_back(t);
// util_year[tmp.year] = years.size() - 1;
// }
//
// books.push_back(tmp);
// }
//
// for (auto &title : titles) {
// sort(title.ids.begin(), title.ids.end());
// }
//
// for (auto &author : authors) {
// sort(author.ids.begin(), author.ids.end());
// }
//
// for (auto &keyword : keywords) {
// sort(keyword.ids.begin(), keyword.ids.end());
// }
//
// for (auto &publisher : publishers) {
// sort(publisher.ids.begin(), publisher.ids.end());
// }
//
// for (auto &year : years) {
// sort(year.ids.begin(), year.ids.end());
// }
//
// int m;
// cin >> m;
// cin.ignore();
//
// while (m--) {
// string query;
// vector<int> query_result;
// getline(cin, query);
// char cmd = query[0];
// string para = query.substr(3);
// int index;
//
// switch (cmd) {
// case TITLE:
// if (util_title.find(para) != util_title.end()) {
// index = util_title[para];
// query_result = titles[index].ids;
// }
//
// break;
//
// case AUTHOR:
// if (util_author.find(para) != util_author.end()) {
// index = util_author[para];
// query_result = authors[index].ids;
// }
//
// break;
//
// case KEY_WORD:
// if (util_keyword.find(para) != util_keyword.end()) {
// index = util_keyword[para];
// query_result = keywords[index].ids;
// }
//
// break;
//
// case PUBLISHER:
// if (util_publisher.find(para) != util_publisher.end()) {
// index = util_publisher[para];
// query_result = publishers[index].ids;
// }
//
// break;
//
// case YEAR:
// if (util_year.find(para) != util_year.end()) {
// index = util_year[para];
// query_result = years[index].ids;
// }
//
// break;
//
// default:
// break;
// }
//
// cout << query << endl;
//
// if (query_result.empty()) {
// cout << "Not Found" << endl;
// } else {
// for (auto id : query_result) {
// cout << id << endl;
// }
// }
// }
//
// return 0;
//}
enum CMD {
TITLE = '1',
AUTHOR = '2',
KEY_WORD = '3',
PUBLISHER = '4',
YEAR = '5'
};
int main() {
#pragma region GET_INPUT
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
#endif
}
#pragma endregion
int n;
cin >> n;
cin.ignore();
map<string, set<string>> titles;
map<string, set<string>> authors;
map<string, set<string>> keywords;
map<string, set<string>> publishers;
map<string, set<string>> years;
string id, title, author, _keywords, publisher, year;
char s[100];
while(n--) {
getline(cin, id);
getline(cin, title);
titles[title].insert(id);
getline(cin, author);
authors[author].insert(id);
// gets(s);
// char *p = strtok(s, " ");
//
// while (p) {
// keywords[p].insert(id);
// p = strtok(NULL, " ");
// }
// //截取字符串出错
getline(cin, _keywords);
int pos, last = 0;
string keyword;
while((pos = _keywords.find(' ', last)) != -1) {
keyword = _keywords.substr(last, pos - last);
keywords[keyword].insert(id);
last = pos + 1;
}
keyword = _keywords.substr(last);
keywords[keyword].insert(id);
getline(cin, publisher);
publishers[publisher].insert(id);
getline(cin, year);
years[year].insert(id);
}
int m;
cin >> m;
cin.ignore();
while(m--) {
string query;
getline(cin, query);
char cmd = query[0];
string para = query.substr(3);
set<string> result;
switch (cmd) {
case TITLE:
result = titles[para];
break;
case AUTHOR:
result = authors[para];
break;
case KEY_WORD:
result = keywords[para];
break;
case PUBLISHER:
result = publishers[para];
break;
case YEAR:
result = years[para];
break;
default:
break;
}
cout << query << endl;
if (result.empty()) {
cout << "Not Found" << endl;
} else {
for (auto _id : result) {
cout << _id << endl;
}
}
}
return 0;
}
| true |
d2015d252be4066fc6de2c63216b921896ad2c33 | C++ | fredsmalley/biolab | /src/search.cpp | UTF-8 | 2,230 | 2.65625 | 3 | [] | no_license | #include "search.h"
#include "util.h"
#include <iostream>
void pgp_search::set_patterns() {
string pattern = "State:</t[d|h]><td>";
patterns.push_back(pattern + "([[:alpha:] ]+)" + "</td>");
//string pattern = "State:";
//patterns.push_back(pattern);
}
void pgp_search::set_files() {
string id_file_name = "./test/participants.tsv";
ids = read_id(id_file_name);
cout << "ids.size() = " << ids.size() << endl;
#if 1
for(int i = 0; i < ids.size(); ++i)
files.push_back("./test/PGP-participants/"+ids[i]+".html");
#endif
}
vector<string>& pgp_search::get_results() {
for(int i = 0; i < files.size(); ++i) {
for(int j = 0; j < patterns.size(); ++j) {
smatch r;
regex reg(patterns[j]);
if(regex_search(html_to_string(files[i]), r, reg)) {
//cout << "found pattern: " << patterns[j] << endl;
results.push_back(r.str());
}
else {
cout << files[i] << " does not have state" << endl;
results.push_back("");
}
}
}
cout << "results size() = " << results.size() << endl;
return results;
}
void pgp_search::write_results() {
ofstream ofs;
ofs.open ("id_state.txt", ofstream::out | ofstream::app);
for(int i = 0; i < ids.size(); i++)
ofs << ids[i] << "\t" << results[i] << endl;
ofs.close();
}
void pgp_search::filter_results() {
// remove tags
for(int i = 0; i < results.size(); i++) {
if(results[i].length() > 0) {
results[i].erase(results[i].begin(), results[i].begin()+15);
results[i].erase(results[i].end()-5, results[i].end());
}
}
// abbreviations
map<string, string> state_table = state_name_table();
#ifdef DEBUG
for(map<string, string>::iterator it = state_table.begin(); it != state_table.end(); ++it) {
cout << it->first << " " << it->second << endl;
}
#endif
for(int i = 0; i < results.size(); i++) {
results[i] = state_table[results[i]];
}
}
#ifdef TEST
void search_test() {
pgp_search se;
vector<string> &output = se.get_results();
cout << "output size: " << output.size() << endl;
se.filter_results();
for(vector<string>::iterator it = output.begin();
it != output.end(); ++it) {
cout << *it << endl;
}
se.write_results();
}
#endif
| true |
c6229d81d9052c10d8654c3d5d47f23670805eea | C++ | Acka1357/ProblemSolving | /BeakjoonOJ/14000/14188_Elections.cpp | UTF-8 | 768 | 2.625 | 3 | [] | no_license | //
// Created by Acka on 2017. 9. 11..
//
#include <stdio.h>
#include <memory.h>
int e[1000];
double p[1001], d[1001][2002];
int main()
{
int N; while(scanf("%d", &N) == 1){
if(N == 0) break;
for(int i = 1; i <= N; i++)
scanf("%lf %d", &p[i], &e[i]);
memset(d, 0, (N + 1) * sizeof(d[0]));
d[0][0] = 1;
int sum = 0;
for(int i = 1; i <= N; i++){
for(int j = 0; j <= sum; j++){
d[i][j + e[i]] += d[i - 1][j] * p[i];
d[i][j] += d[i - 1][j] * (1 - p[i]);
}
sum += e[i];
}
double ans = 0;
for(int i = (sum + 1) / 2; i <= sum; i++)
ans += d[N][i];
printf("%.4lf\n", ans);
}
return 0;
}
| true |
9e8232da5b920c75182e01e356c1d601ccb70852 | C++ | mkhasan/time_gap | /src/time_gap.cpp | UTF-8 | 2,121 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <time.h>
#include <sys/time.h>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <assert.h>
using namespace std;
void print_time(char *str);
int StrToTime(const string str, struct tm * tm);
int Gap(const struct tm &, const struct tm &);
int main(int argc, char * argv[]) {
char curTime[100];
print_time(curTime);
//cout << curTime << endl;
/*
std::string text = curTime;//"Let me split this into words";
std::vector<std::string> results;
boost::split(results, text, [](char c){return c == ':';});
*/
/*
for (vector<string>::const_iterator it = results.begin(); it != results.end(); ++it) {
cout << *it << endl;
}
*/
cout << curTime << endl;
struct tm tm1, tm2;
if(StrToTime("12:37:23_833957", &tm1) == 0) {
cout << tm1.tm_hour << "||" << tm1.tm_min << "||" << tm1.tm_sec << endl;
}
if(StrToTime(curTime, &tm2) == 0) {
cout << tm2.tm_hour << "||" << tm2.tm_min << "||" << tm2.tm_sec << endl;
}
cout << Gap(tm1, tm2) << endl;
}
void print_time(char *str) {
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv, &tz);
tm=localtime(&tv.tv_sec);
sprintf(str, "%d:%02d:%02d_%d", tm->tm_hour, tm->tm_min,
tm->tm_sec, tv.tv_usec);
}
int StrToTime(const string str, struct tm * tm) {
/*
for (vector<string>::const_iterator it = results.begin(); it != results.end(); ++it) {
cout << *it << endl;
}
*/
vector<std::string> results;
try {
boost::split(results, str, [](char c){return c == ':';});
assert(results.size() == 3);
tm->tm_hour = stoi(results[0]);
tm->tm_min = stoi(results[1]);
boost::split(results, results[2], [](char c){return c == '_';});
assert(results.size() == 2);
tm->tm_sec = stoi(results[0]);
}
catch (const exception & e) {
cout << "Error occured " << e.what() << endl;
return -1;
}
return 0;
//cout << curTime << endl;
}
int Gap(const struct tm &tm1, const struct tm &tm2) {
//int sec1 = tm1.tm_hour*3600+tm1.tm_min*60+tm1.tm
auto secs = [](const struct tm &t) {return (t.tm_hour*3600+t.tm_min*60+t.tm_sec); };
return secs(tm2) - secs(tm1);
}
| true |
9de86e95d65dda17463d84a6b3b221b914eea6d1 | C++ | pabern/Wheezy | /Wheezy/MainWindow.cpp | UTF-8 | 2,593 | 2.875 | 3 | [] | no_license | #include "MainWindow.hpp"
using namespace std;
MainWindow::MainWindow()
{
// Attributes of main window
setWindowTitle("Welcome to Wheezy !");
// setFixedSize(1500,750);
// Menus
// Character creation menu
menuChar = menuBar()->addMenu("Character");
// QAction *actionNewChar = new QAction("New",this);
actionNewChar = new QAction("New",this);
menuChar->addAction(actionNewChar);
connect(actionNewChar,SIGNAL(triggered(bool)),this,SLOT(makeNewChar()));
// Obligatory first line
// Container for ALL other widgets of main window
centralZone = new QWidget;
// Set central widget
// Last line of window construction
setCentralWidget(centralZone);
}
// SLOTS
void MainWindow::makeNewChar()
{
setWindowTitle("Wheezy Character Creation");
setFixedWidth(700);
actionSaveChar = new QAction("Save",this);
menuChar->removeAction(actionNewChar);
menuChar->addAction(actionSaveChar);
connect(actionSaveChar,SIGNAL(triggered(bool)),this,SLOT(saveNewChar()));
// Actual layout creation
layoutNewChar = new NewCharWindow;
centralZone->setLayout(layoutNewChar);
// Set central widget
// Last line of window construction
setCentralWidget(centralZone);
}
void MainWindow::saveNewChar()
{
if (layoutNewChar->getRanksLeft() >= 0)
{
ofstream streamSave;
streamSave.open("/home/pat/CodingProjects/Wheezy/Wheezy/Wheezy/" + layoutNewChar->getCharName().toStdString());
if (streamSave)
{
// Name, race & class
streamSave << layoutNewChar->getCharName().toStdString() << endl;
streamSave << layoutNewChar->getCoreRaces().toStdString() << endl;
streamSave << layoutNewChar->getCoreClasses().toStdString() << endl;
// Alignment
streamSave << layoutNewChar->getAlignment() << endl;
// Abilities
layoutNewChar->writeAbilities(streamSave);
// Feats
streamSave << layoutNewChar->getFeats() << endl;
// Hit Dice & starting gold
streamSave << layoutNewChar->getHit()<< endl;
streamSave << layoutNewChar->getGold() << endl;
// Skills
layoutNewChar->writeSkills(streamSave);
QMessageBox::information(this,"Saved","Your character was saved.");
}
else
{
qFatal("Can't open file to save on");
}
}
else
{
QMessageBox::information(this,"Sneaky","You put too much rank ! Check next to your name !");
}
}
| true |
90a6d609510cec18db340ce7037497dc840b8062 | C++ | TheBossBaby/My-Journey-Of-C-pp | /Chapter III/Exercise/DigitToSpellingConverter/DigitToSpellingConverter/Source.cpp | UTF-8 | 1,643 | 4.40625 | 4 | [] | no_license | //This C++ programe converts digit like 0,1 .... 9 to there respective spelled word like zero, one, ...... nine
//and vice-versa
#include"std_lib_facilities.h"
//This function takes a digit and convert it to its spelling
string digit_to_spelling(int input_digit, vector <string> spelled_digit)
{
int i{ -1 }; //Used for iterating
for (string x : spelled_digit)
{
i++; //It stores the digit
if (i == input_digit)
return x;
}
simple_error("Input is out of range!!!!");
}
//This function takes spelling of digit and prints the digit in numeric form
int spelling_to_digit(string input_spelling, vector <string> spelled_digit)
{
int i{ -1 };
for (string x : spelled_digit)
{
i++;
if (x == input_spelling)
return i; //Returns the digit
}
//If the for statement does not return anything it means the input is out of range!!!
simple_error(" is out of range!!!!!\n\n\a");
}
int main()
{
vector <string> spelled_digit{ "zero", "one","two","three","four","five","six","seven","eight","nine" };
int input_digit{ -1 };
//Digit to spelling
cout << "\n\tEnter the digit from(0-9): ";
cin >> input_digit;
if (input_digit > spelled_digit.size())
cout << "\nInput out of range!!\a\a\n";
else
{
cout << "\n\t" << input_digit << " is spelled as: " << digit_to_spelling(input_digit, spelled_digit) << "\n";
}
string input_spelling{ "??" };
cout << "\n\tEnter the spelling(in lower case) form (zero-nine): ";
cin >> input_spelling;
//Spelling to digit
cout << "\n\t"<<input_spelling<<" is the spelling of the digit: "<<spelling_to_digit(input_spelling, spelled_digit)<<"\n";
keep_window_open();
return 0;
} | true |
4a2d71afc2783dd6d016fc32baac196f919dc33d | C++ | LiuJiLan/LeetCodeStudy | /LC_105. 从前序与中序遍历序列构造二叉树/#-1.1_LC官方思路探索.cpp | UTF-8 | 1,230 | 3.203125 | 3 | [] | no_license | //2020.10.08_#-1.1_LC官方思路探索
//未完成
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
private:
TreeNode * inConstruct(int rootVal, vector<int> leftSubTree, vector<int> rightSubTree) {
TreeNode * root = new TreeNode(rootVal); //set the root value
vector<int> rootLeftSubTree = vector<int>(); //Initialize the leftSubTree array of the root
vector<int> rootRightSubTree = vector<int>(); //Initialize the rightSubTree array of the root
if (leftSubTree.size() == 0) {
root->left = NULL;
} else {
// a function to seperate the leftSubTree to new leftSubTree and new rightSubTree
// So, it's definitely can make a recursion directly use preorder array and inorder array
}
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode * newTree = new TreeNode(0); //just to silense the warning/error.
//Now, I already have a idea to deal with this problem.
return newTree; //just to silense the warning/error.
}
};
| true |
31a95e418be6b48b2eb6999b51fe4a1bdcb1f5c5 | C++ | basti-shi031/LeetcodeCpp | /Ex82_Remove_Duplicates_from_Sorted_List_II.cpp | UTF-8 | 911 | 2.953125 | 3 | [] | no_license | //
// Created by Basti031 on 2019/11/19.
//
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL || head->next==NULL)
return head;
ListNode *p=head->next;
if(p->val!=head->val){
head->next=deleteDuplicates(p);
return head;
}
else{
while(p && p->val==head->val) p=p->next;
return deleteDuplicates(p);
}
}
};
/*
int main() {
ListNode n1 = ListNode(1);
ListNode n2 = ListNode(1);
ListNode n3 = ListNode(2);
ListNode n4 = ListNode(3);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
Solution solution = Solution();
ListNode *head = solution.deleteDuplicates(&n1);
int a = 1;
}*/
| true |
3a540df5c0c3d6637cec535597097a46b6d79056 | C++ | HulinCedric/cpp-course | /_Packages/_Maths/DemiDroite/T_DemiDroite_N4_1.cpp | UTF-8 | 1,520 | 2.59375 | 3 | [
"MIT"
] | permissive | //
// IUT de Nice / Departement informatique / Module APO-C++
// Annee 2008_2009 - Package _Maths
//
// Classe DemiDroite - Tests unitaires de la methode support
// (Cas nominaux)
//
// Auteur : A. Thuaire
//
#include "DemiDroite.h"
#include "T:\_Tests\Tests\Tests.h"
void main () {
Tests::Begin("_Maths.DemiDroite", "2.0.0");
Tests::Design("Controle des methodes (lot 1)", 3);
Tests::Case("Methode support / Premiere forme"); {
Point O(0, 0), A(2, -2), B(2.5, -3.75);
Vecteur v1(-1, -1), v2(0, 2), v3(2, -0.5);
DemiDroite d1(O, v1), d2(O, v2), d3(B, v2), d4(B, v3);
Droite* pD;
pD= d1.support();
Tests::Unit("[1, -1, 0]", pD->toString());
pD= d2.support();
Tests::Unit("[0, 1, 0]", pD->toString());
pD= d3.support();
Tests::Unit("[0, 1, -2.5]", pD->toString());
pD= d4.support();
Tests::Unit("[1, 0.25, 3.125]", pD->toString());
}
Tests::Case("Methode support / Seconde forme"); {
Point O(0, 0), A(2, 0), B(4, 0), C(7, 0), D(0, 2);
Segment OA(O, A), OD(O, D);
Vecteur BC(B, C), CB(C, B);
DemiDroite d1(C, CB), d2(B, BC);
Tests::Unit(true, d1.support(OA));
Tests::Unit(false, d2.support(OA));
Tests::Unit(false, d2.support(OD));
}
Tests::End();
}
| true |
3491f477e1758ad23f952b5a20f94a8c346a317c | C++ | Mehran2013T/Sudoku-GUI | /Sudoku/core/DigitExtractor.h | UTF-8 | 1,888 | 2.65625 | 3 | [] | no_license | #pragma once
#include <opencv2\core\core.hpp>
#include <boost\optional.hpp>
#include <boost\serialization\nvp.hpp>
using namespace cv;
using boost::optional;
class DigitExtractor
{
public:
DigitExtractor(void);
~DigitExtractor(void);
optional<Mat> ExtractDigit(unsigned int col, unsigned int row,
unsigned int thresh);
Mat GetProcessedCell(unsigned int col, unsigned int row);
Mat GetInputImage(void);
void LoadImage(Mat& img);
inline int GetBlockSize(void) { return block_size_; }
inline void SetBlockSize(int blockSize) { block_size_ = blockSize; }
inline double GetC(void) { return c_; }
inline void SetC(double c) { c_ = c; }
inline int GetPercentage(void) { return percentage_; }
inline void SetPercentage(int percentage) { percentage_ = percentage; }
inline int GetN(void) { return n_; }
inline void SetN(int n) { n_ = n; }
inline int GetKernelSizeMorph(void) { return kernel_size_morph_; }
inline void SetKernelSizeMorph(int kernel_size) { kernel_size_morph_ = kernel_size; }
void ClearAdjustFlags(void);
void SetAdjustFlag(void) { ClearAdjustFlags(); adjust_flag = true; }
private:
optional<Mat> Preprocess(Mat* img);
void SetDefaultParameters(void);
bool Load(void);
bool Save(void);
Mat input_img;
Mat cell_img;
Mat tmp_img;
int cell_width;
int cell_height;
int cell_area;
bool ready_flag;
bool adjust_flag;
//parameters
std::string file_name_;
int block_size_;
double c_;
int percentage_;
int n_;
int kernel_size_morph_;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
using boost::serialization::make_nvp;
ar & make_nvp("block_size", block_size_)
& make_nvp("c", c_)
& make_nvp("percentage", percentage_)
& make_nvp("n", n_)
& make_nvp("kernel_size_morph", kernel_size_morph_);
}
};
| true |
7b825f9e1a6486f838e7ecff2cd56b1a9a72e38f | C++ | pavelsimo/ProgrammingContest | /uva/11799_Horror_Dash/P11799.cpp | UTF-8 | 433 | 2.578125 | 3 | [] | no_license | /* @BEGIN_OF_SOURCE_CODE */
/* @JUDGE_ID: 11799 C++ "Ad Hoc" */
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[]) {
int TC, n, x, ans;
scanf("%d",&TC);
for(int tc=1; tc<=TC; ++tc) {
ans=0;
scanf("%d",&n);
for(int i = 0; i < n; ++i) {
scanf("%d",&x);
ans=max(ans,x);
}
printf("Case %d: %d\n",tc,ans);
}
return 0;
}
/* @END_OF_SOURCE_CODE */
| true |
6ad1c29e937e2a5f2491f450b98cfe170bd6ef2c | C++ | ckargus/CIS200-CPP2 | /Program_04/Source.cpp | UTF-8 | 921 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include "LeakeyStack.h"
#include "LinkedLeakyStack.h"
using namespace std;
int main()
{
LinkedLeakyStack<int> test(15);
cout << "Linked Leaky stack with 20 pushs" << endl;
for (int i = 0; i < 20; i++)
{
test.push(i);
}
while(!test.isEmpty())
{
cout << test.peek() << endl;
test.pop();
}
cout << "Linked Leaky stack with 100 pushs" << endl;
for (int i = 0; i < 100; i++)
{
test.push(i);
}
while (!test.isEmpty())
{
cout << test.peek() << endl;
test.pop();
}
LeakyStackArray<int> test1;
cout << "Array Leaky stack with 20 pushs" << endl;
for (int i = 0; i < 20; i++)
{
test1.push(i);
}
while (!test1.isEmpty())
{
cout << test1.peek() << endl;
test1.pop();
}
cout << "Array Leaky stack with 100 pushs" << endl;
for (int i = 0; i < 100; i++)
{
test1.push(i);
}
while (!test1.isEmpty())
{
cout << test1.peek() << endl;
test1.pop();
}
return 0;
} | true |
7c47c33efff0c8059ba8d96140bc924f5e081fe6 | C++ | PetarSam/PostBoxAlert-IoT_Project | /MailAlert-IoT.ino | UTF-8 | 834 | 2.71875 | 3 | [] | no_license |
#include <SoftwareSerial.h>
SoftwareSerial mySerial(3, 2);
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
mySerial.begin(9600);
Serial.println("Initializing...");
delay(1000);
mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
updateSerial();
mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
updateSerial();
mySerial.println("AT+CMGS=\"+4550384602\"");
updateSerial();
mySerial.print("Mail recieved"); //text content
updateSerial();
mySerial.write(26);
}
void loop() {
}
void updateSerial()
{
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());
}
while(mySerial.available())
{
Serial.write(mySerial.read());
}
}
| true |
1785d2d89f7e2c9172fb49dfa47526d109afc225 | C++ | babypuma/leetcode | /ImplementQueueusingStacks/implement_queue_using_stacks.h | UTF-8 | 1,739 | 4.0625 | 4 | [] | no_license | /*
* Author : Jeremy Zhao
* Email : jqzhao@live.com
* Date : 2015/07/10
*
* Source : https://leetcode.com/problems/implement-queue-using-stacks/
* Problem: Implement Queue using Stacks
* Description:
* Implement the following operations of a queue using stacks.
*
* push(x) -- Push element x to the back of queue.
* pop() -- Removes the element from in front of queue.
* peek() -- Get the front element.
* empty() -- Return whether the queue is empty.
* Notes:
* You must use only standard operations of a stack -- which means only push to top,
* peek/pop from top, size, and is empty operations are valid.
* Depending on your language, stack may not be supported natively. You may simulate
* a stack by using a list or deque (double-ended queue), as long as you use only
* standard operations of a stack.
* You may assume that all operations are valid (for example, no pop or peek operations
* will be called on an empty queue).
*
*/
#include <stack>
using std::stack;
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
while (!aux_.empty()) {
master_.push(aux_.top());
aux_.pop();
}
master_.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
while (!master_.empty()) {
aux_.push(master_.top());
master_.pop();
}
if (!aux_.empty()) {
aux_.pop();
}
}
// Get the front element.
int peek(void) {
while (!master_.empty()) {
aux_.push(master_.top());
master_.pop();
}
if (!aux_.empty()) {
return aux_.top();
}
}
// Return whether the queue is empty.
bool empty(void) {
return master_.empty() && aux_.empty();
}
private:
stack<int> master_;
stack<int> aux_;
};
| true |
800bed72042769447b09e5c93c27467c8d4f07fa | C++ | kimhaingvan/source-code-C- | /nam1/BTTH_CSLT/BTTH3_TR125.CPP/B2_P2_N1_N2.cpp | UTF-8 | 367 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n1,n2,tong=0;
cout << "Nhap vao so nguyen n1: ";
cin >> n1;
cout << "Nhap vao so nguyen n2: ";
cin >> n2;
while (n1 < n2)
{
if (n1 % 2 == 1)
{
cout <<n1 <<endl;
}
else if (n1 % 2 == 0)
{
tong += n1;
}
n1 =n1+ 1;
}
cout << "Tong cac so chan la: " << tong << endl;
return 0;
} | true |
34e14f807c51fc33f2335621e6baa7d4a8bb4b04 | C++ | orihehe/Codeforces | /Codeforces Round #563 (Div. 2)/D - Ehab and the Expected XOR Problem.cpp | UTF-8 | 813 | 3.25 | 3 | [] | no_license | /*
0이 안 나오게 하려면 1 2 1 4 1 2 1 이런 꼴이 최대를 만들 수 있다.
x또한 나오지 않도록 해야하니 x가 2^n보다 작다면 켜진 비트 하나를 제외하고 같은 꼴로 출력해준다.
*/
#include <cstdio>
#include <vector>
using namespace std;
/* 🐣🐥 */
int arr[19];
vector<int> vec;
void prt(int cur) {
if (cur == -1) return;
prt(cur - 1);
printf("%d ", vec[cur]);
prt(cur - 1);
}
int main() {
int n, x;
scanf("%d %d", &n, &x);
for (int i = 1; i <= 18; i++) arr[i] = arr[i - 1] * 2 + 1;
bool flag = false;
if (x >= (1 << n)) {
printf("%d\n", arr[n]);
flag = true;
}
else printf("%d\n", arr[n - 1]);
for (int i = 0; i < n; i++) {
int tt = 1 << i;
if (!flag && tt & x) flag = true;
else vec.push_back(tt);
}
prt(vec.size() - 1);
return 0;
} | true |
0633fdde4a42e989fdd14435ddc39a502ede83fa | C++ | GarlandChaos/TessellationOpenGL | /Garland/Mesh.cpp | UTF-8 | 3,518 | 3.015625 | 3 | [] | no_license | #include "Mesh.h"
#include <iostream>
Mesh::Mesh()
{
}
Mesh::~Mesh()
{
}
void Mesh::increaseVerticesCount()
{
verticesCount++;
}
vector<glm::vec3> Mesh::getVertices(Group group)
{
vector<glm::vec3> verts;
for (int i = 0; i < group.getFaces().size(); i++)
{
for (int j = 0; j < group.getFaces()[i].getVertices().size(); j++)
{
verts.push_back(vertices[group.getFaces()[i].getVertices()[j]]);
}
}
return verts;
}
vector<glm::vec3> Mesh::getNormals(Group group)
{
vector<glm::vec3> norms;
for (int i = 0; i < group.getFaces().size(); i++) {
for (int j = 0; j < group.getFaces()[i].getNormals().size(); j++) {
norms.push_back(normals[group.getFaces()[i].getNormals()[j]].getNormals());
}
}
return norms;
}
vector<glm::vec2> Mesh::getTextureCoords(Group group)
{
vector<glm::vec2> textCoords;
for (int i = 0; i < group.getFaces().size(); i++)
{
for (int j = 0; j < group.getFaces()[i].getTextures().size(); j++)
{
textCoords.push_back(textures[group.getFaces()[i].getTextures()[j]].getPosition());
}
}
return textCoords;
}
void Mesh::setupMesh() {
for (int i = 0; i < groups.size(); i++) {
vector<glm::vec3> verts = getVertices(groups[i]);
vector<glm::vec3> norms = getNormals(groups[i]);
GLuint vao, vbo1, vbo2, vbo3;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo1);
glBindVertexArray(vao);
vaos.push_back(vao);
//VBO 1: vertex
glBindBuffer(GL_ARRAY_BUFFER, vbo1);
glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(glm::vec3), &verts[0], GL_STATIC_DRAW);
// vertex positions
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
//VBO 2: normal
glGenBuffers(1, &vbo2);
glBindBuffer(GL_ARRAY_BUFFER, vbo2);
glBufferData(GL_ARRAY_BUFFER, norms.size() * sizeof(glm::vec3), &norms[0], GL_STATIC_DRAW);
// vertex normals
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(1);
if (textures.size() > 0)
{
vector<glm::vec2> textCoords = getTextureCoords(groups[i]);
//VBO 3: texture coord
glGenBuffers(1, &vbo3);
glBindBuffer(GL_ARRAY_BUFFER, vbo3);
glBufferData(GL_ARRAY_BUFFER, textCoords.size() * sizeof(glm::vec2), &textCoords[0], GL_STATIC_DRAW);
// vertex texture coords
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
}
}
void Mesh::Draw() {
for (int i = 0; i < vaos.size(); i++) {
glBindVertexArray(vaos[i]);
glDrawArrays(GL_TRIANGLES, 0, verticesCount);
//glDrawElements(GL_TRIANGLES, verticesCount, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
}
void Mesh::DrawPatches() {
for (int i = 0; i < vaos.size(); i++) {
glBindVertexArray(vaos[i]);
glDrawArrays(GL_PATCHES, 0, verticesCount);
glBindVertexArray(0);
}
}
void Mesh::setGroups(vector<Group> groups) {
this->groups = groups;
}
vector<Group>& Mesh::getGroups() {
return groups;
}
void Mesh::setVertices(vector<glm::vec3> vertices) {
this->vertices = vertices;
}
vector<glm::vec3>& Mesh::getVertices() {
return vertices;
}
void Mesh::setTextures(vector<Texture> textures){
this->textures = textures;
}
vector<Texture>& Mesh::getTextures() {
return textures;
}
void Mesh::setNormals(vector<Normal> normals) {
this->normals = normals;
}
vector<Normal>& Mesh::getNormals() {
return normals;
}
void Mesh::setMaterialLib(string materialLib)
{
this->materialLib = materialLib;
}
string Mesh::getMaterialLib()
{
return materialLib;
} | true |
91a46e79bf08f32db1b16d9b4c1b6efcbdf0f4ba | C++ | jpdean/basix | /cpp/basix/dof-transformations.h | UTF-8 | 1,561 | 2.875 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2020 Chris Richardson & Matthew Scroggs
// FEniCS Project
// SPDX-License-Identifier: MIT
#pragma once
#include <vector>
/// Functions to help with the creation of DOF transformation and
/// direction correction.
namespace basix::doftransforms
{
/// Reflect the DOFs on an interval
/// @param degree The number of DOFs on the interval
/// @return A reordering of the numbers 0 to degree-1 representing the
/// transformation
std::vector<int> interval_reflection(int degree);
/// Reflect the DOFs on a triangle
/// @param degree The number of DOFs along one side of the triangle
/// @return A reordering of the numbers 0 to (degree)*(degree+1)/2-1
/// representing the transformation
std::vector<int> triangle_reflection(int degree);
/// Rotate the DOFs on a triangle
/// @param degree The number of DOFs along one side of the triangle
/// @return A reordering of the numbers 0 to (degree)*(degree+1)/2-1
/// representing the transformation
std::vector<int> triangle_rotation(int degree);
/// Reflect the DOFs on a quadrilateral
/// @param degree The number of DOFs along one side of the quadrilateral
/// @return A reordering of the numbers 0 to degree*degree-1 representing the
/// transformation
std::vector<int> quadrilateral_reflection(int degree);
/// Rotate the DOFs on a quadrilateral
/// @param degree The number of DOFs along one side of the quadrilateral
/// @return A reordering of the numbers 0 to degree*degree-1 representing the
/// transformation
std::vector<int> quadrilateral_rotation(int degree);
} // namespace basix::doftransforms
| true |
78cbb81957ec2e51dc7437f032005b8f3d84d865 | C++ | stacyj929/INFO450FavoriteThing | /MyFavoriteThing/FavoriteList.cpp | UTF-8 | 1,294 | 3.359375 | 3 | [] | no_license | #include "stdafx.h"
#include "FavoriteList.h"
#include <iostream>
using namespace std;
FavoriteList::FavoriteList()
{
listSize = 0;
}
FavoriteList::~FavoriteList()
{
}
bool FavoriteList::isUnique(FavoriteItem movieEntry)
{
for (int i = 0; i < listSize; i++)
{
if (movieEntry.getFavoriteItem() == movieArray[i].getFavoriteItem())
{
return false;
}
}
return true;
}
int FavoriteList::addFavoriteItem()
{
if (movieArray[listSize].getFavoriteItem() == 0
&& isUnique(movieArray[listSize]))
{
listSize++;
return 0;
}
else
{
cout << "error occurred in addFavoriteItem " << endl;
return ERROR1;
}
}
void FavoriteList::displayList()
{
for (int outer = 1; outer < listSize; outer++)
{
int inner = outer;
while (inner > 0 &&
movieArray[inner].getFavoriteItem() < movieArray[inner - 1].getFavoriteItem())
{
FavoriteItem temp = movieArray[inner];
movieArray[inner] = movieArray[inner - 1];
movieArray[inner - 1] = temp;
inner--;
}
}
cout << "Here is your collection. It has " << listSize << " movies!\n\n";
for (int i = 0; i < listSize; i++)
{
cout << movieArray[i];
cout << endl << endl;
}
}
/*void FavoriteList::displayList()
{
int i;
for (i = 0; i < listSize; i++)
{
cout << movieArray[i];
cout << endl << endl;
}
}*/ | true |
00a73109c9378a86863f162096a2edcb84cd8040 | C++ | jJayyyyyyy/OJ | /LeetCode/_1001_1100/P1021_Remove_Outermost_Parentheses.cpp | UTF-8 | 731 | 3.15625 | 3 | [] | no_license | /*
https://leetcode.com/problems/remove-outermost-parentheses/description/
移除最外层的括号
同类题目 P1021
参考思路
https://leetcode.com/problems/remove-outermost-parentheses/discuss/270022/JavaC++Python-Count-Opened-Parenthesis
*/
#include <iostream>
#include <string>
using namespace std;
const static auto c = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
return 0;
}();
class Solution {
public:
string removeOuterParentheses(string S) {
string ans;
int cnt_left = 0;
for( char ch : S ){
if( ch == '(' ){
if( cnt_left > 0 ){
ans += ch;
}
cnt_left++;
}
if( ch == ')' ){
if( cnt_left > 1 ){
ans += ch;
}
cnt_left--;
}
}
return ans;
}
};
| true |
e3232aa369e3a6e3b1fa8eea098db1c8ee026f5b | C++ | danoconnor/RayTracer | /RayTracer/RayTracer/Sphere.h | UTF-8 | 1,383 | 3.0625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include "Vector.h"
#include "Windows.h"
namespace RayTracer
{
class Sphere
{
public:
Sphere(Vector center, float radius, COLORREF color, float alpha, float refraction, float reflectivity);
Sphere(Vector center, float radius, const cimg_library::CImg<unsigned char> &texture, float alpha, float refraction, float reflectivity);
bool CheckCollision(const Vector &origin, const Vector &direction, float &distance, Vector &collisionPoint) const;
COLORREF GetColorAt(const Vector &point) const;
// Returns the normalized normal vector at the given point
Vector GetNormalAt(const Vector &point, const Vector &lookDir) const;
bool equals(const Sphere &other) const;
float GetAlpha() const;
float GetRefraction() const;
float GetReflectivity() const;
private:
const cimg_library::CImg<unsigned char> *m_texture;
COLORREF m_color;
// Transparency of object. Ranges from 1 = completely opaque to 0 = completely transparent.
float m_alpha;
// Reflectivity of object. Ranges from 1.0 = completely reflective to 0 = completely unreflective.
float m_reflectivity;
// Refracive index of object. Ranges from 2.0 = max refraction to 1.0 = no refraction.
float m_refraction;
Vector m_center;
float m_radius;
static const float m_Pi; // Pi
static const float m_Two_Pi; // 2 * Pi
};
} | true |
e5154d4794298c29ab53ae099b24513436d61051 | C++ | Faulty-Chow/MineHelper | /Source/Cell.h | UTF-8 | 527 | 3.171875 | 3 | [] | no_license | #ifndef _CELL_H_
#define _CELL_H_
#include <assert.h>
#include "Constants.h"
//! cell class
class Cell{
private:
int m_x;
int m_y;
CellState m_state;
bool haveValue;
public:
Cell(int x, int y):m_x(x),m_y(y),m_state(Unknow),haveValue(true){}
int getX()const{ return m_x;}
int getY()const{ return m_y;}
CellState getState()const{ return m_state;}
void setState(const CellState state){
m_state = state;
}
bool getHaveValue()const{return haveValue;}
void setHaveValue(bool flag){
haveValue = flag;
}
};
#endif | true |
a56db6caac975a1309073ef733939634e37d9cb8 | C++ | MatejSakmary/PGR_semestral_linux | /src/bezier.cpp | UTF-8 | 596 | 2.828125 | 3 | [] | no_license | // // Created by matejs on 12/05/2021.
//
#include "bezier.h"
glm::vec3 Bezier::getPosition(float t) {
glm::vec3 position;
if(!cubic){
position = (float)(glm::pow(1 - t, 2)) * from +
(float)((1 - t) * 2 * t) * firstControlPoint +
(float)(t * t) * to;
} else{
position = (float)(glm::pow(1 - t, 3)) * from +
(float)(glm::pow(1 - t, 2) * 3 * t) * firstControlPoint +
(float)((1 - t) * 3 * t * t) * secondControlPoint +
(float)(t * t * t) * to;
}
return position;
}
| true |
f5dae9a656ad9423a346d14c26bd3c6906f38e8b | C++ | MMG1970/Arduino | /control_Display/control_Display.ino | UTF-8 | 1,134 | 2.640625 | 3 | [] | no_license | #include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
//si tu display no usa pin reset, aquí pon -1 para no desperdiciar un pin de tu arduino
Adafruit_SSD1306 display(-1);
void setup(){
Serial.begin(9600);
//Inicio el display para la AxAA dirección
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64)
// Borrar display
display.clearDisplay();
display.drawRect(0,0,100,64,WHITE); //dibuja rectángulo vacio
//display.fillRect(0,0,100,64,WHITE); //dibuja rectángulo lleno
//display.drawRoundRect(0,0,100,64,20,WHITE); //dibuja rectángulo redondeado
//display.fillRoundRect(0,0,100,64,20,WHITE); //dibuja rectángulo redondeado
//display.drawTriangle(10,10,45,60,60,60,WHITE);
//display.fillTriangle(10,10,45,60,60,60,WHITE);
display.setTextSize(1);
display.setTextColor(WHITE,BLACK);
display.setCursor(5,5);
display.println("Hello, world!");
display.setCursor(5,15);
display.println("Hello, world2!");
display.display();
}
void loop(){
}
| true |
6ecc97d208c1b8421bd6b78a643ce24fcaa01201 | C++ | i-RIC/prepost-gui | /libs/misc/colorcontainer.h | UTF-8 | 1,401 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef COLORCONTAINER_H
#define COLORCONTAINER_H
#include "xmlattributecontainer.h"
class QColor;
class MISCDLL_EXPORT ColorContainer : public XmlAttributeContainer
{
public:
/// @name Constructors and Destructor
//@{
ColorContainer(const QString& name);
ColorContainer(const QString& name, const QColor& defaultVal);
ColorContainer(const ColorContainer& c);
virtual ~ColorContainer();
//@}
/// @name XML I/O functions
//@{
void load(const QDomNode&) override;
void save(QXmlStreamWriter&) const override;
//@}
/// @name Operators
//@{
ColorContainer& operator=(const ColorContainer& c);
ColorContainer& operator=(const QColor& v);
operator QColor() const;
operator double*() const;
//@}
/// @name Getter and Setter
//@{
const QColor& value() const;
void setValue(const QColor& val);
//@}
/// @name Prefix
//@{
const QString& prefix() const override;
void addPrefix(const QString& prefix) override;
/// Attributes name (Prefix added if set)
QString attName(const QString& name) const override;
//@}
private:
void copyValue(const XmlAttributeContainer& c) override;
void setupVtkValue() const;
void updateVtkValue() const;
mutable double* m_double {nullptr};
class Impl;
Impl* impl;
};
#ifdef _DEBUG
#include "private/colorcontainer_impl.h"
#endif // _DEBUG
#endif // COLORCONTAINER_H
| true |
45ef4f3f179017df2fbb564d20abe95f8df0d14f | C++ | jibee/STpp | /lib/PseudoPWMDisplay.cpp | UTF-8 | 1,710 | 2.625 | 3 | [] | no_license | #include <PseudoPWMDisplay.hpp>
#include <Irq.h>
PseudoPWMDisplay::PseudoPWMDisplay():
m_current_pixel_weight(0),
m_current_scanline(0),
m_current_pseudo_pwm_counter(0)
{
}
PseudoPWMDisplay::~PseudoPWMDisplay()
{
}
void PseudoPWMDisplay::tick()
{
if(m_active)
{
m_current_pseudo_pwm_counter--;
if(m_current_pseudo_pwm_counter<=0)
{
m_current_pseudo_pwm_counter = 1<<(m_current_pixel_weight-SKIP_LOW_WEIGHT_BITS);
activateFrame();
// Generic
shiftNextScanline();
// Specific
transferNextFrame();
}
}
}
void PseudoPWMDisplay::shiftNextScanline()
{
m_current_scanline++;
if(m_current_scanline>=SCANLINES)
{
m_current_scanline=0;
m_current_pixel_weight++;
if(m_current_pixel_weight>=BIT_PER_PIXEL)
{
m_current_pixel_weight=SKIP_LOW_WEIGHT_BITS;
}
}
}
bool PseudoPWMDisplay::colorHasComponent(uint32_t color, PseudoPWMDisplay::Component component, int weight)
{
return color & (1<<(weight+(component==Red?16:(component==Green?8:0))));
}
void PseudoPWMDisplay::setTimer(Platform::Timer& hwTimer)
{
hwTimer
// We need to be interrupted 102 400 times per second (25 fps, 256 PWM levels, 16 scanlines)
.setPrescaler(1<<SKIP_LOW_WEIGHT_BITS)
.setAutoReload(469)
.setCounter(469)
.setUIE(true)
.setURS(true)
.setOneShot(false)
.setTopCB([this](int){this->tick();});
Platform::Irq(hwTimer.irqNr()).setPriority(15).enable();
hwTimer
.enable();
}
void PseudoPWMDisplay::enterActiveMode()
{
m_active = true;
m_idle = false;
}
void PseudoPWMDisplay::enterIdleMode()
{
m_active = true;
m_idle = true;
}
void PseudoPWMDisplay::enterSleepMode()
{
m_active = false;
m_idle = true;
}
| true |
0455d597605355571c1016ffbb7b604510ad2adc | C++ | Maksemilian/dfs | /src/dfs_sync/sync_calc_delta_pps.h | UTF-8 | 2,689 | 2.65625 | 3 | [] | no_license | #ifndef SYNC_CALC_DALTA_PPS_H
#define SYNC_CALC_DALTA_PPS_H
#include "radio_channel.h"
#include <iostream>
#include <qglobal.h>
using namespace std;
using namespace proto::receiver;
/*! \addtogroup sync
*/
///@{
/*!
* \brief Класс для определения межканального смещения по шкале времени,
* измеряемого количеством отсчетов DDC. Смещение определяется
* разностью отсчетов после приема импульса PPS
* с одним и тем же номером в 1-ом и 2-ом каналах.
* Количество отсчетов после приема импульса PPS
* в каждом канале вычисляется по формуле:
* AfterPPS = NumBlock × SizeBlock – CntDDC.
*
* \todo Убрать ChannelData
*/
class CalcDeltaPPS
{
public:
CalcDeltaPPS(const ShPtrRadioChannel& channel1,
const ShPtrRadioChannel& channel2,
const ChannelData& data)
: _channel1(channel1), _channel2(channel2), _data(data) { }
/*!
* \brief Метод нахождения разности отсчетов DDC между двумя каналами
* после приема последнего импульса PPS.
* Из обоих каналов последовательно считываются данные до тех пор пока
* не будут полученны данные в обоих каналах.
* Если блоки считанных данных принадлежат к одной секунде происходит
* расчет количества ddc отсчетов после последнего импульса PPS для
* каждого канала. Затем определяется разность полученных значений ,
* которая является задержкой канала channel2 от канала channel1.
*
* \return смещение канала channel2 от channel1 ,
* выраженная разницой между ddc отсчетами двух каналов полученыыми
* после последнего импульса PPS.
*/
double findDeltaPPS();
private:
double calcDeltaPPS(const Packet _pct1, const Packet _pct2) const;
double ddcAfterPPS(const Packet& pct) const;
double deltaStart(const Packet _pct1, const Packet _pct2) ;
private:
ShPtrRadioChannel _channel1;
ShPtrRadioChannel _channel2;
ChannelData _data;
};
///@}
#endif // SYNC_CALC_DALTA_PPS_H
| true |
947206df27450fb1653466d55a1dead49b6376b6 | C++ | alexrush1/ilovelabs2 | /C++/1_lab(tritset)/tests.cpp | UTF-8 | 4,563 | 3.234375 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "tritset.h"
TEST_CASE("Creating tritset") {
tritset set(0);
REQUIRE(set.capacity() == 0);
REQUIRE(set.trit_capacity() == 0);
REQUIRE_THROWS_AS(tritset(-1), std::invalid_argument);
tritset set1(100);
REQUIRE(set1.capacity() == 25);
REQUIRE(set1.trit_capacity() == 100);
tritset set2(112);
REQUIRE(set2.capacity() >= 25);
}
TEST_CASE("Indexing operator and memory allocation") {
tritset set0(100);
tritset set1(200);
int allocLength0 = set0.capacity();
REQUIRE_THROWS_AS(set0[-2], std::invalid_argument);
set0[0] = trit::True;
set0[1] = trit::False;
set1[1] = trit::True;
REQUIRE(set0[0] == trit::True);
REQUIRE(set0[1] == trit::False);
REQUIRE(set0[2] == set1[0]);
set0[101] = trit::True;
REQUIRE(set0[101] == trit::True);
REQUIRE(set0.capacity() == allocLength0+1);
set0[113] = trit::False;
REQUIRE(set0[113] == trit::False);
REQUIRE(set0.capacity() == 29);
set0[130] = trit::Unknown;
REQUIRE(set0.capacity() == 29);
REQUIRE(set0[130] == trit::Unknown);
set0[0] = set1[209];
REQUIRE(set0[0] == trit::Unknown);
set0[130] = set1[209];
REQUIRE(set0.capacity() == 29);
REQUIRE(set0[130] == trit::Unknown);
set0[130] = set1[1];
REQUIRE(set0[130] == trit::True);
REQUIRE(set0.capacity() == 33);
set0[10] = set1[1];
set0[12] = set1[0];
REQUIRE(set0[10] == trit::True);
REQUIRE(set0[12] == trit::Unknown);
}
TEST_CASE("tritset = tritset") {
tritset a(10);
tritset b(16);
a[0] = trit::True;
a[2] = trit::False;
a[15] = trit::True;
b = a;
REQUIRE(b[0] == trit::True);
REQUIRE(b[2] == trit::False);
REQUIRE(b[15] == trit::True);
}
TEST_CASE("Bit operations") {
tritset a(10);
tritset b(20);
tritset d(5);
a[0] = trit::False;
a[1] = trit::True;
b[0] = trit::True;
b[1] = trit::False;
SECTION("Trit with Trit") {
REQUIRE((a[0] & a[1]) == trit::False);
REQUIRE((a[0] | b[0]) == trit::True);
REQUIRE((a[0] & a[3]) == trit::False);
REQUIRE((a[1] | b[4]) == trit::True);
REQUIRE((!a[0]) == trit::True);
REQUIRE((!b[4]) == trit::Unknown);
REQUIRE((a[0] & trit::False) == trit::False);
REQUIRE((b[0] | trit::True) == trit::True);
REQUIRE((!trit::False) == trit::True);
}
SECTION("tritset with tritset") {
d = (a & b);
REQUIRE(d.capacity() == b.capacity());
REQUIRE(d[1] == trit::False);
REQUIRE(d[20] == trit::Unknown);
d = (a | b);
REQUIRE(d[0] == trit::True);
REQUIRE(d[1] == trit::True);
d = (!a);
REQUIRE(d[0] == trit::True);
REQUIRE(d[1] == trit::False);
REQUIRE(d[12] == trit::Unknown);
}
}
TEST_CASE("Convenient Methods") {
tritset a(10), b(16);
SECTION("capacity") {
REQUIRE(a.capacity() == 3);
REQUIRE(b.capacity() == 4);
}
SECTION("trit_capacity") {
REQUIRE(a.trit_capacity() == 10);
REQUIRE(b.trit_capacity() == 16);
}
SECTION("Shrink") {
a[6] = trit::True;
a.shrink();
b.shrink();
REQUIRE(a.capacity() == 2);
REQUIRE(a.trit_capacity() == 7);
REQUIRE(b.capacity() == 0);
REQUIRE(b.trit_capacity() == 0);
tritset e(0);
e.shrink();
REQUIRE(e.capacity() == 0);
}
SECTION("Trit's Cardinality") {
a[0] = trit::True;
a[1] = trit::False;
a[2] = trit::False;
a[50] = trit::True;
a[46] = trit::False;
REQUIRE(a.cardinality(trit::True) == 2);
REQUIRE(a.cardinality(trit::False) == 3);
REQUIRE(a.cardinality(trit::Unknown) == 46);
REQUIRE(b.cardinality(trit::True) == 0);
}
SECTION("All Cardinalities") {
a[0] = trit::True;
a[1] = trit::False;
a[2] = trit::False;
a[50] = trit::True;
a[46] = trit::False;
std::unordered_map<trit, int> tempMap;
tempMap = a.cardinality();
REQUIRE(tempMap[trit::False] == 3);
REQUIRE(tempMap[trit::True] == 2);
REQUIRE(tempMap[trit::Unknown] == 46);
tempMap = b.cardinality();
REQUIRE(tempMap[trit::True] == 0);
REQUIRE(tempMap[trit::Unknown] == 16);
}
SECTION("Trim") {
b[10] = trit::True;
b[9] = trit::False;
b[1] = trit::True;
b.trim(9);
REQUIRE(b[10] == trit::Unknown);
REQUIRE(b[9] == trit::Unknown);
REQUIRE(b[1] == trit::True);
REQUIRE(b.capacity() == 4);
tritset e(0);
e.trim(0);
REQUIRE(e.capacity() == 0);
REQUIRE_THROWS_AS(a.trim(-2), std::invalid_argument);
REQUIRE_THROWS_AS(b.trim(17), std::invalid_argument);
}
SECTION("Length") {
a[7] = trit::True;
REQUIRE(a.t_length() == 8);
REQUIRE(b.t_length() == 0);
tritset e(0);
REQUIRE(e.t_length() == 0);
}
} | true |
606d15bfe1aade3e991edcc519ba114cf31b5e1d | C++ | svilchez0/hello-world | /hw02.cpp | UTF-8 | 2,434 | 3.59375 | 4 | [] | no_license | /*******************************************************************************
* AUTHOR : Samuel Vilchez
* STUDENT ID : 1078959
* HOMEWORK #2 : Deck of Cards
* CLASS : CS1C
* SECTION : MTWTh 4:30 - 7:25pm
* DUE DATE : 6/14/2018
******************************************************************************/
#include"MyHeader.h"
/*******************************************************************************
* DECK OF CARDS
* -----------------------------------------------------------------------------
* This program will simulate a deck of cards.
* It will perform a couple shuffles and will indicate how many shuffles are
* necessary for the deck to return to its original position
* -----------------------------------------------------------------------------
* INPUT
* <no input for this program>
*
* OUTPUT
* outputs the deck of cards dependent on the shuffle
******************************************************************************/
int main()
{
bool perfectShuffles; // CALC - determines when it returned to original
int numOfShuffles; // CALC - how many shuffles it takes to original
Deck myOriginalDeck; // CALC & OUT - first deck to be shuffled
Deck deckToBeShuffled; // CALC & OUT - second deck to be shuffled
cout << PrintHeader("Deck Of Cards", 'A', 2);
//INITIALIZATION
myOriginalDeck.InitializeDeckOfCards();
deckToBeShuffled.InitializeDeckOfCards();
//OUTPUT - orginial deck
cout << "The original deck is: \n";
myOriginalDeck.PrintDeckOfCards();
cout << endl;
//PROCESSING & OUTPUT - output after first shuffle
cout << "The deck after the first perfect shuffle: \n";
myOriginalDeck.PerformPerfectShuffle();
myOriginalDeck.PrintDeckOfCards();
//RE-INITIALIZE
myOriginalDeck.InitializeDeckOfCards();
//PROCESSING - check how many perfect shuffles until original
numOfShuffles = 0;
perfectShuffles = false;
while(!perfectShuffles)
{
deckToBeShuffled.PerformPerfectShuffle();
perfectShuffles = (myOriginalDeck == deckToBeShuffled);
numOfShuffles++;
}
cout << endl << endl;
//OUTPUT - final deck of cards
cout << "FINAL DECK IN ITS ORGINAL POSITION:" << endl;
deckToBeShuffled.PrintDeckOfCards();
cout << "It took " << numOfShuffles << " shuffles "
"for the deck to return to its original deck";
cout << endl;
return 0;
}
| true |
cb3e14400e134ce7b9b545033d2d0f29ba0083e5 | C++ | utec-cs-aed-2021-2/circular-array-erosCarhuancho | /stack.h | UTF-8 | 411 | 3.203125 | 3 | [] | no_license | #include "circulararray.h"
template <typename T>
class StackArray : public CircularArray<T> {
public:
StackArray(){StackArray(0);}
StackArray(int _capacity){
this->array = new T[_capacity];
this->capacity = _capacity;
this->front = this->back = -1;
}
void push(T data){
this->push_back(data);
}
T pop(){
T a=this->pop_back();
return a;
}
}; | true |
eb0336e9bf52a128772724c567b5a5b91728b187 | C++ | JRazek/lorem_ipsum | /gamefiles/Classes/headers/Map.h | UTF-8 | 1,111 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include "Configurable.h"
class Map: public Configurable{
std::map <std::string, std::string> settings;
const std::string map_directory_pattern = "map";//+id this is how the catalogs are called like. for example gamefiles/maps/map1
const std::string map_name_pattern = "map";//name of the file's pattern that maps are written in
const std::string map_config_pattern = "map_config";//name of the file's pattern that contains config of the map
std::string files_directory;//directory where the map files are in
std::string map_directory;
std::string config_directory;
std::string map_id;
int size_x;//size in x
int size_y;//size in y
char** mapa;//contains all the map chars
public:
Map(std::string, std::string);//directory where the maps are stored (./gamefiles/maps), name/id of the map (map1)
~Map();//destructor
int sizex();//returns x size
int sizey();//returns y size
void show_map_debugging();
char **display();//returns a pointer to an array that cointains all the map chars.
void foreach_settings();//foreaching all settings
}; | true |
cd10bec1882641674f2375a24605695bdcb7a0e6 | C++ | longqun/crpc | /crpc/trie.h | GB18030 | 2,613 | 3.234375 | 3 | [] | no_license | #ifndef CRPC_TRIE_H_
#define CRPC_TRIE_H_
#include <unordered_map>
template <typename T, typename Value>
class Trie
{
public:
struct TrieNode
{
//Ƿһڵ
bool is_word;
Value value;
std::unordered_map<T, TrieNode*> trie_map;
};
Trie()
{}
void insert(const T* buff, size_t size, const Value& value)
{
if (!size)
return;
TrieNode* cur = &_root;
for (size_t i = 0; i < size; ++i)
{
if (cur->trie_map[buff[i]] == NULL)
{
cur->trie_map[buff[i]] = new TrieNode();
}
cur = cur->trie_map[buff[i]];
}
cur->is_word = true;
cur->value = value;
}
bool find_prefix(const T* buff, size_t size, Value& ret)
{
bool found = false;
TrieNode* cur = &_root;
for (size_t i = 0; i < size; ++i)
{
auto itr = cur->trie_map.find(buff[i]);
if (itr == cur->trie_map.end())
return found;
cur = cur->trie_map[buff[i]];
if (cur->is_word)
{
found = true;
ret = cur->value;
}
}
return found;
}
void remove(const T* buff, size_t size)
{
if (!size)
return;
size_t last_word_pos = 0;
TrieNode* last_word, *cur;
last_word = cur = &_root;
for (size_t i = 0; i < size; ++i)
{
if (cur->trie_map.find(buff[i]) == cur->trie_map.end())
{
return;
}
TrieNode* pre = cur;
cur = cur->trie_map[buff[i]];
if (cur->is_word || cur->trie_map.size() > 1)
{
last_word_pos = i;
last_word = pre;
}
}
//123445
//123
//check valid
if (!cur || !cur->is_word || cur->trie_map.size())
return;
cur = last_word->trie_map[buff[last_word_pos]];
last_word->trie_map.erase(buff[last_word_pos]);
remove_internal(cur);
}
private:
void remove_internal(TrieNode* cur)
{
if (!cur)
return;
while (cur->trie_map.size())
{
auto itr = cur->trie_map.begin();
remove_internal(itr->second);
cur->trie_map.erase(itr->first);
}
delete cur;
}
TrieNode _root;
};
#endif
| true |
fce825511418fc2b2203ea53f545eebf3e0d4521 | C++ | kiminh/SimRank-1 | /APS/link_cut.cpp | UTF-8 | 3,712 | 3.109375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <utility>
#include <vector>
#include "link_cut.h"
using namespace std;
int depth(Node *x) {
access(x);
return x->sz - 1;
}
Node *lca(Node *x, Node *y) {
access(x);
return access(y);
}
void link(Node *x, Node *y) {
access(x);
access(y);
x->l = y;
y->p = x;
update(x);
}
void cut(Node *x) {
access(x);
x->l->p = 0;
x->l = 0;
update(x);
}
Node *root(Node *x) {
access(x);
while (x->l) x = x->l;
splay(x);
return x;
}
int Kth_ancestor(Node *x, int k) {
access(x);
Node *y = Kth_large(x, k + 1);
return y->label;
}
Node *Kth_large(Node *root, int k) {
// find k-th largest element in a splay tree
if (k < 1 || k > root->sz) {
return NULL;
}
int right_size = r_size(root);
if (k == right_size + 1) {
return root;
} else if (k > 1 + right_size) {
return Kth_large(root->l, k - right_size - 1);
} else {
return Kth_large(root->r, k);
}
}
int r_size(Node *x) {
// size of right sub-tree
if (x->r) {
return x->r->sz;
} else {
return 0;
}
}
Node *access(Node *x) {
splay(x);
if (x->r) {
x->r->pp = x;
x->r->p = 0;
x->r = 0;
update(x);
}
Node *last = x;
while (x->pp) {
Node *y = x->pp;
last = y;
splay(y);
if (y->r) {
y->r->pp = y;
y->r->p = 0;
}
y->r = x;
x->p = y;
x->pp = 0;
update(y);
splay(x);
}
return last;
}
void splay(Node *x) {
Node *y, *z;
while (x->p) {
y = x->p;
if (y->p == 0) {
if (x == y->l) rotr(x);
else rotl(x);
} else {
z = y->p;
if (y == z->l) {
if (x == y->l) rotr(y), rotr(x);
else rotl(x), rotr(x);
} else {
if (x == y->r) rotl(y), rotl(x);
else rotr(x), rotl(x);
}
}
}
update(x);
}
void update(Node *x) {
x->sz = 1;
if (x->l) x->sz += x->l->sz;
if (x->r) x->sz += x->r->sz;
}
void rotr(Node *x) {
Node *y, *z;
y = x->p, z = y->p;
if ((y->l = x->r)) y->l->p = y;
x->r = y, y->p = x;
if ((x->p = z)) {
if (y == z->l) z->l = x;
else z->r = x;
}
x->pp = y->pp;
y->pp = 0;
update(y);
}
void rotl(Node *x) {
Node *y, *z;
y = x->p, z = y->p;
if ((y->r = x->l)) y->r->p = y;
x->l = y, y->p = x;
if ((x->p = z)) {
if (y == z->l) z->l = x;
else z->r = x;
}
x->pp = y->pp;
y->pp = 0;
update(y);
}
// int main(){
// int n = 8;
// LinkCut lc(n+1);
// vector<pair<int,int>> links = {
// {1,2},
// {2,4},
// {4,5},
// {3,4},
// {7,6},
// {8,6},
// {6,5}
// };
// for(auto &item:links){
// lc.link(item.first, item.second);
// }
// vector<pair<int,int>> query_pairs = {
// {1,1},
// {1,2},
// {1,3},
// {3,1},
// {3,2},
// {7,1},
// {7,2},
// {8,1},
// {8,2}
// };
// for(auto &pair:query_pairs){
// cout << pair.first << " " <<
// pair.second << ": " << lc.kth_ans(pair.first,pair.second)<< endl;
// }
// save(lc, string("iotest.txt"));
// LinkCut loaded_lc;
// load(loaded_lc, string("iotest.txt"));
// cout << "after load" << endl;
// for(auto &pair:query_pairs){
// cout << pair.first << " " <<
// pair.second << ": " << loaded_lc.kth_ans(pair.first,pair.second)<< endl;
// }
// }
| true |
bb1da6f2094c01e8b3921379965ac1ca9d3a0f05 | C++ | mikechen66/CPP-Programming | /CPP-Programming-Language/chapter10-expression/ex07/error.cpp | UTF-8 | 222 | 2.75 | 3 | [] | no_license | #include "error.h"
// Prints a syntax error message
void Error::skip(istream* input)
{
while(char ch = static_cast<char>(input->get()))
{
if(ch == '\n' || ch == ';')
return;
}
}
| true |
6a97c2ba8947c2137b20228ff42ccac95c5e959e | C++ | marinov98/Statistical_Calculator | /src/correlation.hpp | UTF-8 | 951 | 2.625 | 3 | [] | no_license | /* ########################
Name: Marin Pavlinov Marinov
file: correlation.hpp
purpose: correlation header file. Calculates slope, y-intercept, LSRL line and Correlation Coefficient
######################## */
#include "basics.hpp"
#include <iostream>
#include <vector>
// printing functions
void displayDatasetXY(const std::vector<double>& datasetX, const std::vector<double>& datasetY);
void displayLSRL(const std::vector<double>& datasetX,
const std::vector<double>& datasetY);
// calculation functions
// Correlation Coefficient
double calculateCorrelationCoefficient(const std::vector<double>& datasetX,
const std::vector<double>& datasetY);
// Slope
double calculateSlope(const std::vector<double>& datasetX,
const std::vector<double>& datasetY);
// Y-intercept
double calculateYintercept(const std::vector<double>& datasetX,
const std::vector<double>& datasetY);
| true |
1097643412058c470bc78d900e40f232c6e48d94 | C++ | szqh97/test | /cpp/designpattern/AbstractFactory/AbstractFactory.h | UTF-8 | 1,221 | 2.765625 | 3 | [] | no_license |
#ifndef _AbstractFactory_H_
#define _AbstractFactory_H_
#include "Product.h"
class AbstractProductA;
class AbstractProductB;
class AbstracFactory
{
public:
AbstracFactory ();
virtual ~AbstracFactory ();
virtual AbstractProductA* createProductA() = 0;
virtual AbstractProductB* createProductB() = 0;
protected:
private:
}; /* ----- end of class AbstracFactory ----- */
class ConcreteFactory1 : public AbstracFactory
{
public:
ConcreteFactory1 ();
~ConcreteFactory1 ();
AbstractProductA* createProductA();
AbstractProductB* createProductB();
protected:
private:
}; /* ----- end of class ConcreteFactory1 ----- */
class ConcreteFactory2 : public AbstracFactory
{
public:
ConcreteFactory2 ();
~ConcreteFactory2 ();
AbstractProductA* createProductA();
AbstractProductB* createProductB();
protected:
private:
}; /* ----- end of class ConcreteFactory2 ----- */
#endif /* ----- #ifndef _AbstractFactory_H_ ----- */
| true |
de2170a8e5ffeccf33056930f4226f362d991b4e | C++ | Guurkha/projekt | /tictac/tictac/State.hpp | WINDOWS-1250 | 468 | 2.515625 | 3 | [] | no_license | #pragma once
namespace Sonar
{
class State
{
public:
virtual void Init() = 0; //initialize the state
virtual void HandleInput() = 0; //all input in particular state
virtual void Update(float dt) = 0; //anything input from user -> np jak klawisz czy cos
virtual void Draw(float dt) = 0; //after ingput it will drwa -> z frame per second.
virtual void Pause() {} // pausa jak dziaa
virtual void Resume() {} // jak dziala wznowienie
};
} | true |
b281345c51246ba1e45c57284382ad0a197a0830 | C++ | wozenwho/networkingExample | /TCPTest/tcpserver.cpp | UTF-8 | 1,957 | 2.921875 | 3 | [] | no_license | #include "tcpserver.h"
#define SERVER_TCP_PORT 9999 // Default port
#define BUFLEN 1200 //Buffer length
#define MAX_NUM_CLIENTS 30
#define TRUE 1
#define FALSE 0
TCPServer::TCPServer()
{
}
/**
*
*
*
*/
int32_t TCPServer::initializeSocket (short port)
{
struct sockaddr_in server;
if ((tcpSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror ("Can't create a socket");
std::cout << strerror(errno) << std::endl;
exit(1);
}
int optFlag = 1;
if(setsockopt(tcpSocket, SOL_SOCKET, SO_REUSEADDR, &optFlag, sizeof(optFlag)) == -1)
{
perror("set opts failed");
return -1;
}
// Zero memory of server sockaddr_in struct
bzero((char *)&server, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY); // Accept connections from any client
if (bind(tcpSocket, (struct sockaddr *)&server, sizeof(server)) == -1)
{
perror("Can't bind name to socket");
std::cout << strerror(errno) << std::endl;
exit(1);
}
listen(tcpSocket, MAX_NUM_CLIENTS);
return 1;
}
/**
*
*
*
*/
int32_t TCPServer::acceptConnection(EndPoint* client)
{
sockaddr_in clientAddr;
socklen_t addrSize = sizeof(clientAddr);
memset(&clientAddr, 0, addrSize);
int clientSocket;
if ((clientSocket = accept(tcpSocket, (struct sockaddr *)&clientAddr, &addrSize)) == -1)
{
std::cout << strerror(errno) << std::endl;
return 0;
}
client->port = ntohs(clientAddr.sin_port);
client->addr = ntohl(clientAddr.sin_addr.s_addr);
return clientSocket;
}
/**
*
*
*
*/
int32_t TCPServer::sendBytes(int clientSocket, char * data, unsigned len)
{
return send(clientSocket, data, len, 0);
}
/**
*
*
*
*/
int32_t TCPServer::receiveBytes(int clientSocket, char * buffer, unsigned len)
{
size_t n = 0;
size_t bytesToRead = len;
while ((n = recv (clientSocket, buffer, bytesToRead, 0)) < len)
{
buffer += n;
bytesToRead -= n;
}
return (len - bytesToRead);
}
| true |
1b8696832a48c5fd3b11a34e2aa22afec79b1c3a | C++ | NikitaBannikow/AiG4sem_2 | /Implementation.cpp | UTF-8 | 9,496 | 3.03125 | 3 | [] | no_license | // This program was made by Bannikov Nikita, group 9309
#include "Header.h"
#include<iostream>
#include<algorithm>
#include<cmath>
bool compareByCountDescend(const _Character& sym_a, const _Character& sym_b)
{
return (sym_a->count > sym_b->count);
}
bool compareByCountAscend(const _Character& sym_a, const _Character& sym_b)
{
return (sym_a->count < sym_b->count);
}
static std::ifstream::pos_type filesize(string filename)
{
std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
int CharacterVector::loadRawDataFromFile(string fileName)
{
inFile.open(fileName, ios::binary);
unsigned char temp;
while (inFile >> noskipws >> temp) {
rawData.push_back(temp);
}
inFile.close();
return filesize(fileName);
}
void CharacterVector::printFile()
{
for (int i = 0; i < rawData.size(); ++i)
cout << rawData[i];
cout << endl;
}
void CharacterVector::findUnique()
{
for (long i = 0; i < rawData.size(); ++i) {
int j;
for (j = 0; j < symbol_in_data.size(); ++j) {
if (symbol_in_data[j]->value == rawData[i] && !symbol_in_data[j]->isHead) {
++symbol_in_data[j]->count;
break;
}
}
if (j == symbol_in_data.size()) {
symbol_in_data.push_back(new Character(rawData[i], 1, 0, false));
}
}
computeFreq();
}
void CharacterVector::listUnique()
{
for (int i = 1; i < symbol_in_data.size(); ++i) {
cout << symbol_in_data[i]->value << '\t'
<< symbol_in_data[i]->count << '\t'
<< symbol_in_data[i]->relativeFreq << endl;
}
}
int CharacterVector::getNumUnique()
{
return symbol_in_data.size() - 1;
}
int CharacterVector::getNumTotal()
{
return rawData.size();
}
float CharacterVector::computeEnt()
{
float entropy = 0;
for (int i = 1; i < symbol_in_data.size(); ++i) {
entropy -= symbol_in_data[i]->relativeFreq * log2(symbol_in_data[i]->relativeFreq);
}
return entropy;
}
void CharacterVector::sortSymbolDescend()
{
sortedSymbolDescend.assign(symbol_in_data.begin(), symbol_in_data.end());
sort(sortedSymbolDescend.begin() + 1, sortedSymbolDescend.end(), compareByCountDescend);
}
void CharacterVector::sortSymbolAscend()
{
sortedSymbolAscend.assign(symbol_in_data.begin(), symbol_in_data.end());
sort(sortedSymbolAscend.begin() + 1, sortedSymbolAscend.end(), compareByCountAscend);
}
// Prints characters frequency to console
void CharacterVector::listSortedDescend()
{
for (int i = 1; i < sortedSymbolDescend.size(); ++i) {
cout << " " << sortedSymbolDescend[i]->value << '\t'
<< sortedSymbolDescend[i]->count << '\t'
<< sortedSymbolDescend[i]->relativeFreq << endl;
}
}
// Prints characters frequency to console
void CharacterVector::listSortedAscend()
{
for (int i = 1; i < sortedSymbolAscend.size(); ++i) {
cout << " " << sortedSymbolAscend[i]->value << '\t'
<< sortedSymbolAscend[i]->count << '\t'
<< sortedSymbolAscend[i]->relativeFreq << endl;
}
}
void BinaryTree::splitNode(int n)
{
for (int i = nodeVector.size() + 1; i <= 2 * n + 1; ++i) {
nodeVector.push_back(new treeNode(i, '\0', 0, 0, 0));
}
for (int i = 0; i <= n - 1; ++i) {
nodeVector[i]->left_child = nodeVector[2 * i + 1];
nodeVector[i]->right_child = nodeVector[2 * i + 2];
}
}
void BinaryTree::assignValue(int n, unsigned char att, float freq)
{
nodeVector[n - 1]->attribute = att;
nodeVector[n - 1]->relativeFreq = freq;
}
int BinaryTree::getLength()
{
return nodeVector.size();
}
void BinaryTree::getNode(int n)
{
cout << nodeVector[n - 1]->index << '\t' << nodeVector[n - 1]->attribute <<
'\t' << nodeVector[n - 1]->relativeFreq << endl;
}
void BinaryTree::printTree()
{
for (int i = 0; i < nodeVector.size(); ++i) {
if (nodeVector[i]->attribute != '\0') {
cout << nodeVector[i]->index << '\t' << nodeVector[i]->attribute
<< '\t' << nodeVector[i]->relativeFreq << endl;
}
}
}
Node BinaryTree::mergeNode(Node& node_a, Node& node_b)
{
Node newParent = new treeNode(0, '\0', node_a->relativeFreq + node_b->relativeFreq,
node_a, node_b, 0, false);
node_a->parent = newParent;
node_b->parent = newParent;
return newParent;
}
string ShannonFanoEncoder::dec2binEncode(int n)
{
vector<bool> binNum;
while (n / 2 != 0) {
binNum.push_back(n % 2);
n /= 2;
}
binNum.push_back(n % 2);
string bitString;
for (int i = binNum.size(); i > 0; --i) {
if (binNum[i - 1])
bitString.push_back('1');
else
bitString.push_back('0');
}
return bitString;
}
int ShannonFanoEncoder::bin2dec(list<unsigned char> buffer)
{
int symbolDec = 0, countDigit = buffer.size() - 1;
for (list<unsigned char>::iterator i = buffer.begin(); i != buffer.end(); ++i) {
symbolDec += int((*i) == '1') * pow(2, countDigit--);
}
return symbolDec;
}
void ShannonFanoEncoder::buildShannonFanoTree(int start, int end, float maxFreq, int currentNode)
{
if (start >= end)
cerr << "Error! No symbol input." << endl;
else if (start == end - 1) {
assignValue(currentNode, sortedSymbolDescend[end]->value, sortedSymbolDescend[end]->relativeFreq);
}
else {
splitNode(currentNode);
float sumFreq = 0;
int i = start, separateIdx;
while (sumFreq < maxFreq / 2 && i < end - 1) {
sumFreq += sortedSymbolDescend[i + 1]->relativeFreq;
++i;
}
if ((sumFreq < maxFreq / 2) ||
((sumFreq - maxFreq / 2) < (maxFreq / 2 - sumFreq + sortedSymbolDescend[i]->relativeFreq))) {
separateIdx = i;
}
else {
separateIdx = i - 1;
sumFreq -= sortedSymbolDescend[i]->relativeFreq;
}
buildShannonFanoTree(start, separateIdx, sumFreq, 2 * currentNode);
buildShannonFanoTree(separateIdx, end, maxFreq - sumFreq, 2 * currentNode + 1);
}
}
void ShannonFanoEncoder::encodeShannonFano()
{
for (int i = 1; i < nodeVector.size(); ++i) {
if (nodeVector[i]->relativeFreq > 0 && nodeVector[i]->relativeFreq < 1) {
CodesTable.push_back(new ShannonFanoCodeWord);
CodesTable.back()->symbol = nodeVector[i]->attribute;
CodesTable.back()->relativeFreq = nodeVector[i]->relativeFreq;
CodesTable.back()->decIndex = nodeVector[i]->index;
CodesTable.back()->binCode = dec2binEncode(nodeVector[i]->index).erase(0, 1);
}
}
}
// Print assigned binary codes
void ShannonFanoEncoder::printCodes()
{
for (int i = 1; i < CodesTable.size(); ++i) {
cout << " " << i << '\t' << CodesTable[i]->symbol <<
'\t' << CodesTable[i]->binCode << endl;
}
}
int ShannonFanoEncoder::encodeToFile(string fileName)
{
outFile.open(fileName, ios::binary);
string tempEncodedString;
list<unsigned char> outputBuffer;
for (long i = 0; i < rawData.size(); ++i) {
for (int j = 0; j < CodesTable.size(); ++j) {
if (rawData[i] == CodesTable[j]->symbol) {
tempEncodedString.append(CodesTable[j]->binCode);
}
}
}
for (long i = 0; i < tempEncodedString.size(); ++i) {
if (i == 0) {
outputBuffer.push_back(tempEncodedString[i]);
}
else if (i == tempEncodedString.size() - 1 && i % 8 != 0) {
outputBuffer.push_back(tempEncodedString[i]);
outFile << unsigned char(bin2dec(outputBuffer));
}
else if (i % 8 == 0 && i != 0) {
outFile << unsigned char(bin2dec(outputBuffer));
outputBuffer.clear();
outputBuffer.push_back(tempEncodedString[i]);
}
else {
outputBuffer.push_back(tempEncodedString[i]);
}
}
outFile.close();
return filesize(fileName);
}
string ShannonFanoDecoder::dec2binDecode(int n)
{
vector<bool> binNum;
while (n / 2 != 0) {
binNum.push_back(n % 2);
n /= 2;
}
binNum.push_back(n % 2);
if (binNum.size() < 8) {
for (int i = binNum.size(); i < 8; ++i)
binNum.push_back(0);
}
string bitString;
for (int i = binNum.size(); i > 0; --i) {
if (binNum[i - 1])
bitString.push_back('1');
else
bitString.push_back('0');
}
return bitString;
}
void ShannonFanoDecoder::decodeEncodedFile(string inFileName, string outFileName)
{
readEncodedFile.open(inFileName, ios::binary);
string tempDecodedString, decodeBuffer;
vector<unsigned char> tempCharVector;
unsigned char readNext;
while (readEncodedFile >> noskipws >> readNext) {
tempCharVector.push_back(readNext);
}
readEncodedFile.close();
for (int i = 0; i < tempCharVector.size(); ++i) {
if (i != tempCharVector.size() - 1) {
tempDecodedString.append(dec2binDecode(int(tempCharVector[i])));
}
else
tempDecodedString.append(dec2binEncode(int(tempCharVector[i])));
}
outFile.open(outFileName, ios::binary);
for (int i = 0; i < tempDecodedString.size(); ++i) {
decodeBuffer.push_back(tempDecodedString[i]);
for (int j = 1; j < CodesTable.size(); ++j) {
if (CodesTable[j]->binCode == decodeBuffer) {
outFile << CodesTable[j]->symbol;
decodeBuffer.clear();
break;
}
}
}
outFile.close();
}
// Compare files
bool Utils::compareFiles(const std::string& p1, const std::string& p2) {
std::ifstream f1(p1, std::ifstream::binary | std::ifstream::ate);
std::ifstream f2(p2, std::ifstream::binary | std::ifstream::ate);
if (f1.fail() || f2.fail()) {
return false;
}
if (f1.tellg() != f2.tellg()) {
return false;
}
f1.seekg(0, std::ifstream::beg);
f2.seekg(0, std::ifstream::beg);
return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(f2.rdbuf()));
} | true |
6ff5cc91e010e54bd205aaf4d65b295008fadcc7 | C++ | Astru43/school | /lab2_t1/lab2_t1.ino | UTF-8 | 1,012 | 2.53125 | 3 | [] | no_license | #define LED 12 //
volatile byte count=00; //sekunnit
volatile byte count2=00; //minuutit
volatile byte count3=00; //tunnit
void setup()
{
Serial.begin(9600);
Serial.print("Timer int test \n");
pinMode(LED, OUTPUT);
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 62500; // compare match register 16MHz/256/2Hz
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}
void loop()
{
}
ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine
{
count++;
Serial.print("Timer count: ");
Serial.print(count3);
Serial.print(":");
Serial.print(count2);
Serial.print(":");
Serial.print(count);
Serial.print("\n");
if (count == 59){ //sekunnit
count2++;
count = -1;
}
if (count2 == 60){ //minuutit
count3++;
count2 = 0;
}
if (count3 == 24){ //tunnit
count3 = 0;
}
digitalWrite(LED, digitalRead(LED) ^ 1); //xor
}
| true |
2a2a483bbc8bc978fe08cb70852d85578feb3bfc | C++ | purvasingh96/HackerRank-solutions | /algorithm/Hashing/10. distinct elements in every window.cpp | UTF-8 | 535 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<map>
using namespace std;
int main(){
int n, i, k;
cin>>k;
cin>>n;
int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
map<int, int> m;
int dc=0;
int j;
for(j=0;j<k;j++){
if(m[a[j]]==0){
dc++;
}
m[a[j]]+=1;
}
cout<<dc<<"\n";
for(j=k;j<n;j++){
if(m[a[j-k]]==1){
dc--; //as tit had count of 1 it counted for dc, now we are removing it so we have to reduce dc by 1
}
m[a[j-k]]-=1;
if(m[a[j]]==0){
dc++;
}
m[a[j]]+=1;
cout<<dc<<"\n";
}
}
| true |
9a01185cd8db598572ceedd705144b586d544df4 | C++ | ndlwill1020/OBB4cocos2dx3.2 | /Classes/OBB.hpp | UTF-8 | 3,886 | 2.734375 | 3 | [] | no_license | //
// OBB.hpp
// OBBDemo
//
// Created by macuser on 16/6/6.
// 参考博客:http://blog.csdn.net/tom_221x/article/details/38457757
//
#ifndef OBB_hpp
#define OBB_hpp
#include "cocos2d.h"
USING_NS_CC;
//弧度 radian
//半径 radius
/*
把2个矩形的半径距离投影到检测轴上
把2个矩形的中心点连线投影到检测轴上
判断2个矩形的中心连线投影和2个矩形的半径投影之和的大小
*/
//向量概念:
//单位向量是指模等于1的向量
/// 没有涉及到node的缩放 (涉及的话 改变一些相应的属性即可)
class OBB : public Ref{
public:
static OBB* createWithNode(Node *node);
bool initWithNode(Node *node);
bool isContainPoint(const Vec2 &point);
bool isCollision(OBB *otherOBB);
/***************set && get****************/
//get set
inline Vec2* getOriginCorners(){
return originCorners;
};
//nodeCenterPosition set && get
inline void setNodeCenterPosition(const Vec2 &point){
this->nodeCenterPosition = point;
// log("*****************obb set center point****************");
// log("x:%f y:%f",this->nodeCenterPosition.x, this->nodeCenterPosition.y);
};
inline Vec2 getNodeCenterPosition(){
return this->nodeCenterPosition;
};
//corners[4] set && get
inline void setCorners(const Vec2 *corners){
this->corners[0] = *corners;
this->corners[1] = *(corners + 1);
this->corners[2] = *(corners + 2);
this->corners[3] = *(corners + 3);
// log("*****************obb set corners****************");
// log("x:%f y:%f",this->corners[0].x, this->corners[0].y);
// log("x:%f y:%f",this->corners[1].x, this->corners[1].y);
// log("x:%f y:%f",this->corners[2].x, this->corners[2].y);
// log("x:%f y:%f",this->corners[3].x, this->corners[3].y);
};
inline Vec2* getCorners(){
return corners;
};
//nodeSize set && get
inline void setNodeSize(const Size &size){
this->nodeSize = size;
};
inline Size getNodeSize(){
return this->nodeSize;
};
//axes[2] set && get
inline Vec2* getAxes(){
return axes;
};
/**************************************/
//for test
inline void getDescription(){
log("*************OBB*************");
};
private:
OBB();
~OBB();
//一个向量点乘一个单位向量,我们得到的是这个向量在这个单位向量上的投影长度#####
//向量点乘 a点乘b=|a|×|b|×coc(a,b)几何定义 a点乘b = a.x * b.x + a.y * b.y代数定义
//b=identityVec为单位向量
float vectorDotProduct(const Vec2& vec, const Vec2& identityVec);
//当一个向量a为单位向量(大小为1)
//它的坐标 旋转angle a=(cos(angle),sin(angle))//a为mid right
//因为垂直cos(90度)=0 所以a点乘b=0 所以与a垂直的单位向量b为(-sin(angle),cos(angle))
void setCheckAxesByRotation(float rotateAngle);
//矩形两条半径投影
//矩形2条检测轴的向量和就是矩形中心点到矩形一个顶点(拐点)的向量,所以投影半径也是矩形中心点到矩形顶点的向量投影长度
//核心:2个矩形检测过程中,每次以一个矩形的检测轴为坐标系,投影另一个矩形的检测轴#####
float getProjectionLength(const Vec2 &identityAxis);
private:
//矩形的4个拐角点 0:lower left 1:lower right 2:upper right 3:upper left
Vec2 originCorners[4];//for test
Vec2 corners[4];//旋转后
//矩形的2条检测轴的向量坐标(与矩形中心点(0,0)的连线) 0:水平轴
Vec2 axes[2];//它为单位向量
Vec2 nodeCenterPosition;
Size nodeSize;
};
#endif /* OBB_hpp */
| true |
c6b95ac19aa6e46105f344f686b208fe44a1b766 | C++ | VolodiaPG/penguin | /src/game_logic/AbstractGame.hpp | UTF-8 | 1,803 | 3.203125 | 3 | [] | no_license | #ifndef ABSTRACT_GAME_HPP_
#define ABSTRACT_GAME_HPP_
#include <vector>
#include "utils/Move.hpp"
namespace game
{
template <class, class, class>
class AbstractBoard;
template <class CellT, class PlayerT, class PawnT>
class AbstractGame
{
public:
AbstractBoard<CellT, PlayerT, PawnT> *board;
explicit AbstractGame(AbstractBoard<CellT, PlayerT, PawnT> *board);
explicit AbstractGame(const AbstractGame<CellT, PlayerT, PawnT> &) = default;
virtual ~AbstractGame(){};
/**
* @brief Tells if the game is finished yet
*
* @return true
* @return false
*/
virtual bool isFinished() const = 0;
// /**
// * @brief play one round of the game
// *
// * @return the played cell
// */
// virtual AbstractBoardCell *play(AbstractPlayer *p1, AbstractPlayer *p2) = 0;
virtual bool play(PawnT *pawn, CellT *cell) = 0;
virtual const Move<CellT, PawnT> revertPlay() = 0;
/**
* @brief Get the player who hadn't play yet
*
* @return const int the player id
*/
virtual unsigned int getPlayerToPlay() = 0;
/**
* @brief Checks the status of the game, if won, draw
*
* @return int when won : the id of the winner, -1 if draw, 0 otherwise
*/
virtual int checkStatus() const = 0;
/**
* @brief Get the available moves to a player
*
* @param player the player (the human one)
* @return Move containing all the necessary informations
*/
virtual std::vector<Move<CellT, PawnT>> getAvailableMoves(PlayerT *player) = 0;
/**
* @brief Clone function for clonning games
*
* @return AbstractGame*
*/
virtual AbstractGame<CellT, PlayerT, PawnT> *clone() const = 0;
};
} // namespace game
#endif | true |
a4fcf0f19ef3a6cc05575847f3b96583e17de112 | C++ | cavapoo2/modern_cpp_book_stuff | /algorithm/codility/prefixModSum.cpp | UTF-8 | 280 | 2.625 | 3 | [] | no_license | //not sure if its fully tested but got 100% on codility
int solution(int A, int B, int K) {
if(A == B) return (A % K) == 0 ? 1 : 0;
if (B < K) return 0;
while(A % K != 0 && A < B) {
A++;
}
int diff = B-A;
int r = diff / K;
return r + 1;
}
| true |
a4c2a2e956c23850d6e53ba419ac9a151e7a91a2 | C++ | lowkey42/BanishedBlaze | /src/core/ecs/entity_handle.hpp | UTF-8 | 5,680 | 2.65625 | 3 | [
"MIT"
] | permissive | /** Handle (unique versioned id) of an entity + generator ********************
* *
* Copyright (c) 2016 Florian Oetke *
* This file is distributed under the MIT License *
* See LICENSE file for details. *
\*****************************************************************************/
#pragma once
#include "../utils/atomic_utils.hpp"
#include "../utils/log.hpp"
#include <moodycamel/concurrentqueue.hpp>
#include <cstdint>
#include <vector>
#include <string>
namespace lux {
namespace ecs {
class Entity_manager;
using Entity_id = int32_t;
class Entity_handle {
public:
using packed_t = uint32_t;
static constexpr uint8_t free_rev = 0b10000; // marks revisions as free,
// is cut off when assigned to Entity_handle::revision
constexpr Entity_handle() : _id(0), _revision(0) {}
constexpr Entity_handle(Entity_id id, uint8_t revision) : _id(id), _revision(revision) {}
constexpr explicit operator bool()const noexcept {
return _id!=0;
}
constexpr Entity_id id()const noexcept {
return _id;
}
constexpr void id(Entity_id id)noexcept {
_id = id;
}
constexpr uint8_t revision()const noexcept {
return _revision;
}
constexpr void revision(uint8_t revision)noexcept {
_revision = revision;
}
void increment_revision()noexcept {
_revision++;
}
constexpr packed_t pack()const noexcept {
return static_cast<packed_t>(_id)<<4 | static_cast<packed_t>(_revision);
}
static constexpr Entity_handle unpack(packed_t d)noexcept {
return Entity_handle{static_cast<int32_t>(d>>4), static_cast<uint8_t>(d & 0b1111)};
}
private:
int32_t _id:28;
uint8_t _revision:4;
};
constexpr inline bool operator==(const Entity_handle& lhs, const Entity_handle& rhs)noexcept {
return lhs.id()==rhs.id() && lhs.revision()==rhs.revision();
}
constexpr inline bool operator!=(const Entity_handle& lhs, const Entity_handle& rhs)noexcept {
return lhs.id()!=rhs.id() || lhs.revision()!=rhs.revision();
}
inline bool operator<(const Entity_handle& lhs, const Entity_handle& rhs)noexcept {
return std::make_tuple(lhs.id(),lhs.revision()) < std::make_tuple(rhs.id(),rhs.revision());
}
static_assert(sizeof(Entity_handle::packed_t)<=sizeof(void*),
"what the hell is wrong with your plattform?!");
inline Entity_handle to_entity_handle(void* u) {
return Entity_handle::unpack(static_cast<Entity_handle::packed_t>(
reinterpret_cast<std::intptr_t>(u)) );
}
inline void* to_void_ptr(Entity_handle h) {
return reinterpret_cast<void*>(static_cast<std::intptr_t>(h.pack()));
}
constexpr const auto invalid_entity = Entity_handle{};
constexpr const auto invalid_entity_id = invalid_entity.id();
extern auto get_entity_id(Entity_handle h, Entity_manager&) -> Entity_id;
extern auto entity_name(Entity_handle h) -> std::string;
class Entity_handle_generator {
using Freelist = moodycamel::ConcurrentQueue<Entity_handle>;
public:
Entity_handle_generator(Entity_id max=128) {
_slots.resize(static_cast<std::size_t>(max));
}
// thread-safe
auto get_new() -> Entity_handle {
Entity_handle h;
if(_free.try_dequeue(h)) {
auto& rev = util::at(_slots, static_cast<std::size_t>(h.id()-1));
auto expected_rev = static_cast<uint8_t>(h.revision()|Entity_handle::free_rev);
h.revision(static_cast<uint8_t>(rev & ~Entity_handle::free_rev)); // mark as used
bool success = rev.compare_exchange_strong(expected_rev, h.revision());
INVARIANT(success, "My handle got stolen :(");
return h;
}
auto slot = _next_free_slot++;
return {slot+1, 0};
}
// thread-safe
auto valid(Entity_handle h)const noexcept -> bool {
return h && (static_cast<Entity_id>(_slots.size()) <= h.id()-1
|| util::at(_slots, static_cast<std::size_t>(h.id()-1)) == h.revision());
}
// NOT thread-safe
auto free(Entity_handle h) -> Entity_handle {
if(h.id()-1 >= static_cast<Entity_id>(_slots.size())) {
_slots.resize(static_cast<std::size_t>(h.id()-1) *2, 0);
}
auto rev = util::at(_slots, static_cast<std::size_t>(h.id()-1)).load();
auto handle = Entity_handle{h.id(), rev};
handle.increment_revision();
// mark as free; no CAS required only written here and in get_new() if already in _free
util::at(_slots, static_cast<std::size_t>(h.id()-1)).store(
handle.revision() | Entity_handle::free_rev );
_free.enqueue(handle);
return {handle};
}
// NOT thread-safe
auto next(Entity_handle curr=invalid_entity)const -> Entity_handle {
// internal_id = external_id - 1, so we don't need to increment it here
auto end = _next_free_slot.load();
for(Entity_id id=curr.id(); id<end; id++) {
if(id>=static_cast<Entity_id>(_slots.size())) {
return Entity_handle{id+1,0};
} else {
auto rev = util::at(_slots, static_cast<std::size_t>(id)).load();
if((rev & ~Entity_handle::free_rev)==rev) { // is marked used
return Entity_handle{id+1,rev};
}
}
}
return invalid_entity;
}
// NOT thread-safe
void clear() {
_slots.clear();
_slots.resize(_slots.capacity(), 0);
_next_free_slot = 0;
_free = Freelist{}; // clear by moving a new queue into the old
}
private:
util::vector_atomic<uint8_t> _slots;
std::atomic<Entity_id> _next_free_slot{0};
Freelist _free;
};
}
}
| true |
49207545b05c8f02f3b224168189bcfe50c7d031 | C++ | drexxcbba/ITMOCOURSE_CP | /SegTreeSum.cpp | UTF-8 | 2,294 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Segment Tree structure
struct segtree{
int size;
vector<long long> sums;
void init(int n){
//Initializing this Segment Tree empty
size = 1;
while(size < n) size *= 2;
sums.assign(2 * size, 0LL);
}
void build(vector<long long> &a, int curr, int lx, int rx){
if(rx - lx == 1){
if(lx < (int) a.size()){
sums[curr] = a[lx];
}
return;
}
int m = (lx + rx) / 2;
build(a, 2 * curr + 1, lx, m);
build(a, 2 * curr + 2, m, rx);
sums[curr] = sums[2 * curr + 1] + sums[2 * curr + 2];
}
void build(vector<long long> &a){
build(a, 0, 0, size);
}
//Checking the current node
void set(int i, int v, int curr, int lx, int rx){
//We are in one leaf..
if(rx - lx == 1){
sums[curr] = v;
return;
}
int m = (lx + rx) / 2;
if(i < m){
//Go to the left part
set(i, v, 2 * curr + 1, lx, m);
}else{
//Go to the right part
set(i, v, 2 * curr + 2, m, rx);
}
//Reconstructing the sum
sums[curr] = sums[2 * curr + 1] + sums[2 * curr + 2];
}
void set(int i, int v){
//Search the node begining in the root
set(i, v, 0, 0, size);
}
long long getSum(int l, int r, int curr, int lx, int rx){
//Out of the border
if(lx >= r || l >= rx) return 0;
//Inside
if(lx >= l && rx <= r) return sums[curr];
int m = (lx + rx) / 2;
long long left = getSum(l, r, 2 * curr + 1, lx, m);
long long right = getSum(l, r, 2 * curr + 2, m, rx);
return left + right;
}
long long getSum(int l, int r){
return getSum(l, r, 0, 0, size);
}
};
int main() {
ios::sync_with_stdio(false);
int n, m;
cin>>n>>m;
segtree st;
st.init(n);
//Creating the Segment Tree in n log n time
/*
for (int i = 0; i < n; i++){
long long v;
cin>>v;
st.set(i, v);
}
*/
//Creating the Segment Tree in a linear time
vector<long long> a (n);
for (int i = 0; i < n; i++) cin>>a[i];
st.build(a);
//Working on querys
while (m--){
int q;
cin>>q;
if(q == 1){
int i, v;
cin>>i>>v;
st.set(i, v);
} else{
int l, r;
cin>>l>>r;
cout<<st.getSum(l ,r)<< "\n";
}
}
return 0;
} | true |
77cfced2b0bd77c292e871d32350705bfd7983c1 | C++ | sahininayanthara/median | /Untitled11.cpp | UTF-8 | 466 | 3.328125 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int i,j,n,x,array[100];
float f;
printf("Enter total number of elements\n");
scanf("%d",&n);
printf("Enter elements of the array\n");
for(i=0;i<n;i++){
scanf("%d",&array[i]);
}
for(i=0;i<n-1;i++){
for(j=i+1;j<n;j++){
if(array[i]>array[j]){
x=array[i];
array[i]=array[j];
array[j]=x;
}
}
}
if(n%2==0)
{
f=array[n/2]+array[n/2-1]/2.0;
} else{
f=array[(n)/2];
printf("\nMedian=%f",f);
}
return 0;
} | true |
75c3428a186b958255e7fb1bfeec880add955b66 | C++ | llenroc/leetcode-ac | /cpp-leetcode/leetcode448-find-all-numbers-disappeared-in-an-array.cpp | UTF-8 | 626 | 3.140625 | 3 | [
"MIT"
] | permissive | #include<algorithm>
#include<vector>
#include<unordered_set>
#include<iostream>
using namespace std;
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
unordered_set<int> se(nums.begin(), nums.end());
int i = 0;
int n = nums.size(); // 原始的size
vector<int>res;
for(i = 1; i <= n; ++i){
if(se.find(i) == se.end())
res.push_back(i);
}
return res;
}
};
int main()
{
Solution sol;
vector<int> nums = { 4,3,2,7,8,2,3,1 };
auto res = sol.findDisappearedNumbers(nums);
return 0;
} | true |
d4fcf48a649a91865b66027eee7620c9b385f5a3 | C++ | Escapist0516/SEU_LEX-YACC | /seu_yacc/construct_table.cpp | GB18030 | 7,071 | 3.03125 | 3 | [] | no_license | /*
construct_table.cpp
*/
/*
룺һķG'
G'lrĺactiongoto
1G'lrdfa
2״̬iIiõ״̬iĹȷ
1[A->xaBb]IiУgotoIia=Ijôaction[i,a]Ϊ"j"aһս
2[A->x,a]IiУA!=S'ôaction[i,a]Ϊ"ԼA->x"
3[S'->S$]IiУaction[i,$]Ϊ""
3״̬iڸսgotogotoIiA=Ijôgoto[i,A]=j
4δõΪerror
5ʼ״̬ǰ[S'->S$]״̬
*/
#include "construct_table.h"
void construct_table(
int boundN, //(ս+ս-1
int boundT, //(ս-1
LRDFA dfa, //(ķ״̬Զ
vector<pair<int, vector<int>>> production_vec,
vector<pair<int, vector<int>>> pre_rules,
vector<vector<pair<char, int>>> &table//ɵ
)
{
//ÿdfa״̬һ
for (int i = 0; i < dfa.statesVec.size(); i++)
{
//ǰ
vector<pair<char, int>> temp_state;
//Ȼÿһֿܵ룬ѹӦӦִеĶ
//ӦboundN+2
//boundN+1: ս+սټһ$ܹboundN+2,±Ϊ[0--boundN+1]
//ȰеĿո
pair<char, int>pair_error('e',-1);
for (int j=0;j<=boundN+1;j++)
{
temp_state.push_back(pair_error);
}
//ֱƽԼ
//ȴƽ
for (auto& action : dfa.statesVec[i].edgesMap)
{
if (action.first <= boundT)
//ս$֮ǰ
{
pair<char, int>temp_s('s', action.second);
temp_state[action.first]=temp_s;
}
else
//Ƿս$֮
{
pair<char, int>temp_s('s', action.second);
temp_state[action.first+1] = temp_s;
}
}
//ȻԼ,鿴ǰ״̬ÿʽ
for (auto& temp_item : dfa.statesVec[i].LRItemsSet)
{
//ڲʽôйԼҪ
if (temp_item.Dotpos == production_vec[temp_item.Label].second.size())
{
//Ԥ
int predictive_symbol = temp_item.Symbol;
if (predictive_symbol == -2)
{
predictive_symbol = boundT + 1; //ҵ$
//[S'->S$]ôaction[i,$]Ϊ""
if (temp_item.Label == 1)
{
pair<char, int>temp_a('a', temp_item.Label);
temp_state[predictive_symbol] = temp_a;
//continue;
}
}
//λѾзǴ
if (temp_state[predictive_symbol].first != 'e')
{
//-ԼͻǹԼ-Լͻ
//-Լͻ
if (temp_state[predictive_symbol].first == 's')
{
int last;//ʽһս
int predPrior = -1, lastPrior = -1; //predPrior¼ԤȼlastPrior¼ÿitemһսȼ
for (int m = production_vec[temp_item.Label].second.size() - 1; m >= 0; m--)
{
//ʼңҵòʽһս
if (production_vec[temp_item.Label].second[m] <= boundT)
{
last = production_vec[temp_item.Label].second[m];
break;
}
}
//ȼжλһսԤȼ˳
for (int p = 0; p < pre_rules.size(); p++)
{
//ÿһ磺pair<int, vector<string>>
//ǰʾ/ҽϣһǾż
for (int q = 0; q < pre_rules[p].second.size(); q++)
{
//ҵԤ
if (temp_item.Symbol == pre_rules[p].second[q])
{
//ȼԽȼԽ
predPrior = p; //¼Ԥȼ
}
//ҵһս
if (last == pre_rules[p].second[q])
{
//ȼԽȼԽ
lastPrior = p; //¼һսȼ
}
}
}
//ȼͰչƽ
if (predPrior != -1 && lastPrior != -1)
{
//һսȼߣԼƽ
if (lastPrior >= predPrior)
{
pair<char, int>temp_r('r', temp_item.Label);
temp_state[predictive_symbol] = temp_r;
}
}
}
//ǹԼ-Լͻ
if (temp_state[predictive_symbol].first == 'r')
{
//ѡȼĹԼĿйԼ
//ǰIJʽԼ
if (temp_state[predictive_symbol].second > temp_item.Label)
{
temp_state[predictive_symbol].second = temp_item.Label;
}
}
}
//ͻֱ뼴
else
{
pair<char, int>temp_r('r', temp_item.Label);
temp_state[predictive_symbol] = temp_r;
}
}
}
// ѹջ
table.push_back(temp_state);
}
} | true |
96fe2b99233fbe050c2e42f32265741ebcfaef54 | C++ | flashpoint493/shiny-octo-archer | /PlaceDescriptionService/PlaceDescriptionService/AddressExtractorTest.cpp | UTF-8 | 1,850 | 3.21875 | 3 | [] | no_license | #include "gmock/gmock.h"
#include "AddressExtractor.h"
#include <algorithm>
#include <string>
using namespace std;
using namespace testing;
class AnAddressExtractor: public Test {
public:
AddressExtractor extractor;
};
//as originally written, the matcher IsEmpty() collides with a built in matcher of gmock
MATCHER(IsEmptyAddress, "") {
return
arg.road.empty() &&
arg.city.empty() &&
arg.state.empty() &&
arg.country.empty();
}
TEST_F(AnAddressExtractor, ReturnsAnEmptyAddressOnAFailedParse) {
auto address = extractor.addressFrom("not valid json");
ASSERT_THAT(address, IsEmptyAddress());
}
TEST_F(AnAddressExtractor, ReturnsAnEmptyAddressWhenNoAddressFound) {
auto json = "{\"place_id\":\"15331615\"}";
auto address = extractor.addressFrom(json);
ASSERT_THAT(address, IsEmptyAddress());
}
TEST_F(AnAddressExtractor, ReturnsPopulatedAddressForValidJsonResult) {
auto json = "{\"place_id\":\"15331615\",\"address\":{\"road\":\"War Eagle Court\",\"city\":\"Colorado Springs\",\"state\":\"Colorado\",\"country\":\"United States of America\"}}";
auto address = extractor.addressFrom(json);
ASSERT_THAT(address.road, Eq("War Eagle Court"));
ASSERT_THAT(address.city, Eq("Colorado Springs"));
ASSERT_THAT(address.state, Eq("Colorado"));
ASSERT_THAT(address.country, Eq("United States of America"));
}
TEST_F(AnAddressExtractor, DefaultsNonexistentFieldsToEmpty) {
auto json = "{\"place_id\":\"15331615\",\"address\":{\"road\":\"War Eagle Court\",\"city\":\"Colorado Springs\",\"country\":\"United States of America\"}}";
auto address = extractor.addressFrom(json);
//ASSERT_THAT(address.state, Eq(""));
//using the built in matcher is empty. can do this as address.state is a string, and IsEmpty works on "STL-like containers" and string implements .empty() and .size()
ASSERT_THAT(address.state, IsEmpty());
}
| true |
5d5b1aa6ca75ae01ec5e6b755e1a50344d393cdc | C++ | author-tiffany/Computer-Programming-Projects | /HW5_EX2.cpp | UTF-8 | 5,660 | 3.578125 | 4 | [] | no_license | // Author: Tiffany Lourdraj
// Course: CS1336
// Date: September 23th 2018
// Assignment: Lecture lesson #5 Exercise #2
// Compiler: Apple Xcode
// Description: You will be calculating the number of seconds it will take for sound to travel though a medium.
//
#include <iostream>
#include <iomanip>
#include<math.h>
using namespace std;
int main()
{
char choicePackage;
double minutes;
double valueA = 0;// this is the value if the minutes is under
double valueA2 = 0 ;
double valueA3 = 0 ;
double valueB = 0;
double valueB2 = 0; // package A minutes cost
double valueB3 = 0;// package c minutes cost
double valueC = 0;
double valueC2 = 0; // package A minutes cost
double valueC3 = 0; // package B minutes cost
cout << "Select the monthly Package plan:"<< endl ;
cout << "1.A" << endl;
cout << "2.B" << endl;
cout << "3.C" << endl;
cin >> choicePackage;
{
if(choicePackage=='a' || choicePackage=='A') // this is the if else statement for calculating the total cost if the package is choice A
{
choicePackage=1;
cout << "Enter minutes (in whole minutes)" << endl;
cin >> minutes;
{
if( minutes>450)
{
valueA = (minutes*.45)+39.99;
{
if (minutes >900)
{
valueA2 = (minutes*.40)+59.99;
}
else
{
valueA2 = 59.99;
}
}
valueA3 = 69.99;
}
else
{
valueA = 39.99;
valueA2= 59.99;
valueA3=69.99;
}
}
}
else if(choicePackage=='b' || choicePackage=='B') // this is the if else statement for calculating the total cost if the package is choice B
{
choicePackage=2;
cout << "Enter minutes (in whole minutes)" << endl;
cin >> minutes;
{
if (minutes>900)
{
valueB = (minutes*.40)+59.99;
valueB2= (minutes*.45)+39.99;
valueB3= 69.99;
}
else
{
valueB = 59.99;
valueB2=39.99;
valueB3=69.99;
}
}
}
else if(choicePackage=='c' || choicePackage=='C') // this is the if else statement for calculating the total cost if the package is choice C
{
choicePackage=3;
cout << "Enter minutes (in whole minutes)" << endl;
cin >> minutes;
{
if(minutes>0)
{
valueC= 69.99;
{
if(minutes>900)
{
valueC3=(minutes*.40)+59.99;
}
else
valueC3= 59.99;
}
if(minutes>450)
{
valueC2= (minutes*.45)+39.99;
}
else
valueC2= 39.99;
}
}
}
else
{
cout << "Enter a valid package" << endl;
}
if(choicePackage==1)
{
if (valueA>valueA2 && valueA>valueA3)
{
cout << "total package cost: $" << valueA<< "Congrats, you chose the best value for you minutes!" << endl;
}
if ( valueA2 > valueA)
{
cout << "your monthly bill is: " << valueA << "However, package B is cheaper at: $" << valueA2<< endl;
}
{
if (valueA3 > valueA)
{
cout << "your monthly bill is: " << valueA << "However, package C is cheaper at: $" << valueA3<< endl;
}
}
}
if(choicePackage==2)
{
if (valueB>valueB2 && valueB>valueB3)
{
cout << "total package cost: $" << valueB << "Congrats, you chose the best value for you minutes!" << endl;
}
if ( valueB2 > valueB)
{
cout << "your monthly bill is: " << valueB << "However, package A is cheaper at: $" << valueB2<< endl;
}
{
if (valueA3 > valueA)
{
cout << "your monthly bill is: " << valueB << "However, package C is cheaper at: $" << valueB3<< endl;
}
}
}
if(choicePackage==3)
{
if (valueC>valueC2 && valueC>valueC3)
{
cout << "total package cost: $" << valueC<< "Congrats, you chose the best value for you minutes!" << endl;
}
if ( valueC2 > valueC)
{
cout << "your monthly bill is: " << valueC << "However, package B is cheaper at: $" << valueC2 << endl;
}
{
if (valueC3 > valueC)
{
cout << "your monthly bill is: " << valueC << "However, package C is cheaper at: $" << valueC3 << endl;
}
}
}
}
return 0;
}
| true |
68c6a8ece45c12e6ec33df22b27d15dfd91682cd | C++ | sid1980/CylinderOSG | /Figure.cpp | UTF-8 | 443 | 3 | 3 | [] | no_license | #include "Figure.h"
void Figure::setPosition(vec p)
{
position = p;
}
void Figure::setRotation(double angle, vec p)
{
rotation.push_back(angle);
for (double d : p.v)
{
rotation.push_back(d);
}
}
void Figure::setColor(vec c)
{
color = c;
}
vec Figure::getColor()
{
return color;
}
vec Figure::getPosition()
{
return position;
}
std::vector<double> Figure::getRotation()
{
return rotation;
} | true |
7a8b510007a21fe3c9d75e2df89380d27c03a974 | C++ | uttam-bhanu/STL | /map/map.cpp | UTF-8 | 581 | 3.328125 | 3 | [] | no_license | #include <map>
using namespace std;
int main()
{
map<int, string> m;
m.insert(pair<int,string> (1, "jhon"));
m.insert(pair<int,string> (2, "rahul"));
m.insert(pair<int,string> (3, "ravi"));
map<int, string>::iterator itr;
for(itr = m.begin(); itr != m.end(); itr++)
std::cout << itr->first<< " " << itr->second << std::endl;
std::cout << "found value is" << std::endl;
map<int, string>::iterator itr1;
itr1 = m.find(2);
std::cout << itr1->first<< " " << itr1->second << std::endl;
return 0;
}
| true |
7e27e3eb8493522de0ffd99af2535050366a9c8a | C++ | Kevin-WangXing/CDMA_myself | /insert_celldlg.cpp | GB18030 | 3,600 | 2.609375 | 3 | [] | no_license | #include <QGridLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QDate>
#include "insert_celldlg.h"
insert_cellDlg::insert_cellDlg(QWidget *parent) :
QDialog(parent)
{
cellidlabel = new QLabel;
cellidlabel->setText(tr("վ"));
cellid = new QLineEdit;
cellnamelabel = new QLabel;
cellnamelabel->setText(tr("վ"));
cellname = new QLineEdit;
bscidlabel = new QLabel;
bscidlabel->setText(tr("վ"));
bscid = new QLineEdit;
createdatelabel = new QLabel;
createdatelabel->setText(tr("ѡվ"));
createdate = new QDateEdit;
createdate->setDisplayFormat("yyyy-M-d");
createdate->setDate(QDate::currentDate());
longitudelablel = new QLabel;
longitudelablel->setText(tr("վ"));
longitude = new QLineEdit;
latitudelabel = new QLabel;
latitudelabel->setText(tr("վγ"));
latitude = new QLineEdit;
descriptionlabel = new QLabel;
descriptionlabel->setText(tr("վ"));
description = new QLineEdit;
okBtn = new QPushButton;
okBtn->setText(tr(""));
cancelBtn = new QPushButton;
cancelBtn->setText(tr("ȡ"));
QGridLayout *layout1 = new QGridLayout(this);
layout1->addWidget(cellidlabel, 0, 0);
layout1->addWidget(cellid, 0, 1);
layout1->addWidget(cellnamelabel, 1, 0);
layout1->addWidget(cellname, 1, 1);
layout1->addWidget(createdatelabel, 2, 0);
layout1->addWidget(createdate, 2, 1);
layout1->addWidget(bscidlabel, 3, 0);
layout1->addWidget(bscid, 3, 1);
layout1->addWidget(createdatelabel, 4, 0);
layout1->addWidget(createdate, 4, 1);
layout1->addWidget(longitudelablel, 5, 0);
layout1->addWidget(longitude, 5, 1);
layout1->addWidget(latitudelabel, 6, 0);
layout1->addWidget(latitude, 6, 1);
layout1->addWidget(descriptionlabel, 7, 0);
layout1->addWidget(description, 7, 1);
QHBoxLayout *layout2 = new QHBoxLayout();
layout2->addWidget(okBtn);
layout2->addWidget(cancelBtn);
layout1->addLayout(layout2, 8, 1);
layout1->setColumnStretch(0, 1);
layout1->setColumnStretch(1, 3);
layout1->setMargin(15);
layout1->setSpacing(10);
connect(okBtn,SIGNAL(clicked()), this, SLOT(okBtnOnclick()));
connect(cancelBtn,SIGNAL(clicked()), this, SLOT(cancelBtnOnclick()));
isok = false;
setWindowIcon(QIcon("main.png"));
setWindowTitle(tr("ӻվ"));
cellid->setFocus();
}
//#define INSERTCELL "<SQL>INSERT INTO cells (cellid, name, createdate, description) VALUES (%1, '%2', str_to_date('%3','%Y-%m-%d %H:%i:%s'), '%4')"
#define INSERTCELL "insert into cells (cellid, cellname, bscid, createdate, longitude, latitude, description) values (%1, '%2', %3, str_to_date('%4','%Y-%m-%d %H:%i:%s'),'%5', '%6', '%7')"
void insert_cellDlg::okBtnOnclick()
{
if (cellid->text().trimmed().isEmpty())
{
QMessageBox::information(this, tr(""), tr("վŲΪ"));
cellid->setFocus();
return ;
}
if (cellname->text().trimmed().isEmpty())
{
QMessageBox::information(this, tr(""), tr("վƲΪ"));
cellname->setFocus();
return ;
}
isok = true;
SQL = QString(INSERTCELL).arg(cellid->text()).arg(cellname->text()).arg(bscid->text()).arg(createdate->text()).arg(longitude->text()).arg(latitude->text()).arg(description->text());
close();
}
void insert_cellDlg::cancelBtnOnclick()
{
close();
}
| true |
558481f2c24d2154a6061188ac6e0bbd8f6538f7 | C++ | MasterJH5574/CS158-DS-Project | /vector/data/three/code.cpp | UTF-8 | 1,188 | 3.03125 | 3 | [] | no_license | #include "vector.hpp"
#include "class-integer.hpp"
#include "class-matrix.hpp"
#include "class-bint.hpp"
#include <iostream>
#include <fstream>
#include <string>
void TestInteger()
{
std::cout << "Test for classes without default constructor..." << std::endl;
sjtu::vector<Integer> vInt;
for (int i = 1; i <= 100; ++i) {
vInt.push_back(Integer(i));
}
std::cout << "Test OK..." << std::endl;
}
void TestMatrix()
{
std::cout << "Test for my Matrix..." << std::endl;
sjtu::vector<Diamond::Matrix<double>> vM;
for (int i = 1; i <= 10; ++i) {
vM.push_back(Diamond::Matrix<double>(i, i, i));
}
for (size_t i = 0; i < vM.size(); ++i) {
std::cout << vM[i] << std::endl;
}
}
void TestBint()
{
std::cout << "Test for big integer" << std::endl;
sjtu::vector<Util::Bint> vBint;
for (long long i = 1LL << 50; i < (1LL << 50) + 10; ++i) {
vBint.push_back(Util::Bint(i) * i);
}
for (sjtu::vector<Util::Bint>::iterator it = vBint.begin(); it != vBint.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
}
int main()
{
TestInteger();
TestMatrix();
TestBint();
} | true |
d62902327f2b60025df546718429f622354bb5a6 | C++ | mwindson/leetcode | /src/cpp/313.super-ugly-number.cpp | UTF-8 | 1,746 | 3.53125 | 4 | [] | no_license | /*
* @lc app=leetcode id=313 lang=cpp
*
* [313] Super Ugly Number
*
* https://leetcode.com/problems/super-ugly-number/description/
*
* algorithms
* Medium (45.77%)
* Likes: 1612
* Dislikes: 304
* Total Accepted: 108.5K
* Total Submissions: 236.6K
* Testcase Example: '12\n[2,7,13,19]'
*
* A super ugly number is a positive integer whose prime factors are in the
* array primes.
*
* Given an integer n and an array of integers primes, return the n^th super
* ugly number.
*
* The n^th super ugly number is guaranteed to fit in a 32-bit signed
* integer.
*
*
* Example 1:
*
*
* Input: n = 12, primes = [2,7,13,19]
* Output: 32
* Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first
* 12 super ugly numbers given primes = [2,7,13,19].
*
*
* Example 2:
*
*
* Input: n = 1, primes = [2,3,5]
* Output: 1
* Explanation: 1 has no prime factors, therefore all of its prime factors are
* in the array primes = [2,3,5].
*
*
*
* Constraints:
*
*
* 1 <= n <= 10^5
* 1 <= primes.length <= 100
* 2 <= primes[i] <= 1000
* primes[i] is guaranteed to be a prime number.
* All the values of primes are unique and sorted in ascending order.
*
*
*/
// @lc code=start
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int> &primes) {
vector<int> index(primes.size(), 0);
vector<long> nums(n, LONG_MAX);
nums[0] = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < index.size(); j++) {
nums[i] = min(nums[i], nums[index[j]] * primes[j]);
}
for (int j = 0; j < index.size(); j++) {
if (nums[i] == nums[index[j]] * primes[j]) {
index[j]++;
}
}
}
return nums[n - 1];
}
};
// @lc code=end
| true |
e7793df0989d5ad910bd2807a806407ece33938d | C++ | Tanjoodo/6502emu | /6502emu/register_procedures.cpp | UTF-8 | 1,678 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "register_procedures.h"
#include "global_registers.h"
using namespace reg;
void _setBit(bool value, int bit_num)
{
if (value)
Status = Status | (1 << bit_num);
else
Status = Status & ~(1 << bit_num);
}
bool _getBit(int bit_num)
{
uint8_t temp_s = Status;
temp_s = temp_s >> bit_num;
return temp_s & 1;
}
uint8_t _get_low(uint16_t address)
{
return address & 0x00FF;
}
uint8_t _get_high(uint16_t address)
{
return (address >> 8) & 0x00FF;
}
void SetFlagC(bool state)
{
_setBit(state, 0);
}
void SetFlagZ(bool state)
{
_setBit(state, 1);
}
void SetFlagI(bool state)
{
_setBit(state, 2);
}
void SetFlagD(bool state)
{
_setBit(state, 3);
}
void SetFlagB(bool state)
{
_setBit(state, 4);
}
void SetFlagV(bool state)
{
_setBit(state, 6);
}
void SetFlagN(bool state)
{
_setBit(state, 7);
}
bool GetFlagC()
{
return _getBit(0);
}
bool GetFlagZ()
{
return _getBit(1);
}
bool GetFlagI()
{
return _getBit(2);
}
bool GetFlagD()
{
return _getBit(3);
}
bool GetFlagB()
{
return _getBit(4);
}
bool GetFlagV()
{
return _getBit(6);
}
bool GetFlagN()
{
return _getBit(7);
}
void IncrementPC(uint8_t val)
{
uint16_t pc = (uint16_t)reg::PCH << 8 | reg::PCL;
pc += val;
reg::PCH = (pc >> 8) & 0x00FF;
reg::PCL = pc & 0x00FF;
reg::pc_changed_externally = true;
}
void DecrementPC(uint8_t val)
{
uint16_t pc = (uint16_t)reg::PCH << 8 | reg::PCL;
pc -= val;
reg::PCH = (pc >> 8) & 0x00FF;
reg::PCL = pc & 0x00FF;
reg::pc_changed_externally = true;
}
void SetPC(uint16_t val)
{
reg::PCH = _get_high(val);
reg::PCL = _get_low(val);
reg::pc_changed_externally = true;
}
uint16_t GetPC()
{
return (uint16_t)reg::PCH << 8 | reg::PCL;
} | true |
e4d4672200fe70c2b6f4ed2f55515ba1bfd3dfa7 | C++ | xyztiger/CodeForces | /ACM-ICPC/2020-NARPC/B.cpp | UTF-8 | 365 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<int> & dynamicProgram(vector<int> & dp) {
}
int main() {
int s, p, m, n;
cin >> s >> p >> m >> n;
vector<int> days;
for (int i = 0; i < n; i++) {
int d;
cin >> d;
days.push_back(d);
}
int vector<int> dp(n, 0);
if (s < p) {
dp[0] = s;
} else {
dp[0] = p;
}
return 0;
}
| true |
6992ad79b1576db5bb83603cdd42cdf6917d2845 | C++ | shahar2112/Master-Minions | /include/dispatcher.hpp | UTF-8 | 4,502 | 3.109375 | 3 | [] | no_license | /******************************************************************************/
/* Dispatcher implementation */
/* Author - Dean Oron */
/* Date - */
/******************************************************************************/
#ifndef __ILRD_RD8586_DISPATCHER_HPP__
#define __ILRD_RD8586_DISPATCHER_HPP__
#include <iostream>
#include <boost/function.hpp> /* function */
#include <boost/noncopyable.hpp> //non-copyable classes
#include "logger.hpp"
using namespace std;
// A defult function to bind with callback death function
static void EmptyFunc()
{
}
template < typename DISPATCHER >
class Callback;
template < typename T >
class Dispatcher : private boost::noncopyable
{
public:
Dispatcher()
{
}
~Dispatcher();
typedef T dataType; // nested type
void Subscribe(Callback<Dispatcher <T> >* callback);
void Unsubscribe(Callback<Dispatcher <T> >* callback);
void Notify(dataType data);
private:
std::list<Callback<Dispatcher <T> > *> m_callbacks;
};
template < typename DISPATCHER >
class Callback : private boost::noncopyable
{
public:
typedef boost::function< void(typename DISPATCHER::dataType) > CallbackPointer;
typedef boost::function< void() > DeathPointer;
Callback(const CallbackPointer& callback_func, const DeathPointer& death_func = &EmptyFunc);
~Callback();
private:
void Link(DISPATCHER* dispatch);
void Unlink();
void Invoke(typename DISPATCHER::dataType data);
CallbackPointer m_callback_func;
DeathPointer m_death_func;
DISPATCHER* m_dispatcher;
struct FriendHelper{typedef DISPATCHER MyDispatcher;};
friend class FriendHelper::MyDispatcher;
};
template < typename T >
class InvokeFunctor
{
public:
InvokeFunctor(T data):m_data(data){}
void operator()(Callback< T > *callback)
{
callback->Invoke(m_data);
}
private:
T m_data;
};
template < typename T >
class UnlinkFunctor
{
public:
void operator()(Callback< T > *callback)
{
callback->Unlink();
}
};
template < typename SOURCE >
Callback<SOURCE>::Callback(const CallbackPointer& callback_func,const DeathPointer& death_func)
: m_callback_func(callback_func), m_death_func(death_func), m_dispatcher(NULL)
{
if (!callback_func)
{
LOG_ERROR("callback function was not supplied");
}
if (!death_func)
{
LOG_WARNING("death_func was not supplied");
}
}
template < typename DISPATCHER >
Callback<DISPATCHER>::~Callback()
{
if (m_dispatcher)
{
m_dispatcher->Unsubscribe(this);
}
}
template < typename T >
void Dispatcher<T>::Subscribe(Callback<Dispatcher <T> >* callback)
{
assert(callback);
if (!callback)
{
LOG_ERROR("Did not recieved callback to subscribe");
}
m_callbacks.push_back(callback);
callback->Link(this);
}
template < typename DISPATCHER >
inline void Callback<DISPATCHER>::Link(DISPATCHER *dispatcher)
{
assert(!m_dispatcher);
assert(dispatcher);
if (!dispatcher)
{
LOG_ERROR("Dispatcher was not sent properly");
}
m_dispatcher = dispatcher;
}
template < typename T >
void Dispatcher<T>::Unsubscribe(Callback<Dispatcher <T> >* callback)
{
if (!callback)
{
LOG_WARNING("Did not recieved callback to unsubscribe");
}
callback->Unlink();
m_callbacks.remove(callback);
}
template < typename DISPATCHER >
inline void Callback<DISPATCHER>::Unlink()
{
assert(m_dispatcher);
m_dispatcher = NULL;
m_death_func();
}
template < typename T >
inline void Dispatcher<T>::Notify(dataType handle)
{
if (!m_callbacks.empty())
{
typename std::list<Callback<Dispatcher<T> > *>::iterator it = m_callbacks.begin();
for (; it != m_callbacks.end(); ++it)
{
(*it)->Invoke(handle);
}
}
else
{
LOG_WARNING("No subscriber is registered to dispatch");
}
}
template < typename DISPATCHER >
inline void Callback<DISPATCHER>::Invoke(typename DISPATCHER::dataType handle)
{
assert(m_dispatcher);
m_callback_func(handle);
}
template < typename T >
Dispatcher<T>::~Dispatcher()
{
if(!m_callbacks.empty())
{
typename std::list<Callback<Dispatcher<T> > *>::iterator it = m_callbacks.begin();
for (; it != m_callbacks.end(); ++it)
{
(*it)->Unlink();
}
}
}
#endif // __ILRD_RD8586_DISPATCHER_HPP__ | true |
8803da2c2259272e1ec5e78b86fe04d63e9d4d64 | C++ | wakuwinmail/my_shojin | /AtCoder/ABC/116/A.cpp | UTF-8 | 170 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
int main(){
int a,b,c;
std::cin>>a>>b>>c;
std::cout<<a*b*c/(std::max(std::max(a,b),c)*2)<<std::endl;
return 0;
} | true |
99b429a881d38a5711cfa6551db17fd4d61c5a38 | C++ | darkraven74/cg | /tests/convex.cpp | UTF-8 | 2,788 | 2.5625 | 3 | [] | no_license |
#include <gtest/gtest.h>
#include <boost/assign/list_of.hpp>
#include <cg/operations/convex.h>
#include <cg/convex_hull/graham.h>
#include <misc/random_utils.h>
#include "random_utils.h"
using namespace util;
TEST(convex, 1)
{
using cg::point_2;
std::vector<point_2> pts = boost::assign::list_of(point_2(0, 0));
EXPECT_TRUE(cg::convex(cg::contour_2(pts)));
}
TEST(convex, 2)
{
using cg::point_2;
std::vector<point_2> pts = boost::assign::list_of(point_2(0, 0))
(point_2(1, 0));
EXPECT_TRUE(cg::convex(cg::contour_2(pts)));
}
TEST(convex, 3)
{
using cg::point_2;
std::vector<point_2> pts = boost::assign::list_of(point_2(0, 0))
(point_2(5, 0))
(point_2(2, 2));
EXPECT_TRUE(cg::convex(cg::contour_2(pts)));
}
TEST(convex, 4)
{
using cg::point_2;
std::vector<point_2> pts = boost::assign::list_of(point_2(0, 0))
(point_2(5, 0))
(point_2(5, 5))
(point_2(0, 5));
EXPECT_TRUE(cg::convex(cg::contour_2(pts)));
}
TEST(convex, 5)
{
using cg::point_2;
std::vector<point_2> pts = boost::assign::list_of(point_2(0, 0))
(point_2(5, 0))
(point_2(5, 5))
(point_2(4, 5))
(point_2(0, 5));
EXPECT_TRUE(cg::convex(cg::contour_2(pts)));
}
TEST(convex, 6)
{
using cg::point_2;
std::vector<point_2> pts = boost::assign::list_of(point_2(0, 0))
(point_2(5, 0))
(point_2(4, 11))
(point_2(5, 10));
EXPECT_FALSE(cg::convex(cg::contour_2(pts)));
}
TEST(convex, 7)
{
using cg::point_2;
std::vector<point_2> pts = boost::assign::list_of(point_2(0, 0))
(point_2(5, 0))
(point_2(7, 10))
(point_2(4, 2))
(point_2(3, 20));
EXPECT_FALSE(cg::convex(cg::contour_2(pts)));
}
TEST(convex, uniform)
{
using cg::point_2;
std::vector<point_2> pts = uniform_points(100);
std::vector<point_2>::iterator it = cg::graham_hull(pts.begin(), pts.end());
pts.resize(std::distance(pts.begin(), it));
EXPECT_TRUE(cg::convex(cg::contour_2(pts)));
}
| true |