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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c2e3686e083a2cb7f1c628ca43b1d540e5a94aaa | C++ | rahulrj/MTV | /HackerRank/STRINGS/STRINGSIMILARITY.cpp | UTF-8 | 2,128 | 2.953125 | 3 | [] | no_license | https://www.hackerrank.com/challenges/string-similarity
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void getZarr(string str, int Z[],int n)
{
//int n = str.length();
int L, R, k;
// [L,R] make a window which matches with prefix of s
L = R = 0;
// cout<<"!"<<endl;
for (int i = 1; i < n; ++i)
{
// if i>R nothing matches so we will calculate.
// Z[i] using naive way.
if (i > R)
{
L = R = i;
// R-L = 0 in starting, so it will start
// checking from 0'th index. For example,
// for "ababab" and i = 1, the value of R
// remains 0 and Z[i] becomes 0. For string
// "aaaaaa" and i = 1, Z[i] and R become 5
while (R<n && str[R-L] == str[R])
R++;
Z[i] = R-L;
R--;
}
else
{
// k = i-L so k corresponds to number which
// matches in [L,R] interval.
k = i-L;
// if Z[k] is less than remaining interval
// then Z[i] will be equal to Z[k].
// For example, str = "ababab", i = 3, R = 5
// and L = 2
if (Z[k] < R-i+1)
Z[i] = Z[k];
// For example str = "aaaaaa" and i = 2, R is 5,
// L is 0
else
{
// else start from R and check manually
L = i;
while (R<n && str[R-L] == str[R])
R++;
Z[i] = R-L;
R--;
}
}
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
cin>>t;
for(int i=0;i<t;i++){
string s;
cin>>s;
int len=s.length();
int Z[len];
getZarr(s, Z,len);
Z[0]=len;
//cout<<len<<endl;
//cout<<endl;
long long res=0;
for(int j=0;j<len;j++){
res=res+Z[j];
}
cout<<res<<endl;
}
return 0;
}
| true |
a45aa523e4df121e1c331e295b5ef7c50eb0be3a | C++ | stefan-ewald/e_fork_UdemyCpp | /4_STLVector/Auto.cc | UTF-8 | 552 | 3.6875 | 4 | [
"MIT"
] | permissive | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main()
{
std::vector<int> my_vector(10, 0);
std::iota(my_vector.begin(), my_vector.end(), 0);
// std::vector<int>::iterator it = my_vector.begin();
// auto it2 = my_vector.begin();
// [begin, end)
for (auto it3 = my_vector.begin(); it3 != my_vector.end(); ++it3)
{
std::cout << *it3 << std::endl;
}
// For-each based loop
for (auto &val : my_vector)
{
std::cout << val << std::endl;
}
return 0;
}
| true |
6b40d6f3da7ef741b89de45aadc50ae34341401b | C++ | jowr/inja | /test/src/unit-parser.cpp | UTF-8 | 8,197 | 3.171875 | 3 | [
"MIT"
] | permissive | #include "catch.hpp"
#include "nlohmann/json.hpp"
#include "inja.hpp"
using json = nlohmann::json;
using Type = inja::Parser::Type;
TEST_CASE("Parse structure") {
inja::Parser parser = inja::Parser();
SECTION("Basic string") {
std::string test = "lorem ipsum";
json result = {{{"type", Type::String}, {"text", "lorem ipsum"}}};
CHECK( parser.parse(test) == result );
}
SECTION("Empty string") {
std::string test = "";
json result = {};
CHECK( parser.parse(test) == result );
}
SECTION("Variable") {
std::string test = "{{ name }}";
json result = {{{"type", Type::Variable}, {"command", "name"}}};
CHECK( parser.parse(test) == result );
}
SECTION("Combined string and variables") {
std::string test = "Hello {{ name }}!";
json result = {
{{"type", Type::String}, {"text", "Hello "}},
{{"type", Type::Variable}, {"command", "name"}},
{{"type", Type::String}, {"text", "!"}}
};
CHECK( parser.parse(test) == result );
}
SECTION("Multiple variables") {
std::string test = "Hello {{ name }}! I come from {{ city }}.";
json result = {
{{"type", Type::String}, {"text", "Hello "}},
{{"type", Type::Variable}, {"command", "name"}},
{{"type", Type::String}, {"text", "! I come from "}},
{{"type", Type::Variable}, {"command", "city"}},
{{"type", Type::String}, {"text", "."}}
};
CHECK( parser.parse(test) == result );
}
SECTION("Loops") {
std::string test = "open {% for e in list %}lorem{% endfor %} closing";
json result = {
{{"type", Type::String}, {"text", "open "}},
{{"type", Type::Loop}, {"command", "for e in list"}, {"children", {
{{"type", Type::String}, {"text", "lorem"}}
}}},
{{"type", Type::String}, {"text", " closing"}}
};
CHECK( parser.parse(test) == result );
}
SECTION("Nested loops") {
std::string test = "{% for e in list %}{% for b in list2 %}lorem{% endfor %}{% endfor %}";
json result = {
{{"type", Type::Loop}, {"command", "for e in list"}, {"children", {
{{"type", Type::Loop}, {"command", "for b in list2"}, {"children", {
{{"type", Type::String}, {"text", "lorem"}}
}}}
}}}
};
CHECK( parser.parse(test) == result );
}
SECTION("Basic conditional") {
std::string test = "{% if true %}Hello{% endif %}";
json result = {
{{"type", Type::Condition}, {"children", {
{{"type", Type::ConditionBranch}, {"command", "if true"}, {"children", {
{{"type", Type::String}, {"text", "Hello"}}
}}}
}}}
};
CHECK( parser.parse(test) == result );
}
SECTION("If/else if/else conditional") {
std::string test = "if: {% if maybe %}first if{% else if perhaps %}first else if{% else if sometimes %}second else if{% else %}test else{% endif %}";
json result = {
{{"type", Type::String}, {"text", "if: "}},
{{"type", Type::Condition}, {"children", {
{{"type", Type::ConditionBranch}, {"command", "if maybe"}, {"children", {
{{"type", Type::String}, {"text", "first if"}}
}}},
{{"type", Type::ConditionBranch}, {"command", "else if perhaps"}, {"children", {
{{"type", Type::String}, {"text", "first else if"}}
}}},
{{"type", Type::ConditionBranch}, {"command", "else if sometimes"}, {"children", {
{{"type", Type::String}, {"text", "second else if"}}
}}},
{{"type", Type::ConditionBranch}, {"command", "else"}, {"children", {
{{"type", Type::String}, {"text", "test else"}}
}}},
}}}
};
CHECK( parser.parse(test) == result );
}
SECTION("Comments") {
std::string test = "{# lorem ipsum #}";
json result = {{{"type", Type::Comment}, {"text", "lorem ipsum"}}};
CHECK( parser.parse(test) == result );
}
SECTION("Line Statements") {
std::string test = R"(## if true
lorem ipsum
## endif)";
json result = {
{{"type", Type::Condition}, {"children", {
{{"type", Type::ConditionBranch}, {"command", "if true"}, {"children", {
{{"type", Type::String}, {"text", "lorem ipsum"}}
}}}
}}}
};
CHECK( parser.parse(test) == result );
}
}
TEST_CASE("Parse variables") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "Washington D.C.";
data["age"] = 29;
data["names"] = {"Jeff", "Seb"};
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["brother"]["daughter0"] = { { "name", "Maria" } };
SECTION("Variables from values") {
CHECK( env.eval_variable("42", data) == 42 );
CHECK( env.eval_variable("3.1415", data) == 3.1415 );
CHECK( env.eval_variable("\"hello\"", data) == "hello" );
CHECK( env.eval_variable("true", data) == true );
CHECK( env.eval_variable("[5, 6, 8]", data) == std::vector<int>({5, 6, 8}) );
}
SECTION("Variables from JSON data") {
CHECK( env.eval_variable("name", data) == "Peter" );
CHECK( env.eval_variable("age", data) == 29 );
CHECK( env.eval_variable("names/1", data) == "Seb" );
CHECK( env.eval_variable("brother/name", data) == "Chris" );
CHECK( env.eval_variable("brother/daughters/0", data) == "Maria" );
CHECK( env.eval_variable("/age", data) == 29 );
CHECK_THROWS_WITH( env.eval_variable("noelement", data), "JSON pointer found no element." );
CHECK_THROWS_WITH( env.eval_variable("&4s-", data), "JSON pointer found no element." );
}
}
TEST_CASE("Parse conditions") {
inja::Environment env = inja::Environment();
json data;
data["age"] = 29;
data["brother"] = "Peter";
data["father"] = "Peter";
data["guests"] = {"Jeff", "Seb"};
SECTION("Elements") {
CHECK( env.eval_condition("age", data) );
CHECK( env.eval_condition("guests", data) );
CHECK_FALSE( env.eval_condition("size", data) );
CHECK_FALSE( env.eval_condition("false", data) );
}
SECTION("Operators") {
CHECK( env.eval_condition("not size", data) );
CHECK_FALSE( env.eval_condition("not true", data) );
CHECK( env.eval_condition("true and true", data) );
CHECK( env.eval_condition("true or false", data) );
CHECK_FALSE( env.eval_condition("true and not true", data) );
}
SECTION("Numbers") {
CHECK( env.eval_condition("age == 29", data) );
CHECK( env.eval_condition("age >= 29", data) );
CHECK( env.eval_condition("age <= 29", data) );
CHECK( env.eval_condition("age < 100", data) );
CHECK_FALSE( env.eval_condition("age > 29", data) );
CHECK_FALSE( env.eval_condition("age != 29", data) );
CHECK_FALSE( env.eval_condition("age < 28", data) );
CHECK_FALSE( env.eval_condition("age < -100.0", data) );
}
SECTION("Strings") {
CHECK( env.eval_condition("brother == father", data) );
CHECK( env.eval_condition("brother == \"Peter\"", data) );
CHECK_FALSE( env.eval_condition("not brother == father", data) );
}
SECTION("Lists") {
CHECK( env.eval_condition("\"Jeff\" in guests", data) );
CHECK_FALSE( env.eval_condition("brother in guests", data) );
}
}
TEST_CASE("Parse functions") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "New York";
data["names"] = {"Jeff", "Seb", "Peter", "Tom"};
data["temperature"] = 25.6789;
SECTION("Upper") {
CHECK( env.eval_variable("upper(name)", data) == "PETER" );
CHECK( env.eval_variable("upper(city)", data) == "NEW YORK" );
CHECK_THROWS_WITH( env.eval_variable("upper(5)", data), "Argument in upper function is not a string." );
}
SECTION("Lower") {
CHECK( env.eval_variable("lower(name)", data) == "peter" );
CHECK( env.eval_variable("lower(city)", data) == "new york" );
CHECK_THROWS_WITH( env.eval_variable("lower(5)", data), "Argument in lower function is not a string." );
}
SECTION("Range") {
CHECK( env.eval_variable("range(4)", data) == std::vector<int>({0, 1, 2, 3}) );
CHECK_THROWS_WITH( env.eval_variable("range(true)", data), "Argument in range function is not a number." );
}
SECTION("Length") {
CHECK( env.eval_variable("length(names)", data) == 4 );
CHECK_THROWS_WITH( env.eval_variable("length(5)", data), "Argument in length function is not a list." );
}
SECTION("Round") {
CHECK( env.eval_variable("round(4, 0)", data) == 4 );
CHECK( env.eval_variable("round(temperature, 2)", data) == 25.68 );
CHECK_THROWS_WITH( env.eval_variable("round(name, 2)", data), "Argument in round function is not a number." );
}
}
| true |
ff1cadaff2f4e87d88da9996d972ecdbb6f0d69f | C++ | ab9x3jhx6a/ACI_F14 | /MovementSound_01/Sound_Movement/src/Particle.cpp | UTF-8 | 865 | 2.84375 | 3 | [] | no_license | #include "Particle.h"
Particle::Particle(){
//Particle(ofVec2f(0,0), ofVec2f(0,0), ofColor::white);
}
Particle::Particle(ofVec2f pos, ofVec2f vel, int r, int g, int b){
position = pos;
velocity = vel;
red = r;
green = g;
blue = b;
destroy = false;
}
void Particle::draw(){
ofSetColor(red,green,blue);
int ran = ofRandom(10,20);
if (ran > 15) ran = 1;
else ran = -1;
int vibrate = ofRandom(0,10);
ofCircle(position+ran*vibrate, 5.0);
}
void Particle::update(){
velocity.limit(40.0);
position += velocity;
if(position.y < -1000||position.y > ofGetHeight()+1000) {
destroy = true;
}
if(position.x < -1000||position.x> ofGetWidth()+1000){
destroy = true;
}
}
void Particle::applyForces(){
ofVec2f gravity = ofVec2f(0.0,9.8);
velocity += gravity;
}
bool Particle::death(){
if (destroy==true)
return true;
else return false;
}
| true |
ce73038c6d40bcd8d5386b363d172b3cd11032e5 | C++ | yumdeer/daily_practice | /vs_project/Template_/模板类的声明与实现分离/foo.tpp | UTF-8 | 208 | 2.546875 | 3 | [] | no_license | #include "foo.h"
template <typename T>
Foo<T>::Foo(T num) : nums(num)
{
}
template <typename T>
void Foo<T>::doSomething(T param)
{
//implementation
cout << nums << endl;
cout << "hello " <<endl;
} | true |
af0252bc8cfe10959569e784fa1902bcd233dac5 | C++ | Yuanfeng-Wang/CSM_Cantera | /include/cantera/numerics/polyfit.h | UTF-8 | 3,947 | 2.75 | 3 | [] | no_license | /**
* @file polyfit.h C interface for Fortran DPOLFT subroutine
*/
/*
* Copyright 2001-2003 California Institute of Technology
* See file License.txt for licensing information
*/
#ifndef CT_POLYFIT_H
#define CT_POLYFIT_H
#include <vector>
#include "cantera/base/ct_defs.h"
namespace Cantera
{
//! Fits a polynomial function to a set of data points
/*!
* Given a collection of points X(I) and a set of values Y(I) which
* correspond to some function or measurement at each of the X(I),
* subroutine DPOLFT computes the weighted least-squares polynomial
* fits of all degrees up to some degree either specified by the user
* or determined by the routine. The fits thus obtained are in
* orthogonal polynomial form. Subroutine DP1VLU may then be
* called to evaluate the fitted polynomials and any of their
* derivatives at any point. The subroutine DPCOEF may be used to
* express the polynomial fits as powers of (X-C) for any specified
* point C.
*
* @param n The number of data points.
*
* @param x A set of grid points on which the data is specified.
* The array of values of the independent variable. These
* values may appear in any order and need not all be
* distinct. There are n of them.
*
* @param y array of corresponding function values. There are n of them
*
* @param w array of positive values to be used as weights. If
* W[0] is negative, DPOLFT will set all the weights
* to 1.0, which means unweighted least squares error
* will be minimized. To minimize relative error, the
* user should set the weights to: W(I) = 1.0/Y(I)**2,
* I = 1,...,N .
*
* @param maxdeg maximum degree to be allowed for polynomial fit.
* MAXDEG may be any non-negative integer less than N.
* Note -- MAXDEG cannot be equal to N-1 when a
* statistical test is to be used for degree selection,
* i.e., when input value of EPS is negative.
*
* @param ndeg output degree of the fit computed.
*
* @param eps Specifies the criterion to be used in determining
* the degree of fit to be computed.
* (1) If EPS is input negative, DPOLFT chooses the
* degree based on a statistical F test of
* significance. One of three possible
* significance levels will be used: .01, .05 or
* .10. If EPS=-1.0 , the routine will
* automatically select one of these levels based
* on the number of data points and the maximum
* degree to be considered. If EPS is input as
* -.01, -.05, or -.10, a significance level of
* .01, .05, or .10, respectively, will be used.
* (2) If EPS is set to 0., DPOLFT computes the
* polynomials of degrees 0 through MAXDEG .
* (3) If EPS is input positive, EPS is the RMS
* error tolerance which must be satisfied by the
* fitted polynomial. DPOLFT will increase the
* degree of fit until this criterion is met or
* until the maximum degree is reached.
*
* @param r Output vector containing the first ndeg+1 Taylor coefficients
*
* P(X) = r[0] + r[1]*(X-C) + ... + r[ndeg] * (X-C)**ndeg
* ( here C = 0.0)
*
* @return Returned value is the value of the rms of the interpolated
* function at x.
*/
doublereal polyfit(int n, doublereal* x, doublereal* y, doublereal* w,
int maxdeg, int& ndeg, doublereal eps, doublereal* r);
}
#endif
| true |
8982959f1e7cbdae3d8a0368deabcaaa1eac413d | C++ | Tali98/Lab9 | /Castillo.h | UTF-8 | 348 | 2.515625 | 3 | [] | no_license | #ifndef CASTILLO_H
#define CASTILLO_H
#include "Edificios.h"
#include<string>
using namespace std;
class Castillo:public Edificios{
private:
int madera;
int oro;
int piedra;
public:
Castillo(int,int,int);
virtual double getCosto_Oro();
virtual double getCosto_Piedra();
virtual double getCosto_Madera();
virtual void toString();
};
#endif | true |
5a53f69ba11805068b3bae544ba775cc33892c0f | C++ | terraKote/Engine | /src/LuaBindings/LuaSandbox.cpp | UTF-8 | 4,666 | 2.609375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #include "LuaSandbox.h"
sol::state LuaSandbox::_lua;
sol::function LuaSandbox::_fun_init;
sol::function LuaSandbox::_fun_postinit;
sol::function LuaSandbox::_fun_update;
sol::function LuaSandbox::_fun_render;
LuaSandbox::LuaSandbox(){}
void LuaSandbox::Init(){
_lua.open_libraries(sol::lib::base,
sol::lib::package,
sol::lib::math,
sol::lib::table);
LuaProxyObject::bind(_lua);
LuaWindow::bind(_lua);
LuaTimer::bind(_lua);
LuaSprite::bind(_lua);
LuaMouse::bind(_lua);
LuaVec2::bind(_lua);
LuaAudio::bind(_lua);
LuaKeyboard::bind(_lua);
LuaCamera::bind(_lua);
LuaDrawer::bind(_lua);
//FIXME package.path
_lua.script(R"(
package.path = "./../Data/?.lua"
count = 0
objects = 0
Globals = {}
ScriptsArray = {}
ObjectsArray = {}
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '`'..k..'`' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
function push_script()
count = count + 1
table.insert(ScriptsArray, count, Script)
end
function push_object(id)
objects = objects + 1
ObjectsArray[objects] = Object
end
function remove_object(id)
ObjectsArray[id] = nil
end
function create_env()
return {
print = print,
math = math,
table = table,
pcall = pcall,
require = require,
dump = dump,
Globals = globals,
Sprite = Sprite,
Flip = Flip,
Animation = Animation,
Vec2 = Vec2,
Audio = Audio,
Mouse = Mouse,
MouseWheel = MouseWheel,
MouseButton = MouseButton,
Keyboard = Keyboard,
Key = Key,
Timer = Timer,
Time = Time,
Camera = Camera,
Window = Window,
Color = Color,
Drawer = Drawer
}
end
function run(untrusted_code, run_object)
-- run code under environment [Lua 5.2]
-- make environment
-- add functions you know are safe here
local env = create_env()
if run_object then
Object.env = env
Object.find = LuaProxyObject.find
Object.new = function(table)
return LuaProxyObject.new(table, remove_object)
end
env.Object = Object
else
Script.env = env
env.Script = Script
end
local untrusted_function = load(untrusted_code, nil, 't', env), message
if not untrusted_function then
return nil, message
end
return pcall(untrusted_function)
end
function post_objects_init()
print("post_objects_init")
do
local env = create_env()
for i = 1, #ObjectsArray do
local object = ObjectsArray[i]
object.PostInit(object, object.DataStorage)
end
end -- do
end -- function
function init()
for i = 1, #ScriptsArray do
pcall(ScriptsArray[i].Init, ScriptsArray[i].env)
end
end
function update()
for i = 1, #ScriptsArray do
pcall(ScriptsArray[i].Update, ScriptsArray[i].env)
end
end
function render()
for i = 1, #ScriptsArray do
pcall(ScriptsArray[i].Render, ScriptsArray[i].env)
end
end
)");
_fun_init = _lua["init"];
_fun_postinit = _lua["post_objects_init"];
_fun_update = _lua["update"];
_fun_render = _lua["render"];
}
void LuaSandbox::AddScript(const std::string& origin, const std::string& script_lines){
try{
sol::table table = _lua.create_named_table("Script");
_lua["run"](script_lines, false);
_lua["push_script"]();
}
catch(const sol::error& ex){
std::cerr << "Error at file: \"" << origin << "\"" << std::endl;
std::cerr << ex.what() << std::endl;
}
}
void LuaSandbox::AddObject(const std::string& origin, const std::string& script_lines, Object* owner){
try{
sol::table table = _lua.create_named_table("Object");
_lua["run"](script_lines, true);
sol::function remfunc = _lua["remove_object"];
LuaProxyObject* proxy = new LuaProxyObject(table, remfunc);
owner->Connect(proxy);
_lua["push_object"](proxy->GetId());
}
catch(const sol::error& ex){
std::cerr << "Error at file: \"" << origin << "\"" << std::endl;
std::cerr << ex.what() << std::endl;
}
}
void LuaSandbox::EngineInit(){
_fun_init();
_fun_postinit();
}
void LuaSandbox::EngineUpdate(){
_fun_update();
}
void LuaSandbox::EngineRender(){
_fun_render();
}
void LuaSandbox::EngineCleanUp(){
}
| true |
4192b32983c79dac354e3af03683ed1a74784614 | C++ | DennisCarcamo/DennisCarcamo_Lab8 | /pintura.cpp | UTF-8 | 414 | 2.65625 | 3 | [] | no_license | #include "obras.h"
#include "pintura.h"
#include <string>
#include <sstream>
using std::stringstream;
Pintura::Pintura(string name, string autor, string fechaIngreso, string materialLienzo, string tecnica):Obras (name,autor,fechaIngreso), materialLienzo(materialLienzo), tecnica(tecnica){
}
string Pintura::toString()const{
stringstream ss;
ss<<"Pintura "<<materialLienzo<<" , "<<tecnica;
return ss.str();
}
| true |
939a022b5c9484d965db372aa9697cb4b4ffb1fb | C++ | AlirezaMojtabavi/misInteractiveSegmentation | /Header/misExtractExternalSurface.h | UTF-8 | 1,009 | 2.515625 | 3 | [] | no_license | #pragma once
#include "logmanager.h"
#include "IImage.h"
#include "vtkSmartPointer.h"
// The misExtractExternalSurface is used for extracting outermost surface layer of a polydata. It bounds the surface within
// a sphere that it builds and connects each point on the sphere to surface [bounding box] center and extracts intersection
// points (between the lines and the spherical surface) as a new surface.
class misExtractExternalSurface
{
public:
static vtkSmartPointer<vtkPolyData> ExtractOuterSurface(vtkImageData* image, double threshold);
private:
static vtkSmartPointer<vtkPolyData> ExtractOuterSurface(vtkPolyData* poly);
static vtkSmartPointer<vtkPolyData> ComputeExternalSurfaceOfContour(vtkPolyData* poly);
// Gets a length proportionate to the longest bounding box edge an estimate for the radius of the bounding sphere.
static double GetEstimatedRadius( double * bounds );
static vtkSmartPointer<vtkPolyData> ComputeCountourFromImage(vtkImageData* image, double threshold);
};
| true |
18f1a7c58b69620148d04af72cd031d4520a85b5 | C++ | qori-aziz/irostech_RnD | /Percobaan_IOT/STM32/STM32F103/UDP_ENC28j60_STM32_test_RX_parisng_part2/UDP_ENC28j60_STM32_test_RX_parisng_part2.ino | UTF-8 | 3,119 | 2.765625 | 3 | [] | no_license | #include <SPI.h>
#include <UIPEthernet.h>
#include <itoa.h>
int recvdSize;
String dataIn;
String dt[10];
int i;
boolean parsing = false;
// -------- Do not change the section below -----------------
byte mac[] = {0x2A, 0x00, 0x22, 0x22, 0x22, 0x24};
IPAddress ip(192, 168, 1, 201);
unsigned int localPort = 8888; // Process ID port (TCP/UDP Alternate port = 8888)
char remote_IP1[] = "192.168.1.202";
int remote_Port1 = 8888;
char UDP_TX_Buffer[80];
char recvdBuffer[900]; // Buffer for incoming data
EthernetUDP Udp; //Class variable (Initiates process of UDP)
// ------------------------------------------------------------
void setup() {
// put your setup code here, to run once:
// put your setup code here, to run once:
Serial1.begin(9600);
dataIn = "";
Serial1.println("Client Start!");
Ethernet.begin(mac, ip); // Set up the Ethernet Shield
Udp.begin(localPort);
Serial1.print("Start TC PC IP: ");
Serial1.println(Ethernet.localIP());
}
void loop() {
// put your main code here, to run repeatedly:
recvdSize = Udp.parsePacket();
if (recvdSize) {
IPAddress remote = Udp.remoteIP();
Udp.read(recvdBuffer, 900); // 900 are bufers for received storage
recvdBuffer[recvdSize] = '\0';
recvdSize -= 8; // Gets rid of the message header
Serial1.println((String)recvdBuffer);
/*
dataIn += recvdBuffer;
parsing = true;
if (parsing)
{
parsingData();
Serial1.print("data 1 : ");
Serial1.print(dt[0]);
Serial1.print("\n");
Serial1.print("data 2 : ");
Serial1.print(dt[1].toInt());
Serial1.print("\n");
Serial1.print("data 3 : ");
Serial1.print(dt[2].toInt());
Serial1.print("\n");
Serial1.print("data 4 : ");
Serial1.print(dt[3].toInt());
Serial1.print("\n");
parsing = false;
dataIn = "";
}*/
}
}
void parsingData()
{
int j = 0;
//kirim data yang telah diterima sebelumnya
Serial1.print("data masuk : ");
Serial1.print(dataIn);
Serial1.print("\n");
//inisialisasi variabel, (reset isi variabel)
dt[j] = "";
//proses parsing data
for (i = 1; i < dataIn.length(); i++)
{
//pengecekan tiap karakter dengan karakter (#) dan (,)
if ((dataIn[i] == '#') || (dataIn[i] == ','))
{
//increment variabel j, digunakan untuk merubah index array penampung
j++;
dt[j] = ""; //inisialisasi variabel array dt[j]
}
else
{
//proses tampung data saat pengecekan karakter selesai.
dt[j] = dt[j] + dataIn[i];
}
}
//kirim data hasil parsing
// Serial1.print("data 1 : ");
// Serial1.print(dt[0]);
// Serial1.print("\n");
// Serial1.print("data 2 : ");
// Serial1.print(dt[1].toInt());
// Serial1.print("\n");
// Serial1.print("data 3 : ");
// Serial1.print(dt[2].toInt());
// Serial1.print("\n");
// Serial1.print("data 4 : ");
// Serial1.print(dt[3].toInt());
// Serial1.print("\n");
// Serial1.print("data 5 : ");
// Serial1.print(dt[4].toInt());
// Serial1.print("\n\n");
}
| true |
b4965343dd80d35cac17a1a288ad264b6f769a39 | C++ | Thomas-Zorroche/Space-Explorer | /src/engine/Camera.cpp | UTF-8 | 2,011 | 2.984375 | 3 | [] | no_license | #include "engine/Camera.hpp"
#include "common.hpp"
Camera::Camera(float x, float z)
: _Position(x, 0, z), _phi(M_PI), _theta(0), _CanTurn(true),
_lastX(450.0f), _lastY(320.0f), _sensitivity(8.0f)
{
computeDirectionVectors();
}
void Camera::Move(float deltaTime, DIRCAM direction)
{
glm::vec3 dir;
switch (direction)
{
case DIRCAM::FRONT:
dir = _FrontVector;
break;
case DIRCAM::BACK:
dir = -_FrontVector;
break;
case DIRCAM::LEFT:
dir = _LeftVector;
break;
default:
dir = _FrontVector;
break;
}
float dst = deltaTime;
MoveX(dst, dir);
MoveZ(dst, dir);
_Position.y += dst * dir.y;
if (_rotateAroundPlanet)
{
glm::mat4 modelMatrix = glm::translate(glm::mat4(1.0f), _rotationPoint);
modelMatrix = glm::rotate(modelMatrix, glm::radians(0.05f), glm::vec3(0.0, 1.0, 0.0));
modelMatrix = glm::translate(modelMatrix, -_rotationPoint);
_Position = modelMatrix * glm::vec4(_Position, 1.0);
}
computeDirectionVectors();
}
void Camera::rotateUp(float angle)
{
_theta -= glm::radians(angle);
computeDirectionVectors();
}
void Camera::rotateLeft(float angle)
{
_phi -= glm::radians(angle);
computeDirectionVectors();
}
void Camera::RotateAroundPlanet(bool rotate, const glm::vec3& planetPosition)
{
if (rotate)
{
_rotateAroundPlanet = true;
_rotationPoint = planetPosition;
}
else
{
_rotateAroundPlanet = false;
}
}
/*
* Private Functions
*/
void Camera::computeDirectionVectors()
{
// Direction
_FrontVector = glm::vec3(glm::cos(glm::radians(_theta)) * glm::sin(glm::radians(_phi)),
glm::sin(glm::radians(_theta)),
glm::cos(glm::radians(_theta)) * glm::cos(glm::radians(_phi)));
// Left
_LeftVector = glm::vec3((glm::sin(glm::radians(_phi) + (M_PI / 2))),
0,
glm::cos(glm::radians(_phi) + (M_PI / 2)));
// Up
_UpVector = glm::cross(_FrontVector, _LeftVector);
}
void Camera::MoveX(float dst, const glm::vec3& dir)
{
_Position.x += dst * dir.x;
}
void Camera::MoveZ(float dst, const glm::vec3& dir)
{
_Position.z += dst * dir.z;
}
| true |
42f3e0ba5daa380b1793eba02d97aac1c344c0c0 | C++ | dualword/LagEngine | /LagEngine/src/collisions/BoundingSphere.cpp | UTF-8 | 1,331 | 2.984375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "BoundingSphere.h"
using namespace Lag;
BoundingSphere::BoundingSphere() : IBoundingVolume(BoundingVolumeType::SPHERE) {
empty();
}
BoundingSphere::BoundingSphere(const BoundingSphere &other) :
IBoundingVolume(BoundingVolumeType::SPHERE),
center(other.center),
radius(other.radius) {
}
BoundingSphere::BoundingSphere(const std::vector<glm::vec3> &points) :
BoundingSphere() {
empty();
for(auto &point : points)
enclose(point);
}
BoundingSphere::BoundingSphere(const BoundingSphere &other, const glm::mat4 &transform) :
BoundingSphere(other) {
this->transform(transform);
}
std::unique_ptr<IBoundingVolume> BoundingSphere::clone() const {
return std::make_unique<BoundingSphere>(*this);
}
void BoundingSphere::empty() {
center[0] = center[1] = center[2] = radius = 0.0f;
}
void BoundingSphere::enclose(const glm::vec3 &point) {
float distance = glm::distance(point, center);
if(distance > radius) {
radius = distance;
}
}
void BoundingSphere::transform(const glm::mat4 &transform) {
glm::vec4 newCenter = transform * glm::vec4(center, 1.0f);
glm::vec4 newOtherPoint = transform * glm::vec4(center + glm::vec3(radius, 0.0, 0.0), 1.0f);
center = glm::vec3(newCenter);
radius = glm::distance(center, glm::vec3(newOtherPoint));
}
| true |
bebeccb7d41c788292ecbe265a19b4c2c14bd7e0 | C++ | pablojor/Anyaroth | /Anyaroth/Anyaroth/Canvas.h | UTF-8 | 364 | 2.71875 | 3 | [] | no_license | #pragma once
#include "UIElement.h"
#include <vector>
class Canvas
{
private:
std::vector<UIElement*> _elements;
public:
Canvas() {}
virtual ~Canvas();
virtual void render() const;
virtual void update(double deltaTime);
virtual bool handleEvent(const SDL_Event& event);
inline virtual void addUIElement(UIElement* elem) { _elements.push_back(elem); }
}; | true |
28c5bd12f50991499f1cd6ba731b01b4d84b4242 | C++ | HaikuArchives/EnglishEditorII | /sources/Hotspot.cpp | UTF-8 | 1,083 | 2.546875 | 3 | [
"MIT"
] | permissive | /* Hotspot.cpp */
#include "Hotspot.h"
#include "StyleParser.h"
#include "View.h"
const rgb_color Hotspot::hotspotColor = StyleParser::ParseColor("rgba(255, 130, 0, 128)");
Hotspot::~Hotspot()
{
}
void Hotspot::FadeDocument(View* view, BPoint origin)
{
// I've decided I don't like this
return;
static const rgb_color fadeColor = { 255, 255, 255, 128 };
//*** static const rgb_color fadeColor = { 255, 255, 255, 96 };
// nicer, but only works at 32-bit
view->PushState();
// set up
BRect bounds = Bounds();
bounds.OffsetBy(origin);
BRect viewBounds = view->Bounds();
view->SetDrawingMode(B_OP_ALPHA);
view->SetHighColor(fadeColor);
// draw the four rectangles
BRect rect = viewBounds;
rect.bottom = bounds.top;
view->FillRect(rect);
rect.top = bounds.top;
rect.bottom = bounds.bottom;
rect.right = bounds.left;
view->FillRect(rect);
rect.left = bounds.right;
rect.right = viewBounds.right;
view->FillRect(rect);
rect.top = bounds.bottom;
rect.bottom = viewBounds.bottom;
rect.left = viewBounds.left;
view->FillRect(rect);
view->PopState();
}
| true |
65a23a233a4a4320fbe37543fa505c18763a2e22 | C++ | kakomarina/spider3d | /t3.cpp | UTF-8 | 13,189 | 2.578125 | 3 | [] | no_license |
#include <cmath>
#include <math.h>
#include <iostream>
#include <GL/glut.h>
#include <opencv2/opencv.hpp>
#include <vector>
#include <string>
#define SKYBOX_SIZE 30.0 //tamanho da largura e comprimento do hexaedro utilizado para o skybox
#define SKYBOX_HEIGHT 30.0 //tamanho da altura do hexaedro utilizado para o skybox
typedef struct{
GLfloat x,y,z; //coordenadas x, y e z
} point;
int width = 900;
int height = 500;
GLfloat raio1 = 1.8;
GLfloat raio2 = 1.3;
GLint xA = 0, yA = 0, zA = 1;
GLint xB = raio1+raio2, yB = 0, zB = 1;
GLfloat alfa = 0;
float tempo_ant;
float movimento = 0;
int andando = 0;
GLfloat rotpers = 1.0;
void drawSky(){
cv::Mat img;
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(65.0, 1.0, 0.01, 1000.0);
glMatrixMode(GL_MODELVIEW);
glLineWidth(2);
//iniciliazando parametros da textura
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, img.cols, img.rows, 1, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT);
//carregando as 6 imagens do skybox
img = cv::imread("ceu.jpg");
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,0,GL_RGBA, img.cols, img.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());//deteminacao da imagem a utilizar na textura z negativa do cube map
img = cv::imread("ceu.jpg");
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z,0,GL_RGBA, img.cols, img.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());//deteminacao da imagem a utilizar na textura z positiva do cube map
img = cv::imread("ceu.jpg");
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,GL_RGBA, img.cols, img.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());//deteminacao da imagem a utilizar na textura x positiva do cube map
img = cv::imread("ceu.jpg");
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X,0,GL_RGBA, img.cols, img.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());//deteminacao da imagem a utilizar na textura x negativa do cube map
img = cv::imread("ceu.jpg");
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y,0,GL_RGBA, img.cols, img.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());//deteminacao da imagem a utilizar na textura y positiva do cube map
img = cv::imread("ceu.jpg");
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,0,GL_RGBA, img.cols, img.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());//deteminacao da imagem a utilizar na textura y negativa do cube map
//definindo os parametros para o cube map
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_REPEAT);
std::vector<point> POINTS;
point aux;
// frente e tras
for(int i=0; i<2; i++){
aux.x = -SKYBOX_SIZE;
aux.y = SKYBOX_HEIGHT;
aux.z = pow(-1, i)*SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = SKYBOX_SIZE;
aux.y = SKYBOX_HEIGHT;
aux.z = pow(-1, i)*SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = SKYBOX_SIZE;
aux.y = -SKYBOX_HEIGHT;
aux.z = pow(-1, i)*SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = -SKYBOX_SIZE;
aux.y = -SKYBOX_HEIGHT;
aux.z = pow(-1, i)*SKYBOX_SIZE;
POINTS.push_back(aux);
}
// direita e embaixo
for(int i=0; i<2; i++){
aux.x = pow(-1, i)*SKYBOX_SIZE;
aux.y = pow(-1, i)*SKYBOX_HEIGHT;
aux.z = SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = SKYBOX_SIZE;
aux.y = -SKYBOX_HEIGHT;
aux.z = SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = SKYBOX_SIZE;
aux.y = -SKYBOX_HEIGHT;
aux.z = -SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = pow(-1, i)*SKYBOX_SIZE;
aux.y = pow(-1, i)*SKYBOX_HEIGHT;
aux.z = -SKYBOX_SIZE;
POINTS.push_back(aux);
}
//esquerda e em cima
for(int i=0; i<2; i++){
aux.x = -SKYBOX_SIZE;
aux.y = pow(-1, i)*SKYBOX_HEIGHT;
aux.z = SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = pow(-1, i)*SKYBOX_SIZE;
aux.y = SKYBOX_HEIGHT;
aux.z = SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = pow(-1, i)*SKYBOX_SIZE;
aux.y = SKYBOX_HEIGHT;
aux.z = -SKYBOX_SIZE;
POINTS.push_back(aux);
aux.x = -SKYBOX_SIZE;
aux.y = pow(-1, i)*SKYBOX_HEIGHT;
aux.z = -SKYBOX_SIZE;
POINTS.push_back(aux);
}
glEnable(GL_TEXTURE_CUBE_MAP);
//Desenha o cube map com textura
glBegin(GL_QUADS);
for(int i = 0; i < POINTS.size(); i++){
glTexCoord3f(POINTS[i].x/SKYBOX_SIZE, POINTS[i].y/SKYBOX_HEIGHT, POINTS[i].z/SKYBOX_SIZE);
glVertex3f(POINTS[i].x, POINTS[i].y,POINTS[i].z);
}
glEnd();
glDisable(GL_TEXTURE_CUBE_MAP);
}
void drawChao(){
cv::Mat img2 = cv::imread("parede.jpg");
glColor3f(1, 1, 1);
//Definindo os parametros da textura 2D para o chao
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img2.cols, img2.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img2.ptr());
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
glEnable(GL_TEXTURE_2D);
//Desenha o chao com textura nas coordenadas passadas
glBegin(GL_QUADS);
glTexCoord2f(0,1); glVertex3f(-10,0,10);
glTexCoord2f(0,0); glVertex3f(-10,0,-10);
glTexCoord2f(1,0); glVertex3f(10,0,-10);
glTexCoord2f(1,1); glVertex3f(10,0,10);
glEnd();
glDisable(GL_TEXTURE_2D);
}
void drawPerninhas(GLfloat width, GLfloat x1, GLfloat y1, GLfloat z1, GLfloat x2, GLfloat y2, GLfloat z2){
glLineWidth(width);
glBegin(GL_LINE_STRIP);
glVertex3f(0, 0, 0.0);
glVertex3f(x1, y1, z1);
glVertex3f(x2, y2, z2);
glEnd();
}
void drawAranha(GLfloat raio1, GLfloat raio2, GLint n){
cv::Mat img = cv::imread("a.jpg");
cv::Mat img2 = cv::imread("pelo.jpg");
//Definindo os parametros da textura 3d
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, img.cols, img.rows, 1, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr());
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT);
//glTranslatef(xB, yB, 0);
glRotatef(alfa, 0, 0, 1.0); //roda tudo
//glTranslatef(0, 0, 0);
glPushMatrix();
glTranslatef(xA, yA, zA); //translada só a bunda
/*Comeca a textura da bunda*/
glEnable(GL_TEXTURE_3D);
GLUquadric *quadObj = gluNewQuadric();
gluQuadricTexture(quadObj, GL_TRUE);
gluSphere(quadObj, raio1, n, n); //desenha bunda
gluDeleteQuadric(quadObj);
glDisable(GL_TEXTURE_3D);
/*Fim da textura da bunda*/
glPopMatrix();
glPushMatrix();
glTranslatef(xB, yB, zB); //translada só a cabeça
/*Comeca a textura da cabeca*/
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, img2.cols, img2.rows, 1, 0, GL_BGR, GL_UNSIGNED_BYTE, img2.ptr());
glEnable(GL_TEXTURE_3D);
quadObj = gluNewQuadric();
gluQuadricTexture(quadObj, GL_TRUE);
gluSphere(quadObj, raio2, n, n); //desenha cabeca
gluDeleteQuadric(quadObj);
glDisable(GL_TEXTURE_3D);
/*Fim da textura da cabeca*/
glPushMatrix();
glTranslatef(raio2*cos(M_PI/6), raio2*sin(M_PI/6), 0);
glColor3f(0, 0, 0);
glutSolidSphere(0.15, 5, 5); //olho 1
glPopMatrix();
glPushMatrix();
glTranslatef(raio2*cos(M_PI/6), raio2*sin(-M_PI/6), 0);
glColor3f(0, 0, 0);
glutSolidSphere(0.15, 5, 5); //olho 2
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(-M_PI/4), raio2*sin(M_PI/4), 0);
float teta = sin(movimento * 2 * M_PI);
glRotatef(teta * 15, 0, teta * 10, 1);
drawPerninhas(2, 1.8, 1.5, 1, 2.5, 2, 0); //perna 1
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(M_PI/4), raio2*sin(-M_PI/4), 0);
teta = sin(movimento * 2 * M_PI);
glRotatef(-teta * 15, 0, teta * 10, 1);
drawPerninhas(2, 1.8, -1.5, 1, 2.5, -2, 0); //perna 1
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(M_PI/3.5), raio2*sin(-M_PI/3.5), 0);
teta = sin(movimento * 2 * M_PI);
glRotatef(teta * 7.5, 0, teta * 7.5, 1);
drawPerninhas(2, 1, -2.5, 1, 2, -3, 0); //perna 2
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(-M_PI/3.5), raio2*sin(M_PI/3.5), 0);
teta = sin(movimento * 2 * M_PI);
glRotatef(-teta * 7.5, 0, teta * 7.5, 1);
drawPerninhas(2, 1, 2.5, 1, 2, 3, 0); //perna 2
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(-M_PI/3), raio2*sin(M_PI/3), 0);
teta = sin(movimento * 2 * M_PI);
glRotatef(teta * 7.5, 0, teta * 7.5, 1);
drawPerninhas(2, 0, 3.5, 1, 1, 4, 0); //perna 3
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(M_PI/3), raio2*sin(-M_PI/3), 0);
teta = sin(movimento * 2 * M_PI);
glRotatef(-teta * 7.5, 0, teta * 7.5, 1);
drawPerninhas(2, 0, -3.5, 1, 1, -4, 0); //perna 3
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(M_PI/2.5), raio2*sin(-M_PI/2.5), 0);
//glRotatef(-30, 0, 0, 1);
teta = sin(movimento * 2 * M_PI);
glRotatef(teta * 15, 0, teta * 10, 1);
drawPerninhas(2, -1, -3.5, 1, -2, -5, 0); //perna 4
glPopMatrix();
glPushMatrix();
glColor3ub(92, 51, 23);
glTranslatef(raio2*cos(-M_PI/2.5), raio2*sin(M_PI/2.5), 0);
teta = sin(movimento * 2 * M_PI);
glRotatef(-teta * 15, 0, teta * 10, 1);
drawPerninhas(2, -1, 3.5, 1, -2, 5, 0); //perna 4
glPopMatrix();
glPopMatrix();
}
/**
* @desc Função de callback para desenho na tela.
*/
void displayCallback(){
/** Limpa a janela APENAS uma vez */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glColor3f(1.0f, 0.0f, 0.0f);
/** Desenha a janela mais a esquerda de cima */
glViewport(0, 0, width/2, height);
glLoadIdentity();
gluLookAt(5.0, 5.0, 10.0, xB*cos(alfa*M_PI/180), yB*sin(alfa*M_PI/180), zB, 0.0, 1.0, 0.0);
drawChao();
drawSky();
glRotatef(-90.0, 1.0, 0.0, 0.0);
drawAranha(raio1, raio2, 15);
/** Desenha a janela mais a direita de cima */
glViewport(width/2, 0, width/2, height);
glLoadIdentity();
gluLookAt(0, 10, 10.0, xB*cos(alfa*M_PI/180), yB*sin(alfa*M_PI/180), zB, 0.0, 1.0, 0.0);
drawChao();
drawSky();
glRotatef(-90.0, 1.0, 0.0, 0.0);
drawAranha(raio1, raio2, 15);
/** Dispara os comandos APENAS uma vez */
glFlush();
}
/* Realiza a animacao das pernas da aranha*/
void anima(){
int tempo_novo = glutGet(GLUT_ELAPSED_TIME);
int dt = tempo_novo - tempo_ant;
if(andando){
movimento = fmod(movimento + dt/1000.0 * rotpers, 1);
andando--;
}
if(!andando) movimento = 0;
tempo_ant = tempo_novo;
glutPostRedisplay();
}
void neblina(unsigned char key, int x, int y){
//a neblina deve aparecer quando a tecla n é pressionada, e desaparecer quando é pressionada novamente
if(key == 'n'){
/* Definindo os parametros do fog*/
GLfloat fogColor[4] = {0.8, 0.8, 0.8, 1};
GLint fogMode = GL_EXP;
glFogi(GL_FOG_MODE, fogMode);
glFogfv(GL_FOG_COLOR, fogColor);
glFogf(GL_FOG_DENSITY, 0.2);
glHint(GL_FOG_HINT, GL_DONT_CARE);
glFogf(GL_FOG_START, 1);
glFogf(GL_FOG_END, 5);
/*Ativando ou desativando o fog*/
if(glIsEnabled(GL_FOG) == GL_TRUE) glDisable(GL_FOG);
else glEnable(GL_FOG);
glutPostRedisplay();
}
}
void keyboard_func(GLint key, GLint x, GLint y){
//GLUT_KEY_UP, GLUT_KEY_DOWN, GLUT_KEY_LEFT, GLUT_KEY_RIGHT
if(key == GLUT_KEY_UP){
//andar para frente
if(xA < 10 && xB < 10){
xA += 1;
xB += 1;
}
andando = 100;
glutPostRedisplay();
} else if(key == GLUT_KEY_DOWN){
//andar para tras
if(xA > -10 && xB > -10) {
xA -= 1;
xB -= 1;
}
andando = 100;
glutPostRedisplay();
} else if(key == GLUT_KEY_LEFT){
//rodar
alfa -= 10;
glutPostRedisplay();
} else if(key == GLUT_KEY_RIGHT){
//rodar
alfa += 10;
glutPostRedisplay();
}
}
/**
* @desc Função de callback para reshape.
* @param {int} w Nova larguraAda Aanela.
* @param {int} h Nova altura da janela.
*/
void reshapeCallback(int w, int h){
/** Atualiza os valores da janela */
width = w;
height = h;
/** Define o volume de vista */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(65.0, (GLfloat) width/(GLfloat) height, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char **argv){
/** Passo 1: Inicializa funções GLUT */
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowPosition(100, 100);
glutInitWindowSize(width, height);
glutCreateWindow("Duas viewports");
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
tempo_ant = glutGet(GLUT_ELAPSED_TIME);
/** Passo 2: Registra callbacks da OpenGl */
glutDisplayFunc(displayCallback);
glutIdleFunc(anima);
glutReshapeFunc(reshapeCallback);
glutSpecialFunc(keyboard_func);
glutKeyboardFunc(neblina);
/** Passo 3: Executa o programa */
glutMainLoop();
return 0;
}
| true |
f98f963933beb89cff8cdde3563eb6c6c2b12d47 | C++ | Jekkt/ph1211GameProgClass | /NYUCodebase/NYUCodebase/main.cpp | UTF-8 | 5,069 | 2.625 | 3 | [] | no_license | #ifdef _WINDOWS
#include <GL/glew.h>
#endif
#include <SDL.h>
#include <SDL_opengl.h>
#include <SDL_image.h>
#include "Matrix.h"
#include "ShaderProgram.h"
#ifdef _WINDOWS
#define RESOURCE_FOLDER ""
#else
#define RESOURCE_FOLDER "NYUCodebase.app/Contents/Resources/"
#endif
SDL_Window* displayWindow;
GLuint loadTexture(const char *image_path);
float lastFrameTicks = 0.0f;
float angle = 0;
int main(int argc, char *argv[])
{
SDL_Init(SDL_INIT_VIDEO);
displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
glewInit();
#endif
glViewport(0, 0, 640, 360);
ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
Matrix projectionMatrix;
Matrix modelMatrix;
Matrix viewMatrix;
GLuint skeletonTex = loadTexture("skeleton.png");
GLuint nyanTex = loadTexture("nyan.png");
GLuint eyeTex = loadTexture("eye.png");
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
SDL_Event event;
bool done = false;
while (!done) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
done = true;
}
else if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.scancode == SDL_SCANCODE_SPACE) {
angle = 0.0f;
std::cout << "Space pressed!" << std::endl;
}
}
}
float ticks = (float)SDL_GetTicks() / 1000.0f;
float elapsed = ticks - lastFrameTicks;
lastFrameTicks = ticks;
glClearColor(0.5f, 0.5f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
const Uint8 *keys = SDL_GetKeyboardState(NULL);
if (keys[SDL_SCANCODE_LEFT]) {
//go left
std::cout << "Pressing Left" << std::endl;
angle += elapsed;
}
else if (keys[SDL_SCANCODE_RIGHT]) {
// go right
std::cout << "Pressing Right" << std::endl;
angle -= elapsed;
}
projectionMatrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f);
//modelMatrix.identity();
modelMatrix.Rotate(elapsed * 20 * (3.1415926f / 180.0f));
program.setModelMatrix(modelMatrix);
program.setProjectionMatrix(projectionMatrix);
program.setViewMatrix(viewMatrix);
glUseProgram(program.programID);
//eye
loadTexture("eye.png");
float vertices1[] = {-0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f };
//float vertices2[] = { -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f };
glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices1);
glEnableVertexAttribArray(program.positionAttribute);
float texCoords1[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f};
glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords1);
glEnableVertexAttribArray(program.texCoordAttribute);
glDrawArrays(GL_TRIANGLES, 0, 12);
//nyan
loadTexture("nyan.png");
float vertices3[] = { 1.5f, -0.5f, 2.5f, 0.5f, 1.5f, 0.5f, 1.5f, -0.5f, 2.5f, -0.5f, 2.5f, 0.5f };
glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3);
glEnableVertexAttribArray(program.positionAttribute);
float texCoords3[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f };
glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords3);
glEnableVertexAttribArray(program.texCoordAttribute);
glDrawArrays(GL_TRIANGLES, 0, 12);
//skeleton
loadTexture("skeleton.png");
float vertices5[] = { -1.5f, 0.5f, -1.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -1.5f, 0.5f };
//float vertices6[] = { -1.5f, 0.5f, -1.5f, -0.5f, -0.5f, 0.5f };
glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices5);
glEnableVertexAttribArray(program.positionAttribute);
float texCoords5[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f };
glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords5);
glEnableVertexAttribArray(program.texCoordAttribute);
glDrawArrays(GL_TRIANGLES, 0, 12);
//test
/*
glBegin(GL_TRIANGLES);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f(0.0f, 2.0f, 0.0f);
glVertex3f(1.0f, 2.0f, 0.0f);
glEnd();
*/
glDisableVertexAttribArray(program.positionAttribute);
glDisableVertexAttribArray(program.texCoordAttribute);
SDL_GL_SwapWindow(displayWindow);
}
SDL_Quit();
return 0;
}
GLuint loadTexture(const char *image_path) {
SDL_Surface *surface = IMG_Load(image_path);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(surface);
return textureID;
} | true |
18bcab335a2d36b8ba08b4b169212c451fc2ecee | C++ | Broadroad/learnLeetcode | /24.swap-nodes-in-pairs.cpp | UTF-8 | 1,145 | 3.609375 | 4 | [
"Apache-2.0"
] | permissive | /*
* @lc app=leetcode id=24 lang=cpp
*
* [24] Swap Nodes in Pairs
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*
*
* Pointer-pointer pp points to the pointer to the current node. So at first, pp points to head, and later it points to the next field of ListNodes. Additionally, for convenience and clarity, pointers a and b point to the current node and the next node.
* We need to go from *pp == a -> b -> (b->next) to *pp == b -> a -> (b->next). The first three lines inside the loop do that, setting those three pointers (from right to left). The fourth line moves pp to the next pair.
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode **pp = &head, *cur, *next;
while ((cur = *pp) && (next = cur->next))
{
cur->next = next->next;
next->next = cur;
*pp = next; // need to make sure that head point to the first node.
pp = &(cur->next); // pp move to the next pair
}
return head;
}
};
| true |
7505309b74c4aa1efc01f2f12581110614a535e2 | C++ | Danigabe/isosphere-game | /src/cBall.cpp | UTF-8 | 6,364 | 2.515625 | 3 | [] | no_license | #include "cBall.h"
cBall::cBall() {
inGoal = false;
}
cBall::~cBall() {
}
void cBall::Render() {
glPushMatrix();
glTranslatef(pos.x, pos.y, pos.z);
//glDepthMask(false);
glColor3f(1.0f, 0.5967f, 0.3254f);
glutSolidSphere(0.5f, 20, 20);
//glDepthMask(true);
glPopMatrix();
}
void cBall::Start() {
dir = initial_dir;
vel = 0.04f; // 2 blocks per sec
inGoal = false;
}
void cBall::Stop() {
vel = 0;
}
void cBall::SetPos(float x, float y, float z) {
pos = cVector(x, y, z);
}
void cBall::SetInitialDir(int dir_) {
initial_dir = dir_;
}
bool cBall::PhysStep(const BlockMatrix3D& map) {
cVector basePos = pos - cVector(0.0f, 0.5f, 0.0f);
int base_posx = (int)(basePos.x + 0.5f),
base_posy = (int)(basePos.y + 0.5f),
base_posz = (int)(basePos.z + 0.5f);
if (!CheckBounds(map, base_posx, base_posy, base_posz))
return true; // ball out of map
cVector moveDir(0.0f, 0.0f, 0.0f);
if (dir == DIR_UP) moveDir.z = -vel;
else if (dir == DIR_DOWN) moveDir.z = vel;
else if (dir == DIR_RIGHT) moveDir.x = -vel;
else if (dir == DIR_LEFT) moveDir.x = vel;
float friction = 0.0f;
if (!map[base_posx][base_posy][base_posz].TouchingUp(basePos, base_posx, base_posy, base_posz))
moveDir.y -= 0.02;
moveDir.x /= 4.0f;
moveDir.z /= 4.0f;
cVector newPos = pos + moveDir;
cVector newBase = newPos - cVector(0.0f, 0.5f, 0.0f);
int newbase_posx = (int)(newBase.x + 0.5f),
newbase_posy = (int)(newBase.y + 0.5f),
newbase_posz = (int)(newBase.z + 0.5f);
if (!CheckBounds(map, newbase_posx, newbase_posy, newbase_posz))
return true;
if (map[newbase_posx][newbase_posy][newbase_posz].TouchingUp(newBase, newbase_posx, newbase_posy, newbase_posz)) {
friction = map[newbase_posx][newbase_posy][newbase_posz].GetFriction();
if ((map[newbase_posx][newbase_posy][newbase_posz].IsType(BLOCK_QUAD) ||
map[newbase_posx][newbase_posy][newbase_posz].IsType(BLOCK_STACK_QUAD_QUAD)) &&
(map[base_posx][base_posy][base_posz].IsType(BLOCK_SLOPE) ||
map[base_posx][base_posy][base_posz].IsType(BLOCK_STACK_QUAD_SLOPE))) {
newPos.y = (float)newbase_posy + 0.5f;
}
else if (map[newbase_posx][newbase_posy][newbase_posz].IsType(BLOCK_HALF_QUAD) &&
map[base_posx][base_posy][base_posz].IsType(BLOCK_HALF_QUAD)) {
newPos.y = (float)newbase_posy;
}
// touching slope
if (map[newbase_posx][newbase_posy][newbase_posz].IsType(BLOCK_SLOPE)) {
newPos.x = pos.x + moveDir.x*0.5f;
newPos.z = pos.z + moveDir.z*0.5f;
if (dir == map[newbase_posx][newbase_posy][newbase_posz].GetDir()) {
vel *= 0.996f;
newPos.y = pos.y + abs(moveDir.x*0.52f) + abs(moveDir.z*0.52f);
moveDir.y = newPos.y - pos.y;
if (vel < 0.005) {
dir = (dir+2)%4;
vel += 0.00025;
friction = 0.0f;
}
}
else if ((dir+2)%4 == map[newbase_posx][newbase_posy][newbase_posz].GetDir()) {
vel *= 1.025;
newPos.y = pos.y - abs(moveDir.x*0.5f) - abs(moveDir.z*0.5f);
moveDir.y = newPos.y - pos.y;
}
else if (fequals(newBase.x, (float)newbase_posx) && fequals(newBase.z, (float)newbase_posz))
dir = (map[newbase_posx][newbase_posy][newbase_posz].GetDir()+2)%4;
}
// touching half slope or stacked slope
else if (map[newbase_posx][newbase_posy][newbase_posz].IsType(BLOCK_HALF_SLOPE) ||
(map[newbase_posx][newbase_posy][newbase_posz].IsType(BLOCK_STACK_QUAD_SLOPE))) {// && newBase.y > (float)newbase_posy)) {
newPos.x = pos.x + moveDir.x;
newPos.z = pos.z + moveDir.z;
if (dir == map[newbase_posx][newbase_posy][newbase_posz].GetDir()) {
vel *= 0.9975;
newPos.y = pos.y + abs(moveDir.x*0.52f) + abs(moveDir.z*0.52f);
moveDir.y = newPos.y - pos.y;
if (vel < 0.005) {
dir = (dir+2)%4;
vel += 0.00025;
friction = 0.0f;
}
}
else if ((dir+2)%4 == map[newbase_posx][newbase_posy][newbase_posz].GetDir()) {
vel *= 1.0125;
newPos.y = pos.y - abs(moveDir.x*0.5f) - abs(moveDir.z*0.5f);
moveDir.y = newPos.y - pos.y;
}
else if (fequals(newBase.x, (float)newbase_posx) && fequals(newBase.z, (float)newbase_posz))
dir = (map[newbase_posx][newbase_posy][newbase_posz].GetDir()+2)%4;
}
else {
newPos.y = pos.y;
moveDir.y = 0.0f;
}
}
cVector frontDir = moveDir; frontDir.y = 0;
cVector front = newPos + cVector::normalize(frontDir)*0.5f;
int front_posx = (int)(front.x + 0.5f),
front_posy = (int)(front.y + 0.5f),
front_posz = (int)(front.z + 0.5f);
if (CheckBounds(map, front_posx, front_posy, front_posz)) {
if (map[front_posx][front_posy][front_posz].TouchingSide(front, dir, front_posy)) {
newPos.x = pos.x;
newPos.z = pos.z;
dir = (dir+2)%4;
}
}
else {
dir = (dir+2)%4;
}
pos = newPos;
vel -= friction;
CheckOverBlock(map);
if (vel < 0.0001)
return true;
return false;
}
bool cBall::IsInGoal() const {
return inGoal;
}
bool cBall::CheckBounds(const BlockMatrix3D& map, int x, int y, int z) const {
if (x < 0 || (unsigned int)x >= map.size())
return false;
if (y < 0 || (unsigned int)y >= map[x].size())
return false;
if (z < 0 || (unsigned int)z >= map[x][y].size())
return false;
return true;
}
void cBall::CheckOverBlock(const BlockMatrix3D& map) {
// base in tile space
cVector base = pos + cVector(0.5f, 0.025f, 0.5f);
float modx = fmod(base.x, 1.0f),
modz = fmod(base.z, 1.0f);
if (fequals(modx, 0.5f, 0.05) && // is aproximately in
fequals(modz, 0.5f, 0.05)) // the center of the block
{
int basex = (int)base.x,
basey = (int)base.y,
basez = (int)base.z;
if (map[basex][basey][basez].IsType(BLOCK_DIRECTIONAL)) {
if (dir != (map[basex][basey][basez].GetDir()+2)%4)
if (vel < 0.05f)
vel += 0.01f;
dir = map[basex][basey][basez].GetDir();
}
if (map[basex][basey][basez].IsType(BLOCK_STACK_QUAD_DIR)) {
if (dir != (map[basex][basey][basez].GetDir()+2)%4)
if (vel < 0.05f)
vel += 0.01f;
dir = map[basex][basey][basez].GetDir();
}
if (map[basex][basey][basez].IsType(BLOCK_GOAL))
inGoal = true;
}
} | true |
d337cf42d7beda6ec3e1dc268a675942765b0573 | C++ | grahameger/EECS398Engine | /include/StringView.h | UTF-8 | 830 | 2.828125 | 3 | [] | no_license | #ifndef STRINGVIEW_H
#define STRINGVIEW_H
// Note that StringView does NOT have ownership of it's CString and thus does not
// delete it when finished.
//
class StringView
{
public:
StringView( );
StringView( char* CString, unsigned length, bool forwards = true );
bool Empty( ) const;
unsigned Size( ) const;
const char* const CString( ) const;
char* const RawCString( ) const;
bool Compare( const StringView& other ) const;
template < typename T >
const T GetInString( unsigned offset = 0 ) const;
template < typename T >
void SetInString( T value, unsigned offset = 0 );
const char operator[ ] ( int index ) const;
operator bool( ) const;
private:
char* cString;
unsigned length;
bool forwards;
};
#endif
| true |
db9288ea787604bf77d307af2ebc3efb1cfb3fde | C++ | Richard-coder-Nai/OJ | /acwing/1523.cpp | UTF-8 | 607 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
#include<unordered_map>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main(void) {
int n, k;
cin>>n>>k;
unordered_map<string, vector<int>> table;
for(int i=0; i<k; i++) {
int idx, Nums;
cin>>idx>>Nums;
for(int i=0; i<Nums; i++){
string name;
cin>>name;
table[name].push_back(idx);
}
}
for(auto &it:table){
sort(it.second.begin(), it.second.end());
}
for(int i=0; i<n; i++){
string name;
cin>>name;
cout<<name<<" ";
cout<<table[name].size()<<" ";
for(int it:table[name]) {
cout<<it<<" ";
}
cout<<endl;
}
}
| true |
f50c6ffb887972bbf9f469569d0087c066bfa540 | C++ | Jungzhang/SlothServer | /Common/InfoPkg.cpp | WINDOWS-1252 | 813 | 2.515625 | 3 | [
"MIT"
] | permissive | /*************************************************************************
> File Name: InfoPkg.cpp
> Author: Raiden
> Mail: jungzhang@xiyoulinux.org
> Created Time: Thu Sep 28 00:52:47 2017
************************************************************************/
#include <memory>
#include <cstring>
#include "InfoPkg.h"
std::shared_ptr<char> InfoPkg::serialize()
{
std::shared_ptr<char> buf(new char[6]);
if (buf == nullptr)
{
return nullptr;
}
memcpy(buf.get(), &this->_remoteAddr, 4);
memcpy(buf.get() + 4, &this->_port, 2);
return buf;
}
int InfoPkg::deserialize(const char *data, int len)
{
//
if (len != 6)
{
return -1;
}
memcpy(&this->_remoteAddr, data , 4);
memcpy(&this->_port, data + 4, 2);
return 0;
}
int InfoPkg::size()
{
return 6;
}
| true |
68cd885e54ffdbf0e2c31599a38bf34d5a9b72ff | C++ | nasrat-v/cross-platform-client-network-module | /src/ClientNetwork.cpp | UTF-8 | 6,761 | 2.53125 | 3 | [] | no_license |
#include "../../header/Network/ClientNetwork.hh"
ClientNetwork::ClientNetwork()
{
_connected = false;
}
ClientNetwork::~ClientNetwork() = default;
#ifdef _WIN32
void ClientNetwork::startWSA()
{
WSAStartup(MAKEWORD(2, 0), &_wsaData);
Log::logSomething("\nInitialize windows network - WSA Startup\n");
}
void ClientNetwork::stopWSA()
{
WSACleanup();
Log::logSomething("\nClean windows network - WSA Cleanup\n");
}
#endif
ERR ClientNetwork::initSocket()
{
if ((_sock = socket(_srvParam.ipType, _srvParam.socketType, _srvParam.protocol)) == NET_ERROR)
{
LogNetwork::logFailureMsg("Error socket initialization");
return (NET_ERROR);
}
LogNetwork::logSuccessMsg("Successfully initialize socket: " + std::to_string(_sock));
return (SUCCESS);
}
ERR ClientNetwork::initHandleSocketWithIpAddress()
{
__binary_iptype binaryIpAddress = 0;
__sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = _srvParam.ipType;
sin.sin_port = htons(_srvParam.port);
if (__inetpton(_srvParam.ipType, _srvParam.ipAddr, &binaryIpAddress) != 1)
{
logFailureMsg("Error when initialize socket, invalid param ", true);
return (NET_ERROR);
}
sin.sin_addr.s_addr = binaryIpAddress;
_sins.push_back(sin);
LogNetwork::logSuccessMsg("Successfully initialize socket handle with ip address");
return (SUCCESS);
}
void ClientNetwork::initHandleSocketWithHostname()
{
int i = 0;
__sockaddr_in sin;
struct addrinfo *p;
for (p = _addrInfo; p != nullptr; p = p->ai_next)
{
memset(&sin, 0, sizeof(sin));
sin = *(reinterpret_cast<__sockaddr_in*>(p->ai_addr));
sin.sin_port = htons(_srvParam.port);
_sins.push_back(sin);
i++;
}
LogNetwork::logInfoMsg(std::to_string(i) + " ip address found");
if (_addrInfo != nullptr)
freeaddrinfo(_addrInfo);
LogNetwork::logSuccessMsg("Successfully initialize socket handle with hostname");
}
ERR ClientNetwork::findIpAddrWithHostname()
{
struct addrinfo hints;
memset(&_addrInfo, 0, sizeof(_addrInfo));
memset(&hints, 0, sizeof(hints));
hints.ai_family = _srvParam.ipType;
hints.ai_socktype = _srvParam.socketType;
hints.ai_protocol = _srvParam.protocol;
if ((__getaddrinfo(_srvParam.hostName, _srvParam.serviceName, &hints, &_addrInfo) != 0) || (_addrInfo == nullptr))
{
LogNetwork::logFailureMsg("Error cannot retrieve ip address with hostname");
return (NET_ERROR);
}
LogNetwork::logSuccessMsg("Successfully retrieve ip address of: " + std::string(_srvParam.hostName));
return (SUCCESS);
}
ERR ClientNetwork::initNetworkClient(const t_serverParam &srvParam)
{
#ifdef __WIN32
startWSA();
#endif
_srvParam = srvParam;
_sins.clear();
LogNetwork::logSomething("Server param received\nLaunch initialization of the client...\n");
if (_srvParam.ipAddr != nullptr)
initHandleSocketWithIpAddress();
else if (_srvParam.hostName != nullptr)
{
if (findIpAddrWithHostname() == NET_ERROR)
return (NET_ERROR);
initHandleSocketWithHostname();
}
else
{
LogNetwork::logFailureMsg("Bad param - no ip address or hostname set");
return (NET_ERROR);
}
if (initSocket() == NET_ERROR)
return (NET_ERROR);
return (SUCCESS);
}
ERR ClientNetwork::connectToServer()
{
char hostsIp[SIZE_BUFF] = { 0 };
std::string connectionData;
for (__sockaddr_in &sin : _sins)
{
if (__inetntop(sin.sin_family, &sin.sin_addr, hostsIp, SIZE_BUFF) == nullptr)
LogNetwork::logSomething("\nWarning ! error when parsing ip server");
else
LogNetwork::logSomething("\nTrying to connect to server " + std::string(hostsIp) + ':' + std::to_string(sin.sin_port));
if (connect(_sock, (__sockaddr*)&sin, sizeof(__sockaddr)) != NET_ERROR)
{
LogNetwork::logSuccessMsg("Successfully connect to server");
_connected = true;
return (SUCCESS);
}
logFailureMsg("Error connection failed ", true);
}
LogNetwork::logFailureMsg("Error all connections failed");
return (NET_ERROR);
}
void ClientNetwork::deconnectToServer()
{
char error_code[SIZE_BUFF] = { 0 };
__err_size error_code_size = sizeof(error_code);
__attribute__((unused))int status;
LogNetwork::logTryMsg("Cleaning server connection...");
if (getsockopt(_sock, SOL_SOCKET, SO_ERROR, error_code, &error_code_size) == NET_ERROR)
{
#ifdef _WIN32
if ((status = WSAGetLastError()) == WSAENOTSOCK)
Log::logSuccessMsg("Socket already closed or never initialized");
else
Log::logFailureMsg("Error when closing socket: " + status);
#elif __linux__ || __unix__ || __unix || unix || __APPLE__ || __MACH__
LogNetwork::logFailureMsg("Error when closing socket");
#endif
}
else
{
LogNetwork::logSuccessMsg("Successfully close socket");
__close_socket(_sock);
}
_connected = false;
#ifdef __WIN32
stopWSA();
#endif
}
ERR ClientNetwork::readData(std::string &data)
{
__ret ret;
char buff[(SIZE_BUFF + sizeof(char))] = { 0 };
while ((ret = __read_socket(_sock, buff, SIZE_BUFF, 0)) == SIZE_BUFF)
{
data.append(buff, SIZE_BUFF);
memset(buff, 0, (SIZE_BUFF + sizeof(char)));
}
if (ret > 0)
{
buff[ret] = '\0'; // to be sure
data.append(buff, static_cast<unsigned long>(ret));
}
else if (ret < 0)
{
LogNetwork::logFailureMsg("Error failed to read data from socket");
return (NET_ERROR);
}
else
{
LogNetwork::logInfoMsg("Received deconnection notification from server");
deconnectToServer();
return (SUCCESS);
}
LogNetwork::logSomething("\nReceived:\n" + data + "\n:From Server\n");
return (SUCCESS);
}
ERR ClientNetwork::writeData(const std::string &data)
{
auto size = (__size)data.size();
const char *dataToSend = data.c_str();
if ((__write_socket(_sock, dataToSend, size, 0)) == NET_ERROR)
{
LogNetwork::logFailureMsg("\nError failed to write data to socket");
return (NET_ERROR);
}
LogNetwork::logSomething("\nSend:\n" + data + "\n:To server\n");
return (SUCCESS);
}
bool ClientNetwork::isDataToRead()
{
clearSocket();
if (select(((__socket)_sock + 1), &_fd_set, nullptr, nullptr, nullptr) == -1)
{
logFailureMsg("Error on select ", true);
return (false);
}
return (FD_ISSET(_sock, &_fd_set));
}
bool ClientNetwork::isConnected() const
{
return (_connected);
}
void ClientNetwork::clearSocket()
{
FD_ZERO(&_fd_set);
FD_SET(_sock, &_fd_set);
LogNetwork::logSomething("Socket: " + std::to_string(_sock) + " cleared\n");
}
void ClientNetwork::logFailureMsg(const std::string &msg, __attribute__((unused))bool errorCode)
{
#ifdef _WIN32
if (errorCode)
LogNetwork::logFailureMsg(msg + WSAGetLastError());
else
LogNetwork::logFailureMsg(msg);
#elif __linux__ || __unix__ || __unix || unix || __APPLE__ || __MACH__
LogNetwork::logFailureMsg(msg);
#endif
}
void ClientNetwork::setLogActive(bool log)
{
_logActive = log;
LogNetwork::setLogActive(log);
}
bool ClientNetwork::isLogActive() const
{
return (_logActive);
} | true |
94aaeed9bb07c61cd81678d3d952d0affaccfb58 | C++ | rintujrajan/DesignPattern | /PatternsCompunded/Locomotive/main.cpp | UTF-8 | 3,070 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include "Subjects\SpeedMonitor.h"
#include "Subjects\GeoPosMonitor.h"
#include "Observers\DataUploader.h"
#include "Observers\Speaker.h"
#include "Sensors\SpeedSensor.h"
#include "Sensors\GPSSensor.h"
#include "Controller.h"
int main()
{
std::thread threadToExecuteCommands([]() { Controller::getControllerInstance().executeQueuedCommands(); });
std::vector<int> speeds = {0, 1, 2, 3, 4, 5};
// We have used shared_ptr instead of unique_ptr since the pointer is shared by various classes
// If we use a unique_ptr and then move it, we will get segfault at next usage
// We create share pointers to both of our concrete subjects
// notice that there is object slicing and concrete subjects are used
std::shared_ptr<SpeedMonitor>
speedMonitor = std::make_shared<SpeedMonitor>();
std::shared_ptr<GeoPosMonitor> geoPosMonitor = std::make_shared<GeoPosMonitor>();
// We create shared pointer for the DataUploader observer and then register it to the two concrete subjects
std::shared_ptr<IObserver> dataUploader = std::make_shared<DataUploader>();
speedMonitor->registerObserver(dataUploader);
geoPosMonitor->registerObserver(dataUploader);
// We create shared pointer for the Speaker observer and then register it to the concrete subject - SpeedMonitor
std::shared_ptr<IObserver> speaker = std::make_shared<Speaker>();
speedMonitor->registerObserver(speaker);
// We here try to simulate a speed sensor updating speed data which would trigger to the Subject-SpeedMonitor to notify it's observers
SpeedSensor speedSensor(speedMonitor);
for (auto speed : speeds)
{
speedSensor.speedChangedTo(speed); //this can be some external api call as well
}
std::this_thread::sleep_for(std::chrono::seconds(3));
// We here try to simulate a GPS sensor updating GPS data which would trigger to the Subject-GeoPosMonitor to notify it's observers
GPSSensor gpsSensor(geoPosMonitor);
gpsSensor.geoPositionChangedTo(200, 500); //this can be some external api call as well
auto incSpeedByFives = [](int &speed) { return speed + 5; };
std::transform(speeds.begin(), speeds.end(), speeds.begin(), incSpeedByFives);
for (auto speed : speeds)
{
speedSensor.speedChangedTo(speed); //this can be some external api call as well
}
std::this_thread::sleep_for(std::chrono::seconds(3));
// We now remove the DataUploader Observer from observing the SpeedMonitor Subject. When speed changes only the Speaker subject would be notified
// speedMonitor->removeObserver(dataUploader);
std::transform(speeds.begin(), speeds.end(), speeds.begin(), incSpeedByFives);
for (auto speed : speeds)
{
speedSensor.speedChangedTo(speed); //this can be some external api call as well
}
std::this_thread::sleep_for(std::chrono::seconds(3));
Controller::getControllerInstance().stopLoop();
threadToExecuteCommands.join();
std::cin.get();
} | true |
1af44846504304902bd55569faa01dde38b2c85e | C++ | macl1012/leetcode-cpp-do | /106.从中序与后序遍历序列构造二叉树.cpp | UTF-8 | 1,582 | 3.296875 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=106 lang=cpp
*
* [106] 从中序与后序遍历序列构造二叉树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
// 中序遍历:左子树 根 右子树
// 后序遍历:左子树 右子树 根
if(inorder.size() == 0 || postorder.size() == 0)
return nullptr;
unordered_map<int, int> inMap;
for(int i=0; i<inorder.size(); i++)
inMap[inorder[i]] = i;
return buildTree(inorder, 0, inorder.size()-1, inMap,
postorder, 0, postorder.size()-1);
}
TreeNode* buildTree(vector<int>& inorder, int inStart, int inEnd, unordered_map<int, int>& inMap,
vector<int>& postorder, int postStart, int postEnd) {
if(inStart > inEnd || postStart > postEnd) return nullptr;
TreeNode* root = new TreeNode(postorder[postEnd]);
int inRoot = inMap[root->val];
int leftTree = inRoot - inStart;
root->left = buildTree(inorder, inStart, inRoot-1, inMap,
postorder, postStart, postStart+leftTree-1);
root->right = buildTree(inorder, inRoot+1, inEnd, inMap,
postorder, postStart+leftTree, postEnd-1);
return root;
}
};
// @lc code=end
| true |
82474e51e5e321d84b2aa787706ed7e52c44882c | C++ | dandachok/MAI | /OOP/Lab_03/TList.cpp | UTF-8 | 2,616 | 3.21875 | 3 | [] | no_license | #include "TList.hpp"
TList::TList() {
head = nullptr;
size = 0;
}
size_t TList::GetSize() {
return this->size;
}
bool TList::IsEmpty() {
return head == nullptr;
}
void TList::PushIndex(size_t index, std::shared_ptr<Figure>& obj) {
if(index > size) {
return;
}
else {
std::shared_ptr<TListItem> item = head;
for(int i = 0; i < index; i++) {
item = item->GetNext();
}
std::shared_ptr<TListItem> new_item = std::make_shared<TListItem>(obj);
new_item->SetNext(item->GetNext());
new_item->SetPrev(item);
item->GetNext()->SetPrev(new_item);
item->SetNext(new_item);
size++;
}
}
void TList::PushLast(std::shared_ptr<Figure>& obj) {
std::shared_ptr<TListItem> item = std::make_shared<TListItem>(obj);
if(size == 0) {
head = item;
tail = item;
}
else {
item->SetPrev(tail);
tail->SetNext(item);
tail = item;
}
size++;
}
void TList::PushFirst(std::shared_ptr<Figure> &obj) {
std::shared_ptr<TListItem> item = std::make_shared<TListItem>(obj);
if(size == 0) {
head = item;
tail = item;
}
else {
item->SetNext(head);
head->SetPrev(item);
head = item;
}
size++;
}
std::shared_ptr<Figure> TList::PopIndex(size_t index) {
}
std::shared_ptr<Figure> TList::PopFirst() {
if (size == 1) {
std::shared_ptr<Figure> res = this->head->GetFigure();
head = nullptr;
tail = nullptr;
size--;
return res;
}
head = head->GetNext();
std::shared_ptr<Figure> res = head->GetPrev()->GetFigure();
head->SetPrev(nullptr);
size--;
return res;
}
std::shared_ptr<Figure> TList::PopLast() {
if (size == 1) {
std::shared_ptr<Figure> res = head->GetFigure();
head = nullptr;
tail = nullptr;
size--;
return res;
}
tail = tail->GetPrev();
std::shared_ptr<Figure> res = head->GetNext()->GetFigure();
head->SetNext(nullptr);
size--;
return res;
}
TList::~TList() {
while (head) {
head->SetPrev(nullptr);
head = head->GetNext();
}
tail = nullptr;
}
std::shared_ptr<TListItem> TList::GetHead() {
return head;
}
std::ostream& operator<<(std::ostream& os, TList& list) {
std::shared_ptr<TListItem> item = list.head;
for(int i = 0; i < list.size; i++) {
os << "id: " << i + 1 << " ";
item->GetFigure()->Print();
item = item->GetNext();
os << std::endl;
}
os << std::endl;
return os;
}
| true |
4c9f12f7b7304422ab0635ef2cc6d0ebad8e8871 | C++ | MathewsJosh/teoria-dos-grafos-ufjf | /aresta.cpp | UTF-8 | 1,733 | 2.953125 | 3 | [
"MIT"
] | permissive | /**
* @file aresta.cpp
* @brief Arquivo do objeto aresta do projeto
*
* @warning Documentar sempre que possível!
* @todo
* @bug
* @authors João Victor - 201665528AB, Matheus Casarim 201765512AB, Mathews Edwirds 201765503AB. Grupo 19
*/
/*******************************************************************
* Includes
*******************************************************************/
#include "aresta.h"
/*******************************************************************
* IMPLEMENTACAO
*******************************************************************/
/**
* @brief Construtor do objeto aresta
*
* @param no Ponteiro para o vertice
* @param prox Ponteiro que indica o vertice adjacente
* @param peso Peso da aresta
*/
Aresta::Aresta(No *no, Aresta *prox, int peso)
{
this->no = no;
this->prox = prox;
this->peso = peso;
}
/**
* @brief Destrutor da aresta
*
*/
Aresta::~Aresta()
{
if (prox != NULL)
{
delete prox;
}
}
/**
* @brief Retorna o nó atual
*
* @return No* Retorna o nó atual
*/
No *Aresta::getNo()
{
return this->no;
}
/**
* @brief Determina o nó atual
*
* @param no Nó atual
*/
void Aresta::setNo(No *no)
{
this->no = no;
}
/**
* @brief Retorna o proximo nó
*
* @return Aresta* Proximo nó
*/
Aresta *Aresta::getProx()
{
return this->prox;
}
/**
* @brief Determina o proximo nó
*
* @param prox Proximo nó
*/
void Aresta::setProx(Aresta *prox)
{
this->prox = prox;
}
/**
* @brief Retorna o peso da aresta
*
* @return int Peso da aresta
*/
int Aresta::getPeso()
{
return this->peso;
}
/**
* @brief Determina o peso da aresta
*
* @param peso peso da aresta
*/
void Aresta::setPeso(int peso)
{
this->peso = peso;
} | true |
cc42f4f0e0aec248cd57b8e08d71ae62b03809bc | C++ | Robro7389/Array-101 | /max_consecutives_ones.cpp | UTF-8 | 616 | 3.21875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
//input goes here
int n;
cin>>n;
int a[n];
for (int i = 0; i < n; i++)
{
cin>>a[i];
}
//logic
int currlen=1;
int maxlen=1;
for (int i =1; i < n; i++)
{
if (a[i]==a[i-1])
{
currlen++;
if (currlen>maxlen)
{
maxlen=currlen;
}
}
else{
currlen=1;
}
}
//output goes here
cout<<"Max length is- "<<maxlen<<endl;
return 0;
} | true |
1689cd15dcf39d05d7bd90248407fb0c12b32d44 | C++ | gmeligio/axon_training | /Those who can not remember the past are condemned to repeat it - DP/Solutions/cmpeguerog/D - Approximating a Constant Range/D - Approximating a Constant Range.cpp | UTF-8 | 2,077 | 2.921875 | 3 | [
"MIT"
] | permissive | //
// Created by Carlos on 5/8/2019.
// Email: cmpeguerog@gmail.com
//
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
#define MAX 20
#define LOG_MAX 17
template <class T>
class RMQ {
public:
explicit RMQ(vector<T> values) {
this->n = values.size();
build(values);
}
T max(int lower, int upper) {
int exponent = static_cast<int>(log2((upper - lower + 1)));
return std::max(sparse[1][upper - (1 << exponent) + 1][exponent], sparse[1][lower][exponent]);
}
T min(int lower, int upper) {
int exponent = static_cast<int>(log2((upper - lower + 1)));
return std::min(sparse[0][upper - (1 << exponent) + 1][exponent], sparse[0][lower][exponent]);
}
private:
int n;
T sparse[2][MAX][LOG_MAX];
void build(vector<T> values) {
for(int i = 0; i < n; ++ i){
sparse[0][i][0] = sparse[1][i][0] = values[i];
}
for(int j = 1; (1 << j) <= n ; ++ j) {
for(int i = 0; i + (1 << (j - 1)) - 1 < n; ++ i){
sparse[0][i][j] = std::min(sparse[0][i][j - 1], sparse[0][i + (1 << (j - 1))][j - 1]);
sparse[1][i][j] = std::max(sparse[1][i][j - 1], sparse[1][i + (1 << (j - 1))][j - 1]);
}
}
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// freopen("test.in", "r", stdin);
int n;
cin >> n;
vector<int> values(static_cast<unsigned int>(n));
for(int i = 0; i < n; ++ i){
cin >> values[i];
}
auto rmq = new RMQ<int>(values);
int lower = 0, upper = 0, sol = -1;
while(upper < n) {
while(rmq->max(lower, upper) - rmq->min(lower, upper) <= 1) {
sol = std::max(sol, upper - lower + 1);
upper ++;
if( upper >= n ) {
break;
}
}
while(rmq->max(lower, upper) - rmq->min(lower, upper) > 1) {
lower ++;
}
}
cout << sol << endl;
return 0;
} | true |
f8a866954fed9e416b1f521d083644b5de0a1538 | C++ | caszhang/BackendDevelopmentEnvironment | /base/dsalgo_test/stack_test.cc | UTF-8 | 2,499 | 3.0625 | 3 | [] | no_license | // Author: zhangguoqiang01 <80176975@qq.com>
#include "gtest/gtest.h"
#include "dsalgo/stack.cc"
typedef struct Date {
int32_t year;
int32_t month;
int32_t date;
Date() {
year = 0;
month = 0;
date = 0;
}
} Date;
TEST(StackTest, TestNormal)
{
Stack<char> *stack = new Stack<char>;
bool ret = stack->Init(20);
EXPECT_TRUE(ret);
ret = stack->IsFull();
EXPECT_FALSE(ret);
ret = stack->IsEmpty();
EXPECT_TRUE(ret);
int32_t size = stack->GetSize();
EXPECT_EQ(0, size);
int32_t i = 0;
char c = 'a';
for (i = 0; i < 20; i++) {
ret = stack->Push(c + i);
EXPECT_TRUE(ret);
}
ret = stack->IsFull();
EXPECT_TRUE(ret);
ret = stack->IsEmpty();
EXPECT_FALSE(ret);
ret = stack->Push('z');
EXPECT_FALSE(ret);
size = stack->GetSize();
EXPECT_EQ(20, size);
c += 19;
char res = 0;
for (i = 0; i < 20; i++) {
ret = stack->Pop(res);
EXPECT_TRUE(ret);
EXPECT_EQ(res, c - i);
}
ret = stack->IsEmpty();
EXPECT_TRUE(ret);
ret = stack->IsFull();
EXPECT_FALSE(ret);
ret = stack->Pop(res);
EXPECT_FALSE(ret);
size = stack->GetSize();
EXPECT_EQ(0, size);
ret = stack->Release();
EXPECT_TRUE(ret);
delete stack;
stack = NULL;
}
TEST(StackTest, TestCompositeDataType)
{
Stack<Date> *stack = new Stack<Date>;
bool ret = stack->Init(20);
EXPECT_TRUE(ret);
ret = stack->IsFull();
EXPECT_FALSE(ret);
ret = stack->IsEmpty();
EXPECT_TRUE(ret);
int32_t size = stack->GetSize();
EXPECT_EQ(0, size);
int32_t i = 0;
for (i = 0; i < 20; i++) {
Date d;
d.year = i;
d.month = i;
d.date = i;
ret = stack->Push(d);
EXPECT_TRUE(ret);
}
ret = stack->IsFull();
EXPECT_TRUE(ret);
ret = stack->IsEmpty();
EXPECT_FALSE(ret);
Date d;
ret = stack->Push(d);
EXPECT_FALSE(ret);
size = stack->GetSize();
EXPECT_EQ(20, size);
Date res;
for (i = 0; i < 20; i++) {
ret = stack->Pop(res);
EXPECT_TRUE(ret);
EXPECT_EQ(res.year, 19 - i);
EXPECT_EQ(res.month, 19 - i);
EXPECT_EQ(res.date, 19 - i);
}
ret = stack->IsEmpty();
EXPECT_TRUE(ret);
ret = stack->IsFull();
EXPECT_FALSE(ret);
ret = stack->Pop(res);
EXPECT_FALSE(ret);
size = stack->GetSize();
EXPECT_EQ(0, size);
ret = stack->Release();
EXPECT_TRUE(ret);
}
| true |
2c2402bbd0cd20a079ea780fba39629743a8b6b1 | C++ | davideanastasia/ORIP | /common_lib/yuvwriter.h | UTF-8 | 1,192 | 2.765625 | 3 | [] | no_license | /*
* License
*
* Copyright 2011 Davide Anastasia <davideanastasia@users.sourceforge.net>
*/
#ifndef ORIP_YUVREADER_H
#define ORIP_YUVREADER_H
#include <iostream>
#include <fstream>
#include <string>
#include "framewriter.h"
namespace ORIP
{
class YUVWriter : public FrameWriter
{
public:
/*
* ctor
*/
YUVWriter();
/*
* virtual dtor
*/
virtual ~YUVWriter();
/*
* open an YUV video file
*/
void open(const std::string& filename);
/*
* get only the Y part of the YUV frame
* return if the status of the read operation
*/
bool storeY(char* Y);
/*
* get the YUV frame in planar format
* return if the status of the read operation
*/
bool storeYUV420(char* Y, char* U, char* V);
/*
* close the YUV video file
*/
void close();
/*
* Set frame dimension (CIF 352x288 is set by default)
*/
void setFrameSize(int width, int height);
/*
* Return current Width;
*/
int getFrameWidth();
/*
* Return current Height;
*/
int getFrameHeight();
private:
int m_Width;
int m_Height;
std::ofstream m_OutputFileStream;
};
}
#endif // ORIP_FRAMEREADER_H
| true |
17a9ae73d31f8fe54b1ebe3761ed291d7272f5e7 | C++ | cdr6934/ofParticleExperiments | /src/flickeringSquare.cpp | UTF-8 | 1,059 | 2.984375 | 3 | [] | no_license | //
// flickeringSquare.cpp
// animationTest
//
// Created by Chris Ried on 7/10/18.
//
#include "flickeringSquare.hpp"
#include "ofMain.h"
Flicker::Flicker() {
}
void Flicker::setup(){
xPos = ofGetWidth()/2;
yPos = ofGetHeight()/2;
size = ofRandom(10);
}
void Flicker::draw(float radius){
ofRect(xPos,yPos,1,1);
ofSetColor( 255,255,255, radius);
}
void Flicker::update(){
/*
xPos += ofRandom(10);
yPos += ofRandom(10);
size = ofRandom(10);
*/
randn = (int)ofRandom(5);
if(randn == 1) { yPos += ofRandom(5); }
if(randn == 2) { xPos += ofRandom(5); }
if(randn == 3) { yPos -= ofRandom(5); }
if(randn == 4) { xPos -= ofRandom(5); }
if(xPos >= ofGetWidth())
{
center();
}
if (xPos <= 0)
{
center();
}
if (yPos <= 0)
{
center();
}
if(yPos >= ofGetHeight())
{
center();
}
}
void Flicker::center()
{
xPos = ofGetWidth()/2;
yPos = ofGetHeight()/2;
}
| true |
fa5323ee2d1e0ecd821fcb847cc66adfe6332e7b | C++ | anujbajpai/treeProblems | /diameter_tree.cpp | UTF-8 | 1,784 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
struct node {
int data;
struct node *left, *right;
};
node* createnode(int data) {
node* new_node = new node();
new_node -> data = data;
new_node -> left = NULL;
new_node -> right = NULL;
return new_node;
}
int height_tree(node* temp, int cnt, int &max_cnt) {
int flag = 0;
if (temp -> left) {
flag = 1;
cnt ++;
height_tree(temp -> left, cnt, max_cnt);
}
if(temp -> right) {
if (!flag)
cnt++;
height_tree(temp -> right, cnt, max_cnt);
}
if (cnt > max_cnt)
max_cnt = cnt;
return max_cnt +1;
}
int diameter(node * root, int cnt, int max_cnt) {
int L, R;
L = height_tree(root-> left, cnt, max_cnt);
R = height_tree(root -> right, cnt, max_cnt);
return L +R +1;
}
int main() {
int cnt = 0, max_cnt = 0;
node *root;
root = createnode(1);
root -> left = createnode(2);
root -> right = createnode(3);
root -> left -> left = createnode(4);
root -> left -> right = createnode(5);
root -> left -> right -> left = createnode(14);
root -> left -> right -> right = createnode(15);
root -> right -> right= createnode(6);
//root -> right -> left= createnode(7);
//root -> right -> left -> right = createnode(8);
root -> right -> right -> right= createnode(9);
root -> right -> right -> right -> left = createnode(10);
root -> right -> right -> right -> left-> left = createnode(11);
root -> right -> right -> right -> left-> right = createnode(12);
root -> right -> right -> right -> right = createnode(13);
cout<<diameter(root, cnt, max_cnt);
//cout<<height_tree(root, cnt, max_cnt);
return 0;
}
| true |
15baffe452eb65f6f1c04bd54cf25852ff976f5b | C++ | Stiner/todengine | /code/tod/core/kernel.cc | UTF-8 | 4,988 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "tod/core/kernel.h"
#include "tod/core/assert.h"
#include "tod/core/module.h"
#include "tod/core/builtinmodule.h"
using namespace tod;
//-----------------------------------------------------------------------------
Kernel::Kernel()
{
String::initializeEncoding();
addModule(new BuiltinModule(this, "Builtin"));
root_ = create_node("Node", "");
pushCwn(root_);
}
//-----------------------------------------------------------------------------
Kernel::~Kernel()
{
while (cwn_.size())
popCwn();
root_.release();
initModuleOrder_.reverse();
for (InitModuleOrder::iterator i = initModuleOrder_.begin();
i != initModuleOrder_.end(); ++i)
(*i)->finalize();
Module* module = findModule("Builtin");
tod_assert(module);
delete module;
initModuleOrder_.clear();
modules_.clear();
types_.clear();
String::finalizeEncoding();
}
//-----------------------------------------------------------------------------
Object* Kernel::create(const String& type_name)
{
Types::iterator find_iter = types_.find(type_name);
if (types_.end() == find_iter)
return 0;
Object* new_obj = find_iter->second->create(type_name);
Node* new_node = dynamic_cast<Node*>(new_obj);
if (new_node)
--new_node->refCount_;
return new_obj;
}
//-----------------------------------------------------------------------------
Node* Kernel::create(const String& type_name, const Path& path)
{
Node* cur;
if (path.isAbsolute())
cur = root_;
else
cur = cwn_.top();
for (Path::iterator token = path.begin(); token != path.end(); ++token)
{
Node* child = cur->findChild(*token);
if (0 == child)
{
Node* new_node;
Path::iterator e = token;
if (++e == path.end())
new_node = create_node(type_name, *token);
else
new_node = create_node("Node", *token);
if (0 == new_node)
return 0;
cur->attach(new_node);
cur = new_node;
}
else
cur = child;
}
return cur;
}
//-----------------------------------------------------------------------------
Node* Kernel::lookup(const Path& path)
{
if (path == "/")
return root_;
if (path.isAbsolute())
return root_->relativeNode(path);
return cwn_.top()->relativeNode(path);
}
//-----------------------------------------------------------------------------
void Kernel::pushCwn(Node* node)
{
cwn_.push(node);
}
//-----------------------------------------------------------------------------
Node* Kernel::popCwn()
{
tod_assert(cwn_.size() > 0);
Node* node = cwn_.top();
cwn_.pop();
return node;
}
//-----------------------------------------------------------------------------
Node* Kernel::getCwn()
{
return cwn_.top();
}
//-----------------------------------------------------------------------------
void Kernel::addModule(Module* module)
{
if (0 == module)
return;
modules_.insert(Modules::value_type(module->getName(), module));
module->initialize();
initModuleOrder_.push_back(module);
}
//-----------------------------------------------------------------------------
Module* Kernel::findModule(const String& name)
{
Modules::iterator find_iter = modules_.find(name);
if (modules_.end() == find_iter)
return 0;
return find_iter->second;
}
//-----------------------------------------------------------------------------
Module* Kernel::findModuleByTypeName(const String& type_name) const
{
Types::const_iterator fi = types_.find(type_name);
if (types_.end() == fi)
return 0;
return fi->second;
}
//-----------------------------------------------------------------------------
void Kernel::addType(const String& type_name, Module* module)
{
// insert type names in module to Kernel::types_ for Object creation
types_.insert(Types::value_type(type_name, module));
}
//-----------------------------------------------------------------------------
const Type* Kernel::findType(const String& type_name) const
{
Module* module = findModuleByTypeName(type_name);
if (0 == module)
return 0;
return module->findType(type_name);
}
//-----------------------------------------------------------------------------
Node* Kernel::create_node(const String& type_name, const String& name)
{
Types::iterator find_iter = types_.find(type_name);
if (types_.end() == find_iter)
return 0;
Node* new_node = static_cast<Node*>(
find_iter->second->create(type_name));
if (0 == new_node)
return 0;
new_node->setName(name);
--new_node->refCount_;
return new_node;
}
| true |
35a0f15999721e6f448e3589530bcdb086612072 | C++ | gosu/gosu | /src/Image.cpp | UTF-8 | 4,584 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <Gosu/Bitmap.hpp>
#include <Gosu/Buffer.hpp>
#include <Gosu/Drawable.hpp>
#include <Gosu/Graphics.hpp>
#include <Gosu/Image.hpp>
#include <Gosu/Math.hpp>
#include "EmptyDrawable.hpp"
#include <stdexcept>
Gosu::Image::Image()
{
static const auto default_data_ptr = std::make_shared<EmptyDrawable>(0, 0);
m_drawable = default_data_ptr;
}
Gosu::Image::Image(const std::string& filename, unsigned image_flags)
: Image(load_image_file(filename), image_flags)
{
}
Gosu::Image::Image(const std::string& filename, const Rect& source_rect, unsigned image_flags)
: Image(load_image_file(filename), source_rect, image_flags)
{
}
Gosu::Image::Image(const Bitmap& source, unsigned image_flags)
: Image(source, Rect::covering(source), image_flags)
{
}
Gosu::Image::Image(const Bitmap& source, const Rect& source_rect, unsigned image_flags)
: m_drawable(create_drawable(source, source_rect, image_flags))
{
}
Gosu::Image::Image(std::unique_ptr<Drawable> data)
: m_drawable(std::move(data))
{
if (!m_drawable) {
throw std::invalid_argument("Gosu::Image cannot be initialized with nullptr");
}
}
unsigned Gosu::Image::width() const
{
return m_drawable->width();
}
unsigned Gosu::Image::height() const
{
return m_drawable->height();
}
void Gosu::Image::draw(double x, double y, ZPos z, double scale_x, double scale_y, Color c,
BlendMode mode) const
{
double x2 = x + width() * scale_x;
double y2 = y + height() * scale_y;
m_drawable->draw(x, y, c, x2, y, c, x, y2, c, x2, y2, c, z, mode);
}
void Gosu::Image::draw_mod(double x, double y, ZPos z, double scale_x, double scale_y, Color c1,
Color c2, Color c3, Color c4, BlendMode mode) const
{
double x2 = x + width() * scale_x;
double y2 = y + height() * scale_y;
m_drawable->draw(x, y, c1, x2, y, c2, x, y2, c3, x2, y2, c4, z, mode);
}
void Gosu::Image::draw_rot(double x, double y, ZPos z, double angle, double center_x,
double center_y, double scale_x, double scale_y, Color c,
BlendMode mode) const
{
double size_x = width() * scale_x;
double size_y = height() * scale_y;
double offs_x = offset_x(angle, 1);
double offs_y = offset_y(angle, 1);
// Offset to the centers of the original Image's edges after rotation.
double dist_to_left_x = +offs_y * size_x * center_x;
double dist_to_left_y = -offs_x * size_x * center_x;
double dist_to_right_x = -offs_y * size_x * (1 - center_x);
double dist_to_right_y = +offs_x * size_x * (1 - center_x);
double dist_to_top_x = +offs_x * size_y * center_y;
double dist_to_top_y = +offs_y * size_y * center_y;
double dist_to_bottom_x = -offs_x * size_y * (1 - center_y);
double dist_to_bottom_y = -offs_y * size_y * (1 - center_y);
m_drawable->draw( //
x + dist_to_left_x + dist_to_top_x, y + dist_to_left_y + dist_to_top_y, c,
x + dist_to_right_x + dist_to_top_x, y + dist_to_right_y + dist_to_top_y, c,
x + dist_to_left_x + dist_to_bottom_x, y + dist_to_left_y + dist_to_bottom_y, c,
x + dist_to_right_x + dist_to_bottom_x, y + dist_to_right_y + dist_to_bottom_y, c, //
z, mode);
}
Gosu::Drawable& Gosu::Image::drawable() const
{
return *m_drawable;
}
std::vector<Gosu::Image> Gosu::load_tiles(const Bitmap& bitmap, //
int tile_width, int tile_height, unsigned flags)
{
if (tile_width == 0 || tile_height == 0) {
throw std::invalid_argument("Gosu::load_tiles does not support empty tiles");
}
int tiles_x, tiles_y;
std::vector<Image> images;
if (tile_width > 0) {
tiles_x = bitmap.width() / tile_width;
}
else {
tiles_x = -tile_width;
tile_width = bitmap.width() / tiles_x;
}
if (tile_height > 0) {
tiles_y = bitmap.height() / tile_height;
}
else {
tiles_y = -tile_height;
tile_height = bitmap.height() / tiles_y;
}
for (int y = 0; y < tiles_y; ++y) {
for (int x = 0; x < tiles_x; ++x) {
images.emplace_back(
bitmap, Rect { x * tile_width, y * tile_height, tile_width, tile_height }, flags);
}
}
return images;
}
std::vector<Gosu::Image> Gosu::load_tiles(const std::string& filename, //
int tile_width, int tile_height, unsigned flags)
{
const Bitmap bitmap = load_image_file(filename);
return load_tiles(bitmap, tile_width, tile_height, flags);
}
| true |
2124d7fa71beb07516ac0b069cf4fb7475be81d0 | C++ | cdj68765/MetasqeExportPmx | /ExportPMX/MLibs/MString.cpp | UTF-8 | 24,919 | 2.921875 | 3 | [] | no_license | #ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#endif
#include "MString.h"
#include "stdio.h"
#include "stdlib.h"
#include "stdarg.h"
#include "memory.h"
#include "wchar.h"
#include <algorithm>
static wchar_t* null_str = L"";
inline bool isHighSurrogate(wchar_t ch)
{
return (ch >= 0xD800) && (ch <= 0xDBFF);
}
inline bool isLowSurrogate(wchar_t ch)
{
return (ch >= 0xDC00) && (ch <= 0xDFFF);
}
inline bool isSurrogatePair(const wchar_t* str)
{
return isHighSurrogate(str[0]) && isLowSurrogate(str[1]);
}
MString::MString()
{
mStr = null_str;
mLength = 0;
mCapacity = 0;
}
MString::MString(const wchar_t* str)
{
mStr = null_str;
mLength = 0;
mCapacity = 0;
*this = str;
}
MString::MString(const wchar_t* str, size_t length)
{
mStr = null_str;
mLength = 0;
mCapacity = 0;
append(str, length);
}
#ifndef MSTRING_DISABLE_STDSRING
MString::MString(const std::wstring& str)
{
mStr = null_str;
mLength = 0;
mCapacity = 0;
append(str.c_str(), str.length());
}
#endif
MString::MString(const MString& str)
{
mStr = null_str;
mLength = 0;
mCapacity = 0;
*this = str;
}
#if _MSC_VER >= 1600 || __BORLAND_C__ >= 0x0630
MString::MString(MString&& str)
{
mStr = str.mStr;
mLength = str.mLength;
mCapacity = str.mCapacity;
str.mStr = null_str;
str.mLength = 0;
str.mCapacity = 0;
}
#endif
MString::~MString()
{
if (mStr != null_str)
{
free(mStr);
}
}
// Get a number of characters with care of surrogage characters
size_t MString::count() const
{
size_t num = 0;
for (wchar_t* ptr = mStr; ptr < mStr + mLength;)
{
if (ptr + 2 <= mStr + mLength && isSurrogatePair(ptr))
{
num += 1;
ptr += 2;
}
else
{
num += 1;
ptr += 1;
}
}
return num;
}
// Get a pointer to the next character with care of surrogate
wchar_t* MString::next(wchar_t* ptr) const
{
assert(ptr >= mStr && ptr <= mStr + mLength);
if (ptr < mStr || ptr >= mStr + mLength)
{
return nullptr;
}
if (ptr + 2 <= mStr + mLength && isSurrogatePair(ptr))
{
return ptr + 2;
}
return ptr + 1;
}
const wchar_t* MString::next(const wchar_t* ptr) const
{
assert(ptr >= mStr && ptr <= mStr + mLength);
if (ptr < mStr || ptr >= mStr + mLength)
{
return nullptr;
}
if (ptr + 2 <= mStr + mLength && isSurrogatePair(ptr))
{
return ptr + 2;
}
return ptr + 1;
}
size_t MString::next(size_t pos) const
{
const wchar_t* ptr = next(mStr + pos);
return (ptr != nullptr) ? ptr - mStr : kInvalid;
}
// Get a pointer to the previous character with care of surrogate characters
wchar_t* MString::prev(wchar_t* ptr) const
{
assert(ptr >= mStr && ptr <= mStr + mLength);
if (ptr <= mStr || ptr > mStr + mLength)
{
return nullptr;
}
if (ptr >= mStr + 2 && isSurrogatePair(ptr - 2))
{
return ptr - 2;
}
return ptr - 1;
}
const wchar_t* MString::prev(const wchar_t* ptr) const
{
assert(ptr >= mStr && ptr <= mStr + mLength);
if (ptr <= mStr || ptr > mStr + mLength)
{
return nullptr;
}
if (ptr >= mStr + 2 && isSurrogatePair(ptr - 2))
{
return ptr - 2;
}
return ptr - 1;
}
size_t MString::prev(size_t pos) const
{
const wchar_t* ptr = prev(mStr + pos);
return (ptr != nullptr) ? ptr - mStr : kInvalid;
}
void MString::clear()
{
if (mStr != null_str)
{
free(mStr);
mStr = null_str;
}
mLength = 0;
mCapacity = 0;
}
bool MString::resize(size_t size)
{
if (size > 0 && size + 1 > mCapacity)
{
size_t new_cap = ((size + 1) + 3) & ~3;
if (mStr == null_str)
{
void* buf = malloc(sizeof(wchar_t) * new_cap);
if (buf == nullptr)
{
return false;
}
memset(buf, 0, sizeof(wchar_t) * new_cap);
mStr = (wchar_t*)buf;
}
else
{
void* buf = realloc(mStr, sizeof(wchar_t) * new_cap);
if (buf == nullptr)
{
return false;
}
memset((wchar_t*)buf + mCapacity, 0, sizeof(wchar_t) * (new_cap - mCapacity));
mStr = (wchar_t*)buf;
}
mCapacity = new_cap;
}
else if (size == 0)
{
clear();
}
mLength = size;
if (mStr != null_str)
{
mStr[mLength] = L'\0';
}
return true;
}
void MString::append(const wchar_t* str, size_t len)
{
if (str == nullptr)
{
return;
}
size_t len2 = wcsnlen(str, len);
if (len2 == 0)
{
return;
}
size_t len1 = length();
resize(len1 + len2);
memcpy_s(mStr + len1, sizeof(wchar_t) * (mCapacity - len1), str, sizeof(wchar_t) * len2);
mStr[len1 + len2] = L'\0';
}
MString MString::substring(size_t start) const
{
if (start >= mLength)
{
return MString();
}
return MString(mStr + start, mLength - start);
}
MString MString::substring(size_t start, size_t len) const
{
if (start >= mLength)
{
return MString();
}
size_t copy_len = std::min(mLength - start, len);
return MString(mStr + start, copy_len);
}
size_t MString::indexOf(const MString& str, size_t start) const
{
assert(start >= 0);
if (str.length() == 0) return kInvalid;
for (size_t i = (size_t)start; i < mLength; i++)
{
if (i + str.length() > mLength) break;
if (wcsncmp(&mStr[i], str.c_str(), str.length()) == 0)
{
return i;
}
}
return kInvalid;
}
size_t MString::indexOf(const wchar_t* str, size_t start) const
{
assert(start >= 0);
if (str == nullptr) return kInvalid;
size_t length = wcslen(str);
if (length == 0) return kInvalid;
for (size_t i = (size_t)start; i < mLength; i++)
{
if (i + length > mLength) break;
if (wcsncmp(&mStr[i], str, length) == 0)
{
return i;
}
}
return kInvalid;
}
size_t MString::indexOf(wchar_t character, size_t start) const
{
assert(start >= 0);
for (size_t i = (size_t)start; i < mLength; i++)
{
if (mStr[i] == character)
{
return i;
}
}
return kInvalid;
}
size_t MString::indexOf(const std::vector<wchar_t>& characters, size_t start) const
{
assert(start != kInvalid);
for (size_t i = (size_t)start; i < mLength; i++)
{
if (characters.end() != find(characters.begin(), characters.end(), mStr[i]))
{
return i;
}
}
return kInvalid;
}
size_t MString::lastIndexOf(const MString& str, size_t start) const
{
if (str.length() == 0) return kInvalid;
if (mLength < str.length()) return kInvalid;
if (start == kInvalid || start > mLength - str.length())
{
start = mLength - str.length();
}
for (size_t i = start; i >= 0; i--)
{
if (wcsncmp(&mStr[i], str.c_str(), str.length()) == 0)
{
return i;
}
if (i == 0) break;
}
return kInvalid;
}
size_t MString::lastIndexOf(wchar_t character, size_t start) const
{
if (mLength == 0) return kInvalid;
if (start == kInvalid || start >= mLength) start = mLength - 1;
for (size_t i = start; i >= 0; i--)
{
if (mStr[i] == character)
{
return i;
}
if (i == 0) break;
}
return kInvalid;
}
size_t MString::lastIndexOf(const std::vector<wchar_t>& characters, size_t start) const
{
if (mLength == 0) return kInvalid;
if (start == kInvalid || start >= mLength) start = mLength - 1;
for (size_t i = start; i >= 0; i--)
{
if (characters.end() != find(characters.begin(), characters.end(), mStr[i]))
{
return i;
}
if (i == 0) break;
}
return kInvalid;
}
std::vector<MString> MString::split(const MString& separator) const
{
std::vector<MString> ret;
size_t pos = 0;
while (true)
{
size_t next = indexOf(separator, pos);
if (next == kInvalid)
{
ret.push_back(substring(pos));
break;
}
ret.push_back(substring(pos, next - pos));
pos = next + separator.length();
}
return ret;
}
std::vector<MString> MString::split(wchar_t separator) const
{
std::vector<MString> ret;
size_t pos = 0;
while (true)
{
size_t next = indexOf(separator, pos);
if (next == kInvalid)
{
ret.push_back(substring(pos));
break;
}
ret.push_back(substring(pos, next - pos));
pos = next + 1;
}
return ret;
}
std::vector<MString> MString::split(const std::vector<wchar_t>& separators) const
{
std::vector<MString> ret;
size_t pos = 0;
while (true)
{
size_t next = indexOf(separators, pos);
if (next == kInvalid)
{
ret.push_back(substring(pos));
break;
}
ret.push_back(substring(pos, next - pos));
pos = next + 1;
}
return ret;
}
MString MString::combine(const std::vector<MString>& strings, const MString& separator)
{
MString ret;
for (size_t i = 0; i < strings.size(); i++)
{
if (i > 0) ret += separator;
ret += strings[i];
}
return ret;
}
MString MString::combine(const std::vector<MString>& strings, wchar_t separator)
{
MString ret;
for (size_t i = 0; i < strings.size(); i++)
{
if (i > 0) ret += separator;
ret += strings[i];
}
return ret;
}
MString MString::toLowerCase() const
{
size_t len = length();
MString ret;
ret.resize(len);
for (size_t i = 0; i < len; i++)
{
ret[i] = towlower(mStr[i]);
}
return ret;
}
MString MString::toUpperCase() const
{
size_t len = length();
MString ret;
ret.resize(len);
for (size_t i = 0; i < len; i++)
{
ret[i] = towupper(mStr[i]);
}
return ret;
}
MAnsiString MString::toAnsiString() const
{
if (length() == 0) return std::string();
int lenu = WideCharToMultiByte(CP_ACP, 0, mStr, -1, nullptr, 0, nullptr, nullptr);
char* stru = (char*)malloc(lenu + 1);
WideCharToMultiByte(CP_ACP, 0, mStr, -1, stru, lenu, nullptr, nullptr);
MAnsiString str(stru);
free(stru);
return str;
}
MAnsiString MString::toUtf8String() const
{
if (length() == 0) return std::string();
int lenu = WideCharToMultiByte(CP_UTF8, 0, mStr, -1, nullptr, 0, nullptr, nullptr);
char* stru = (char*)malloc(lenu + 1);
WideCharToMultiByte(CP_UTF8, 0, mStr, -1, stru, lenu, nullptr, nullptr);
MAnsiString str(stru);
free(stru);
return str;
}
template <typename T>
T parseRadix16(const wchar_t* ptr, const wchar_t* end_ptr)
{
T val = 0;
for (; ptr < end_ptr; ptr++)
{
if (*ptr >= L'0' && *ptr <= '9')
{
val = (val << 4) | (*ptr - L'0');
}
else if (*ptr >= L'A' && *ptr <= 'F')
{
val = (val << 4) | (*ptr - L'A' + 10);
}
else if (*ptr >= L'a' && *ptr <= 'f')
{
val = (val << 4) | (*ptr - L'a' + 10);
}
else
{
break;
}
}
return val;
}
int MString::toInt() const
{
// 0x** is treated as 16 radix number
if (mLength >= 3 && mStr[0] == L'0' && (mStr[1] == L'x' || mStr[1] == L'X'))
{
return parseRadix16<int>(mStr + 2, mStr + mLength);
}
return _wtoi(mStr);
}
int MString::toIntWithRadix(int base) const
{
return wcstol(mStr, nullptr, base);
}
unsigned int MString::toUInt() const
{
// 0x** is treated as 16 radix number
if (mLength >= 3 && mStr[0] == L'0' && (mStr[1] == L'x' || mStr[1] == L'X'))
{
return parseRadix16<unsigned int>(mStr + 2, mStr + mLength);
}
__int64 val = std::max((__int64)0, std::min(_wtoi64(mStr), (__int64)UINT_MAX));
return (unsigned int)val;
}
unsigned int MString::toUIntWithRadix(int base) const
{
return wcstoul(mStr, nullptr, base);
}
__int64 MString::toInt64() const
{
// 0x** is treated as 16 radix number
if (mLength >= 3 && mStr[0] == L'0' && (mStr[1] == L'x' || mStr[1] == L'X'))
{
return parseRadix16<__int64>(mStr + 2, mStr + mLength);
}
return _wtoi64(mStr);
}
__int64 MString::toInt64WithRadix(int base) const
{
return _wcstoi64(mStr, nullptr, base);
}
unsigned __int64 MString::toUInt64() const
{
// 0x** is treated as 16 radix number
if (mLength >= 3 && mStr[0] == L'0' && (mStr[1] == L'x' || mStr[1] == L'X'))
{
return parseRadix16<unsigned __int64>(mStr + 2, mStr + mLength);
}
return _wtoi64(mStr);
}
unsigned __int64 MString::toUInt64WithRadix(int base) const
{
return _wcstoui64(mStr, nullptr, base);
}
float MString::toFloat(void) const
{
double val = wcstod(mStr, nullptr);
return (float)val;
}
double MString::toDouble(void) const
{
double val = wcstod(mStr, nullptr);
return val;
}
bool MString::canParseInt() const
{
wchar_t* endptr;
wcstol(mStr, &endptr, 10);
return (endptr == nullptr) || (endptr == mStr + mLength);
}
bool MString::canParseFloat() const
{
wchar_t* endptr;
wcstod(mStr, &endptr);
return (endptr == nullptr) || (endptr == mStr + mLength);
}
bool MString::canParseDouble() const
{
wchar_t* endptr;
wcstod(mStr, &endptr);
return (endptr == nullptr) || (endptr == mStr + mLength);
}
MString MString::fromCharacter(wchar_t character)
{
wchar_t str[2];
str[0] = character;
str[1] = L'\0';
return MString(str);
}
MString MString::fromAnsiString(const char* str)
{
if (str == nullptr) return MString();
int lenw = MultiByteToWideChar(CP_ACP, 0, str, -1, nullptr, 0);
wchar_t* strw = (wchar_t*)malloc(sizeof(wchar_t) * (lenw + 1));
MultiByteToWideChar(CP_ACP, 0, str, -1, strw, lenw);
MString ret(strw);
free(strw);
return ret;
}
MString MString::fromUtf8String(const char* str)
{
if (str == nullptr) return MString();
int lenw = MultiByteToWideChar(CP_UTF8, 0, str, -1, nullptr, 0);
wchar_t* strw = (wchar_t*)malloc(sizeof(wchar_t) * (lenw + 1));
MultiByteToWideChar(CP_UTF8, 0, str, -1, strw, lenw);
MString ret(strw);
free(strw);
return ret;
}
MString MString::fromInt(int value, int radix)
{
wchar_t buf[30];
#if _MSC_VER >= 1400 || __BORLAND_C__ >= 0x0630
errno_t ret = _itow_s(value, buf, _countof(buf), radix);
if (ret != 0)
{
return MString();
}
return MString(buf);
#else
_itow(value, buf, radix);
return MString(buf);
#endif
}
MString MString::fromUInt(unsigned int value, int radix)
{
wchar_t buf[30];
#if _MSC_VER >= 1400 || __BORLAND_C__ >= 0x0630
errno_t ret = _ultow_s(value, buf, _countof(buf), radix);
if (ret != 0)
{
return MString();
}
#else
_ultow(value, buf, radix);
#endif
return MString(buf);
}
MString MString::fromInt64(__int64 value, int radix)
{
wchar_t buf[30];
#if _MSC_VER >= 1400 || __BORLAND_C__ >= 0x0630
errno_t ret = _i64tow_s(value, buf, _countof(buf), radix);
if (ret != 0)
{
return MString();
}
#else
_i64tow(value, buf, radix);
#endif
return MString(buf);
}
MString MString::fromUInt64(unsigned __int64 value, int radix)
{
wchar_t buf[30];
#if _MSC_VER >= 1400 || __BORLAND_C__ >= 0x0630
errno_t ret = _ui64tow_s(value, buf, _countof(buf), radix);
if (ret != 0)
{
return MString();
}
#else
_ui64tow(value, buf, radix);
#endif
return MString(buf);
}
// Convert from float value
MString MString::fromFloat(float value, int digit, int max_digit)
{
float absval = fabs(value);
int d = (absval > 0) ? (int)floor(log10(absval)) : 0;
MString format = MString::format(L"%%0.%df", std::min(std::max(0, digit - d - 1), max_digit));
return MString::format(format.c_str(), value);
}
// Convert from double value
MString MString::fromDouble(double value, int digit, int max_digit)
{
double absval = fabs(value);
int d = (absval > 0) ? (int)floor(log10(absval)) : 0;
MString format = MString::format(L"%%0.%dlf", std::min(std::max(0, digit - d - 1), max_digit));
return MString::format(format.c_str(), value);
}
// Check if is numberic string
bool MString::isNumber() const
{
bool sign = false;
bool number = false;
bool period = false;
bool exponent = false;
bool hex = false;
for (const wchar_t* ptr = mStr; ptr < mStr + mLength; ptr = next(ptr))
{
switch (*ptr)
{
case '-':
case '+':
if (number || period || sign || hex)
{
return false;
}
sign = true;
break;
case '.':
if (period || exponent || hex)
{
return false;
}
period = true;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
number = true;
break;
case 'e':
case 'E':
if (!hex)
{
if (!number || exponent)
{
return false;
}
exponent = true;
number = false;
period = false;
sign = false;
}
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'F':
if (!hex) return false;
number = true;
break;
case 'x':
case 'X':
if (hex) return false;
if (ptr == mStr) return false;
if (*(ptr - 1) != '0') return false;
if (ptr - 2 == mStr && (*(ptr - 2) != L'+' && *(ptr - 2) != L'-')) return false;
if (ptr - 3 >= mStr) return false;
hex = true;
break;
default:
return false;
}
}
return number;
}
// Trim 0 for numeric string
bool MString::trimNumber()
{
if (!isNumber()) return false;
bool trimmed = false;
// Remove end 0
size_t period = lastIndexOf('.');
if (period != kInvalid)
{
int zero_count = 0;
size_t pos = mLength - 1;
for (; pos > period; pos--)
{
if (mStr[pos] == 'E' || mStr[pos] == 'e')
{
zero_count = 0;
break;
}
if (mStr[pos] >= '1' && mStr[pos] <= '9')
{
break;
}
if (mStr[pos] != '0')
{
zero_count = 0;
break;
}
zero_count++;
}
if (pos == period)
{
resize(pos);
trimmed = true;
}
else if (zero_count > 0)
{
resize(mLength - zero_count);
trimmed = true;
}
}
// Remove header '+'
if (mLength > 0 && mStr[0] == L'+')
{
*this = substring(1);
trimmed = true;
}
return trimmed;
}
MString MString::getTrimDecimalZero() const
{
size_t pos = mLength;
bool other = false;
for (size_t i = mLength; ;)
{
i = prev(i);
if (i == kInvalid) break;
if (mStr[i] == L'.')
{
if (other)
{
return substring(0, pos);
}
return substring(0, i);
}
if (mStr[i] == L'0')
{
if (!other)
{
pos = i;
}
}
else if (mStr[i] >= L'1' && mStr[i] <= L'9')
{
other = true;
}
else
{
break;
}
}
return *this;
}
MString MString::getTrimSpace() const
{
if (mLength == 0) return MString();
size_t pre_pos = mLength;
for (size_t i = 0; i < mLength && i != kInvalid; i = next(i))
{
if (!(mStr[i] == L' ' || mStr[i] == L'\t'))
{
pre_pos = i;
break;
}
}
size_t pst_pos = pre_pos;
for (size_t n = mLength; n > pre_pos && n != kInvalid;)
{
size_t i = prev(n);
if (i != kInvalid && !(mStr[i] == L' ' || mStr[i] == L'\t'))
{
pst_pos = n;
break;
}
n = i;
}
return substring(pre_pos, pst_pos - pre_pos);
}
MString MString::format(const wchar_t* format, ...)
{
va_list argp;
va_start(argp, format);
#if _MSC_VER >= 1400
int num = _vscwprintf(format, argp);
if (num <= 0)
{
va_end(argp);
return MString();
}
MString ret;
ret.resize(num);
num = vswprintf_s(ret.c_str(), ret.capacity(), format, argp);
if (num < 0)
{
va_end(argp);
return MString();
}
va_end(argp);
return ret;
#else
wchar_t *temp = NULL;
int num = 0;
for (size_t temp_len = 1024; temp_len < 1024 * 1024; temp_len *= 4) {
temp = (wchar_t*)malloc(sizeof(wchar_t)*temp_len);
if (temp == NULL) {
va_end(argp);
return MString();
}
num = _vsnwprintf(temp, temp_len, format, argp);
if (num >= 0) {
break;
}
free(temp);
temp = NULL;
}
if (num <= 0) {
free(temp);
va_end(argp);
return MString();
}
MString ret;
ret.resize(num);
memcpy_s(ret.c_str(), sizeof(wchar_t)*ret.mCapacity, temp, sizeof(wchar_t)*(num + 1));
free(temp);
va_end(argp);
return ret;
#endif
}
int MString::formatSet(const wchar_t* format, ...)
{
va_list argp;
va_start(argp, format);
#if _MSC_VER >= 1400
int num = _vscwprintf(format, argp);
if (num <= 0)
{
va_end(argp);
return num;
}
resize(num);
num = vswprintf_s(c_str(), capacity(), format, argp);
va_end(argp);
return num;
#else
wchar_t *temp = NULL;
int num = 0;
for (size_t temp_len = 1024; temp_len < 1024 * 1024; temp_len *= 4) {
temp = (wchar_t*)malloc(sizeof(wchar_t)*temp_len);
if (temp == NULL) {
va_end(argp);
return -1;
}
num = _vsnwprintf(temp, temp_len, format, argp);
if (num >= 0) {
break;
}
free(temp);
temp = NULL;
}
if (num <= 0) {
free(temp);
va_end(argp);
return num;
}
resize(num);
memcpy_s(c_str(), sizeof(wchar_t)*mCapacity, temp, sizeof(wchar_t)*(num + 1));
free(temp);
va_end(argp);
return num;
#endif
}
int MString::compare(const MString& str) const
{
return wcsncmp(mStr, str.c_str(), std::max(mLength, str.length()));
}
int MString::compareIgnoreCase(const MString& str) const
{
return _wcsnicmp(mStr, str.c_str(), std::max(mLength, str.length()));
}
int MString::compareSubstring(size_t start, const MString& str) const
{
return wcsncmp(mStr + start, str.c_str(), str.length());
}
int MString::compareSubstringIgnoreCase(size_t start, const MString& str) const
{
return _wcsnicmp(mStr + start, str.c_str(), str.length());
}
MString& MString::operator =(const MString& str)
{
if (mStr == str.c_str())
{
return *this;
}
size_t len = str.length();
if (len == 0)
{
clear();
}
else
{
resize(len);
memcpy_s(mStr, sizeof(wchar_t) * mCapacity, str.c_str(), sizeof(wchar_t) * len);
mStr[len] = L'\0';
}
return *this;
}
MString& MString::operator =(const wchar_t* str)
{
if (mStr == str)
{
return *this;
}
size_t len = (str != nullptr) ? wcslen(str) : 0;
if (len == 0)
{
clear();
}
else
{
resize(len);
memcpy_s(mStr, sizeof(wchar_t) * mCapacity, str, sizeof(wchar_t) * len);
mStr[len] = L'\0';
}
return *this;
}
#ifndef MSTRING_DISABLE_STDSRING
MString& MString::operator =(const std::wstring& str)
{
if (mStr == str.c_str())
{
return *this;
}
size_t len = str.length();
if (len == 0)
{
clear();
}
else
{
resize(len);
memcpy_s(mStr, sizeof(wchar_t) * mCapacity, str.c_str(), sizeof(wchar_t) * len);
mStr[len] = L'\0';
}
return *this;
}
#endif
#if _MSC_VER >= 1600 || __BORLAND_C__ >= 0x0630
MString& MString::operator =(MString&& str)
{
if (mStr == str.c_str())
{
return *this;
}
if (mStr != null_str)
{
free(mStr);
}
mStr = str.mStr;
mLength = str.mLength;
mCapacity = str.mCapacity;
str.mStr = null_str;
str.mLength = 0;
str.mCapacity = 0;
return *this;
}
#endif
MString& MString::operator +=(const MString& str)
{
size_t len2 = str.length();
if (len2 == 0)
{
return *this;
}
size_t len1 = length();
resize(len1 + len2);
memcpy_s(mStr + len1, sizeof(wchar_t) * (mCapacity - len1), str.c_str(), sizeof(wchar_t) * len2);
mStr[len1 + len2] = L'\0';
return *this;
}
MString& MString::operator +=(const wchar_t* str)
{
size_t len2 = (str != nullptr) ? wcslen(str) : 0;
if (len2 == 0)
{
return *this;
}
size_t len1 = length();
resize(len1 + len2);
memcpy_s(mStr + len1, sizeof(wchar_t) * (mCapacity - len1), str, sizeof(wchar_t) * len2);
mStr[len1 + len2] = L'\0';
return *this;
}
MString& MString::operator +=(wchar_t character)
{
size_t len1 = length();
resize(len1 + 1);
mStr[len1] = character;
mStr[len1 + 1] = L'\0';
return *this;
}
MString MString::operator +(const MString& str) const
{
MString ret(*this);
ret += str;
return ret;
}
MString MString::operator +(const wchar_t* str) const
{
MString ret(*this);
ret += str;
return ret;
}
MString MString::operator +(wchar_t character) const
{
MString ret(*this);
ret += character;
return ret;
}
#if _MSC_VER >= 1600 || __BORLAND_C__ >= 0x0630
MString operator +(MString&& str1, const MString& str2)
{
str1 += str2;
return std::move(str1);
}
MString operator +(MString&& str1, const wchar_t* str2)
{
str1 += str2;
return std::move(str1);
}
#endif
MString operator +(const wchar_t* str1, const MString& str2)
{
MString ret(str1);
ret += str2;
return ret;
}
bool MString::operator ==(const MString& str) const
{
if (length() != str.length()) return false;
return (wmemcmp(mStr, str.c_str(), length()) == 0);
}
bool MString::operator ==(const wchar_t* str) const
{
size_t len = (str != nullptr) ? wcslen(str) : 0;
if (length() != len) return false;
return (wmemcmp(mStr, str, length()) == 0);
}
#ifndef MSTRING_DISABLE_STDSRING
bool MString::operator ==(const std::wstring& str) const
{
size_t len = str.length();
if (length() != len) return false;
return (wmemcmp(mStr, str.c_str(), length()) == 0);
}
#endif
bool operator ==(const wchar_t* str1, const MString& str2)
{
size_t len = (str1 != nullptr) ? wcslen(str1) : 0;
if (len != str2.length()) return false;
return (wmemcmp(str1, str2.c_str(), len) == 0);
}
#ifndef MSTRING_DISABLE_STDSRING
bool operator ==(const std::wstring& str1, const MString& str2)
{
size_t len = str1.length();
if (len != str2.length()) return false;
return (wmemcmp(str1.c_str(), str2.c_str(), len) == 0);
}
#endif
bool MString::operator !=(const MString& str) const
{
if (length() != str.length()) return true;
return (wmemcmp(mStr, str.c_str(), length()) != 0);
}
bool MString::operator !=(const wchar_t* str) const
{
size_t len = (str != nullptr) ? wcslen(str) : 0;
if (length() != len) return true;
return (wmemcmp(mStr, str, length()) != 0);
}
#ifndef MSTRING_DISABLE_STDSRING
bool MString::operator !=(const std::wstring& str) const
{
size_t len = str.length();
if (length() != len) return false;
return (wmemcmp(mStr, str.c_str(), length()) != 0);
}
#endif
bool operator !=(const wchar_t* str1, const MString& str2)
{
size_t len = (str1 != nullptr) ? wcslen(str1) : 0;
if (len != str2.length()) return false;
return (wmemcmp(str1, str2.c_str(), len) != 0);
}
#ifndef MSTRING_DISABLE_STDSRING
bool operator !=(const std::wstring& str1, const MString& str2)
{
size_t len = str1.length();
if (len != str2.length()) return false;
return (wmemcmp(str1.c_str(), str2.c_str(), len) != 0);
}
#endif
| true |
112664a4532178202ed9ad6ad4cc9bc1d9e1808a | C++ | DerfOh/School-Programming-Projects | /C++/C++ Programming-II/Assignments/Assignment5/Solution/q4/main_driver.cpp | UTF-8 | 1,311 | 3.59375 | 4 | [] | no_license | // ****************************************************************
// main.cpp
//
// Test file to try out the User and Administrator classes.
// ****************************************************************
// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
#include <iostream>
#include <string>
#include "user.h"
#include "administrator.h"
using namespace std;
// Main method
int main()
{
// Hard-coded tests. Abbott has User access, Costello has
// user and admin access.
//
User user1("abbott","monday"),
user2("lynn","guini"),
user3("costello","tuesday");
Administrator admin1("abbott","monday"),
admin2("kerry","oki"),
admin3("costello","tuesday");
cout << "Results of login:" << endl;
cout << "User login for abbott: " << user1.Login() << endl;
cout << "User login for lynn: " << user2.Login() << endl;
cout << "User login for costello: " << user3.Login() << endl;
cout << "Admin login for abbott: " << admin1.Login() << endl;
cout << "Admin login for lynn: " << admin2.Login() << endl;
cout << "Admin login for costello: " << admin3.Login() << endl;
return 0;
}
// --------------------------------
// --------- END USER CODE --------
// --------------------------------
| true |
29555b410f2319bffc339a963ead0cc171574a6f | C++ | eliaslawrence/uvrp-brkga | /UVRP/ProblemInstance.cpp | UTF-8 | 6,983 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cassert>
#include <cmath>
#include <limits>
#include <algorithm>
#include <iomanip>
#include "ProblemInstance.h"
#ifndef NDEBUG
#define PI_DEBUG 1 //uncomment to switch to debug mode
#endif
#ifdef PI_DEBUG
#define DEBUG
#else
#define DEBUG while(false)
#endif
using namespace UVRP;
ProblemInstance::ProblemInstance(int _seed, std::string _directoryName) : seed (_seed), directory_name (_directoryName), pseudorandom_engine(_seed){
struct Point{
float x, y;
};
std::ifstream matrixFile;
std::string matrixFileName = directory_name + "matrix.txt";
matrixFile.open(matrixFileName);
setOriginPoint(directory_name + "origin.txt");
if ( matrixFile ){
file_name = matrixFileName;
setGraph();
} else {
std::ifstream gridFile(file_name.c_str());
assert(gridFile);
std::string temp;
std::getline(gridFile, temp); // Names
std::getline(gridFile, temp); // Comment
std::getline(gridFile, temp); // Type
gridFile >> temp; //Dimension
gridFile >> temp; // :
int maxX = std::numeric_limits<int>::min(), minX = std::numeric_limits<int>::max(),
maxY = std::numeric_limits<int>::min(), minY = std::numeric_limits<int>::max();
gridFile >> c; //Dimension
std::getline(gridFile, temp);
std::getline(gridFile, temp); // Edge Type
std::getline(gridFile, temp); // Name Coord
//Clients
std::vector<Point> c_loc;
for(int i = 0; i < c; ++i){
int h_id;
Point pnt;
gridFile >> h_id;
gridFile >> pnt.x;
gridFile >> pnt.y;
c_loc.emplace_back(std::move(pnt));
if(pnt.x > maxX){
maxX = pnt.x;
}
if(pnt.x < minX){
minX = pnt.x;
}
if(pnt.y > maxY){
maxY = pnt.y;
}
if(pnt.y < minY){
minY = pnt.y;
}
}
gridFile.close();
col = maxX - minX + 1;
lines = maxY - minY + 1;
//do the graph
grid.resize(lines);
for_each(grid.begin(), grid.end(), [this](std::vector<unsigned> &a){ a.resize(col); std::fill(a.begin(), a.end(), 0); });
for(auto& client : c_loc){
client.x -= minX;
client.y -= minY;
grid[client.y][client.x] = UVRP::POINTS::DELIVER;
clients.emplace_back(std::make_pair(client.x, client.y));
specialPoints.emplace_back(std::make_pair(client.x, client.y));
}
assert(c < UVRP::MAX_NODES); //if its bigger then you should reimplement the representation
int qty_charge = 0, //1 - Variables that will be incremented as the stopping points are instantiated
qty_prohibited = 0,
random_x = 0, //2 - Temporary variable that receives a random value along the loop
random_y = 0,
map_size = col * lines,
total_points = map_size - c; // 3 - Qty of points in the map
r = (unsigned) (pRecharge * total_points);
p = (unsigned) (pProhibited * total_points);
//Recharge
while (qty_charge != r){
random_x = rand() % col;
random_y = rand() % lines;
if (grid[random_y][random_x] == POINTS::NOTHING) {
grid[random_y][random_x] = POINTS::RECHARGE;
specialPoints.emplace_back(std::make_pair(random_x, random_y));
qty_charge++;
}
}
//Prohibited
while (qty_prohibited != p){
random_x = rand() % col;
random_y = rand() % lines;
if ((grid[random_y][random_x] == POINTS::NOTHING) &&
(random_x != origin_x || random_y != origin_y)) {
grid[random_y][random_x] = POINTS::PROHIBITED;
qty_prohibited++;
prohibited.emplace_back(std::make_pair(random_x, random_y));
}
}
std::ofstream gridFileOUT;
gridFileOUT.open("/home/elias/Documents/Mestrado/Projeto/instances/matrix.txt");
for (int j = 0; j < grid.size(); ++j) {
for (int i = 0; i < grid[j].size(); ++i) {
gridFileOUT << grid[j][i] << " ";
}
gridFileOUT << '\n';
}
gridFileOUT.close();
}
// c = max_c;
}
void ProblemInstance::setGraph() {
std::ifstream inGRAPH1(file_name.c_str());
assert(inGRAPH1);
std::string temp;
std::getline(inGRAPH1, temp); // Line
temp.erase (std::remove(temp.begin(), temp.end(), ' '), temp.end());
col = temp.length();
lines = 0;
do{
lines++;
} while(std::getline(inGRAPH1, temp));
inGRAPH1.close();
//Initializing the array that represents the map
grid.resize(lines);
for_each(grid.begin(), grid.end(), [this](std::vector<unsigned> &a){ a.resize(col); std::fill(a.begin(), a.end(), 0); });
std::ifstream inGRAPH2(file_name.c_str());
int x = 0;
c = 0;
r = 0;
p = 0;
// Inicializa Matriz
for ( int i = 0; i < grid.size(); i++ ) {
for ( int j = 0; j < grid[i].size(); j++ ) {
inGRAPH2 >> x;
grid[i][j] = x;
switch (x) {
case POINTS::DELIVER:
c++;
clients.emplace_back(std::make_pair(j, i));
specialPoints.emplace_back(std::make_pair(j, i));
break;
case POINTS::COLLECT:
c++;
clients.emplace_back(std::make_pair(j, i));
specialPoints.emplace_back(std::make_pair(j, i));
break;
case POINTS::RECHARGE:
r++;
specialPoints.emplace_back(std::make_pair(j, i));
break;
case POINTS::PROHIBITED:
p++;
prohibited.emplace_back(std::make_pair(j, i));
break;
}
}
}
inGRAPH2.close();
}
void ProblemInstance::setOriginPoint(std::string originFileName) /* set origin point of the drones */
{
std::ifstream originFile(originFileName.c_str());
if ( originFile ){
originFile >> origin_x;
originFile >> origin_y;
originFile.close();
}
}
std::ostream& UVRP::operator<<(std::ostream& os, const ProblemInstance& pi){
DEBUG os << "Number of clients/recharge/prohibited";
os << pi.c << " " << pi.r << " " << pi.p << std::endl;
DEBUG os << "Vehicles: ";
os << pi.v << std::endl;
os << std::endl;
DEBUG os << "Map: " << std::endl;
for(auto& i : pi.grid){
for(auto& j : i){
os << j << " ";
// os << std::fixed << std::setprecision(3) << j << "\t";
}
os << std::endl;
}
DEBUG os << "Seed: ";
os << pi.seed << std::endl;
return os;
}
| true |
cf430681bc0e2445a67b2a9204f5eb2daef442f9 | C++ | Xamla/torch-ros | /src/std/string_vector.cpp | UTF-8 | 1,534 | 3.03125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "torch-std.h"
STDIMP(StringVector *, StringVector, new)() {
return new StringVector();
}
STDIMP(StringVector *, StringVector, clone)(StringVector *self) {
return new StringVector(*self);
}
STDIMP(void, StringVector, delete)(StringVector *ptr) {
delete ptr;
}
STDIMP(int, StringVector, size)(StringVector *self) {
return static_cast<int>(self->size());
}
STDIMP(const char*, StringVector, getAt)(StringVector *self, size_t pos) {
StringVector& v = *self;
return v[pos].c_str();
}
STDIMP(void, StringVector, setAt)(StringVector *self, size_t pos, const char *value) {
StringVector& v = *self;
v[pos] = value;
}
STDIMP(void, StringVector, push_back)(StringVector *self, const char *value) {
self->push_back(value);
}
STDIMP(void, StringVector, pop_back)(StringVector *self) {
self->pop_back();
}
STDIMP(void, StringVector, clear)(StringVector *self) {
self->clear();
}
STDIMP(void, StringVector, insert)(StringVector *self, size_t pos, size_t n, const char *value) {
StringVector& v = *self;
StringVector::iterator i = pos >= v.size() ? v.end() : v.begin() + pos;
v.insert(i, n, value);
}
STDIMP(void, StringVector, erase)(StringVector *self, size_t begin, size_t end) {
if (begin >= end)
return;
StringVector& v = *self;
StringVector::iterator b = begin >= v.size() ? v.end() : v.begin() + begin;
StringVector::iterator e = end >= v.size() ? v.end() : v.begin() + end;
v.erase(b, e);
}
STDIMP(bool, StringVector, empty)(StringVector *self) {
return self->empty();
}
| true |
9b766aacfc90c147b5862ad5f60e8912544d77c5 | C++ | yu-cao/AlgorithmExercise | /LeetCode/Algorithm/Plus One.cpp | UTF-8 | 1,028 | 3.578125 | 4 | [] | no_license | #include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
static vector<int> plusOne(vector<int>& digits) {
int length=digits.size();
digits[length-1]++;
if(digits[length-1]==10){
for(int i=digits.size()-1;i>=0;i--){
if(digits[i]==10){
if(i==0){
digits[i]=0;
vector<int> res ={1};
for(int i=0;i<digits.size();i++){
res.push_back(digits[i]);
}
return res;
}
else
digits[i-1]++;
digits[i]=0;
}
}
}
return digits;
}
};
int main(void)
{
vector<int> digits = {9,9};
vector<int> hello;
hello=Solution::plusOne(digits);
for(int i=0;i<hello.size();i++){
cout<<hello[i]<<endl;
}
return 0;
}
//give an array and plus one | true |
9302a1a13b00e2e982a45a0e057465e53310674b | C++ | weisensee/PinochleGame | /Desktop Server/cardGame.cpp | UTF-8 | 20,659 | 3.078125 | 3 | [] | no_license | /* Live Game Manager -- Pinochle Game
Desktop Application
Lucas Weisensee
November 2014
This program will function as a pinochle game manager. It will:
-manage connections to all current players and observers
-keep track of the current game
-keep track of the current round
-enforce turn rules/turn order
-quit and save game when finished
// Data
int MAXOBSERVERS, MAXPLAYERS, GAMEID, GOAL; // Maximum Observers and players, game's unique id, winning goal
int * SCORES;
std::string * gameName;
Client ** PLAYERS;
Client ** OBSERVERS;
bool gameOver;
char gType;
char STATUS; // Game's current status, 'W': waiting 'R': ready to play 'P':playing 'B':bored
LogFile * gLog; // Game's log file
*/
#include "CardGame.h" //exception library
//****************************************************************************
// ::CONSTRUCTORS AND INITIALIZERS::
//****************************************************************************
CardGame::CardGame() {
}
CardGame::CardGame(GameSettings toMake):gamePlayer(toMake) { // constructs an active game loading settings from the game settings file passed in
// Setup Game
// Initiate log file
//gLog = new LogFile("game log file_", "C:\\Users\\Pookey\\OneDrive\\Projects\\PinochleGame\\logs\\games");
infoStringDirty = true;
PLAYERS = new Client*[MAXPLAYERS];
OBSERVERS = new Client*[MAXOBSERVERS];
// set score board
SCORES = new int[MAXPLAYERS / 2];
for (int i = 0; i < MAXPLAYERS / 2; i++)
SCORES[i] = 0;
gameOver = false;
totalObservers = 0;
totalPlayers = 0;
// set player and observer pointers to NULL
for (int i = 0; i < MAXPLAYERS; i++)
PLAYERS[i] = NULL;
for (int i = 0; i < MAXOBSERVERS; i++)
OBSERVERS[i] = NULL;
// Initialize Critical Section Locks
if (!InitializeCriticalSectionAndSpinCount(&playerCountLock, 0x00000400) ||/* Check for any errors that might occur*/
!InitializeCriticalSectionAndSpinCount(&newPlayerListLock, 0x00000400)) {
perror("\nMutex Initiation error: "); // report errors if any
exit(0);
}
DEBUG_IF(true)
printf("Setting up %s a game of: %c for %i players and %i observers. The winning score will be: %i.", gameName.c_str(), gType, MAXPLAYERS, MAXOBSERVERS, GOAL);
// Add player 1 to the game
addPlayer(player1, 0);
}
CardGame::~CardGame() { // destructor
// release critical sections
DeleteCriticalSection(&StaticDataLock);
DeleteCriticalSection(&newPlayerListLock);
// release arrays of players and Observers
if (PLAYERS)
delete[] PLAYERS;
if (OBSERVERS)
delete[] OBSERVERS;
//// delete log object
//delete gLog;
}
//****************************************************************************
// ::SERVER COMMUNICATOR FUNCTIONS::
//****************************************************************************
std::string CardGame::getInfoString() { //returns game information as string
std::string temp;
// if the info string is out of date, rebuild it
if (infoStringDirty) {
// Request ownership of StaticDataLock critical section.
EnterCriticalSection(&StaticDataLock);
infoString = *settingsString();
infoStringDirty = false;
// Release ownership of StaticDataLock critical section.
LeaveCriticalSection(&StaticDataLock);
}
// copy the info string
temp = infoString;
// Return info string
return temp;
}
//void CardGame::buildInfoString() { // rebuilds and sets the game info string, function must take place within critical sections to avoid race conditions
// // Request ownership of appropriate critical sections before copying them to send
// EnterCriticalSection(&statusLock);
// char tStatus = STATUS;
// LeaveCriticalSection(&statusLock);
//
// EnterCriticalSection(&gameIdLock);
// int tID = GAMEID;
// LeaveCriticalSection(&gameIdLock);
//
// EnterCriticalSection(&infoStrLock);
// std::string tName = gameName;
// LeaveCriticalSection(&infoStrLock);
//
//
// // set new info string
// infoString = tStatus;
// infoString += '^';
// infoString.append(std::to_string(tID));
// infoString += '^';
// infoString.append(tName);
// infoString += '^';
// infoString.append(PLAYERS[0]->getName());
//
// //append other player names if available
// if (totalPlayers > 1)
// for (int i = 1; i < totalPlayers; ++i)
// infoString.append('^' + PLAYERS[i]->getName());
//}
void CardGame::setGameID(int newId) { // sets/updates the current game's gameID
EnterCriticalSection(&StaticDataLock);
infoStringDirty = true;
GAMEID = newId; // read value
// Release ownership of StaticDataLock critical section.
LeaveCriticalSection(&StaticDataLock);
}
int CardGame::getGameID() { // Returns game ID
//// Request ownership of StaticDataLock critical section.
//EnterCriticalSection(&StaticDataLock);
int ID = GAMEID; // read value
//// Release ownership of StaticDataLock critical section.
//LeaveCriticalSection(&StaticDataLock);
return ID;
}
int CardGame::playerCount() { // returns current total players
return totalPlayers;
}
bool CardGame::connectClient(Client * toAdd) { // adds new Client to list of Clients to add to game
// Request ownership of newPlayerListLock critical section.
EnterCriticalSection(&newPlayerListLock);
// add new player to list
newPlayers.push(toAdd);
// Release ownership of newPlayerListLock critical section.
LeaveCriticalSection(&newPlayerListLock);
// signal Client updates
signalDataUpdate();
return true;
}
//****************************************************************************
// ::GAME SETUP::
//****************************************************************************
bool CardGame::addPlayer(Client * newPlayer, int n) { //checks on and adds any new players
// give player the newMessage event handle
if (dataUpdate)
newPlayer->setUpdateEvent(dataUpdate);
else
printf("\ncreate event error in CardGame");
// check that no player occupies desired spot n
if (PLAYERS[n] != NULL)
return makePlayer(newPlayer);
// if the spot is unoccupied
PLAYERS[n] = newPlayer;
incrementPlayerCount();
return true;
}
void CardGame::decrementPlayerCount() { // decreases the player count by one
// Request ownership of playerCountLock critical section.
EnterCriticalSection(&playerCountLock);
totalPlayers--;
infoStringDirty = true;
// Release ownership of playerCountLock critical section.
LeaveCriticalSection(&playerCountLock);
}
void CardGame::incrementPlayerCount() { // increases the player count by one
// Request ownership of playerCountLock critical section.
EnterCriticalSection(&playerCountLock);
totalPlayers++;
// Release ownership of playerCountLock critical section.
LeaveCriticalSection(&playerCountLock);
}
void CardGame::decrementObserverCount() { // decreases the player count by one
// Request ownership of playerCountLock critical section.
EnterCriticalSection(&playerCountLock);
totalObservers--;
// Release ownership of playerCountLock critical section.
LeaveCriticalSection(&playerCountLock);
}
void CardGame::incrementObserverCount() { // increases the player count by one
// Request ownership of playerCountLock critical section.
EnterCriticalSection(&playerCountLock);
totalObservers++;
// Release ownership of playerCountLock critical section.
LeaveCriticalSection(&playerCountLock);
}
bool CardGame::makePlayer(Client * player) { // adds player to current players, returns true if successful, false otherwise
// add player to player list
// get player position preference from player
int newPos = player->getPlayerPref();
int oldPos = -1;
// if preference is valid, add them to position
if (newPos > 0 && newPos < MAXPLAYERS) {
// remove user currently occupying position
Client * otherPlayer = PLAYERS[newPos];
if (otherPlayer != NULL)
decrementPlayerCount();
PLAYERS[newPos] = NULL; // set new position to NULL
// remove player from position in game
oldPos = removeClient(player); // removes Client from game, decrementing appropriate counters and returning previous position
// add user to desired position
addPlayer(player, newPos);
// if other player occupied a position, add them to player's previous position, if they had one
if (otherPlayer != NULL)
addPlayer(otherPlayer, oldPos);
// if the player didn't have a previous position
else {
otherPlayer->setPlayerPref(0); // reset player preference
connectClient(otherPlayer); // put them back in the connection queue
}
}
// if position preference is invalid
else
return false; // return failure to player
return true; // return true if success
}
//****************************************************************************
// ::GAME CONTROL FLOW::
//****************************************************************************
void CardGame::run() { // starts the current game
// Wait for game to be ready
while (STATUS != 'R') {
// Wait (x) microseconds for information update
int result = WaitForSingleObject(dataUpdate, 10000);
printf("\nQuit Waiting, result: %d", result);
// Check for new players
checkForConnections();
// Check on current connections status and requests
checkCurrentConnections();
// check if game is ready
if (ready())
STATUS = 'R';
// If the users quit, quit
if (STATUS == 'Q')
quit(0);
}
// Once ready, play game:
do {
play(gType);
} while (restart()); // While players still want to play, verify game-type data and restart
// game data should be saved after each round, so no current need for a cleanup function.
}
void CardGame::play(char gType) { // Launch the game type specified
// update players
sendToAll(G_STATUS, settingsString());
//update status to playing
STATUS = 'P';
switch (gType) {
case 'P':
managePinochleGamePlay();
break;
case 'E':
manageEuchreGamePlay();
break;
}
}
int CardGame::removeClient(Client * player) { // removes Client from game, decrementing appropriate counters, returns previous position, 0 if not in game, 1-maxplayers if player, maxplayers-maxobservers if observer
int oldPos = 0;
// check if player is playing
for (int i = 0; i < MAXPLAYERS; i++) // for each player position
if (PLAYERS[i] == player) { // check if that position is the player in question
oldPos = i; // if so, save that position
PLAYERS[i] = NULL;
}
// decrement player count if player was removed from current game
if (oldPos) {
decrementPlayerCount();
return oldPos; // return their player position
}
// otherwise check if player is an observer
else {
for (int i = 0; i < MAXOBSERVERS; i++) // for each player position
if (OBSERVERS[i] == player) { // check if that position is the player in question
oldPos = i; // if so, save that position
OBSERVERS[i] = NULL;
}
// check if player was an observer
if (oldPos) {
decrementObserverCount();
return oldPos + MAXPLAYERS; // return their observer position
}
}
// otherwise player is waiting to be added, return 0
return 0;
}
//****************************************************************************
// ::PLAYER COMMUNICATION::
//****************************************************************************
bool CardGame::handleRequest(Client * player, unsigned char request) { // handles request from Client and notifies Client of request status, returns true if success
// execute appropriate response to request passed in as argument
switch (request) {
case G_LIST: // Client requests game list
printf("\nUnhandled request:%u from player: %s", request, player->getName());
break;
case RESTART_ANS: // Restart answer
handleRestartAns();
player->requestHandled(RESTART_ANS);
break;
case N_GINFO: // New Game Creation Info
player->sendM(G_STATUS, settingsString());
player->requestHandled(N_GINFO);
break;
case BEC_PLAYER:// Become Player
player->requestHandled(BEC_PLAYER, makePlayer(player)); // send the result of the makePlayer command
break;
case BEC_OBS:// Become Observer
player->requestHandled(BEC_OBS, makePlayer(player)); // send the result of the makePlayer command
break;
default: // request not handled
// Run in base class to accept any default responses
if (gamePlayer::handleRequest(player, request))
return true;
printf("\nUnhandled request:%u from player: %s", request, player->getName());
return false;
}
return true;
}
void CardGame::sendToAll(unsigned char code) { // send message of type code to all players and observers
sendToAll(code, '\0');
}
void CardGame::sendToAll(unsigned char code, char msg) { // send message of type code, with body of type msg to all players and observers
//convert to string
std::string temp;
temp.fill(1, msg);
// send message to all players
}
void CardGame::sendToAll(unsigned char code, std::string * msg) { // send message of type code, with body of type msg to all players and observers
// send message to all players
for (int i = 0; i < MAXPLAYERS; ++i)
if (PLAYERS[i])
PLAYERS[i]->sendM(code, msg);
// send message to all observers
for (int i = 0; i < MAXOBSERVERS; ++i)
if (OBSERVERS[i])
OBSERVERS[i]->sendM(code, msg);
}
bool CardGame::checkForConnections() { // checks for new incoming connections
printf("\nchecking for connections...");
// Request ownership of newPlayerList critical section.
EnterCriticalSection(&newPlayerListLock);
// if new players have connected, add them to the game
while (newPlayers.size() > 0) {
// get next Client
Client * toAdd = newPlayers.front(); // copy over new Client data
// get preferred position
int pos = toAdd->getPlayerPref();
if (pos == 0) { //if the player doesnt have a preferred position
if (MAXPLAYERS > totalPlayers){ // if there is still room in the game
for (int i = 0; i < MAXPLAYERS; i++) // add them to the first available one
if (PLAYERS[i] == NULL) { // iterate to the first available position
pos = i; // save that position and quit looking
i += MAXPLAYERS;
}
}
else // if there is no room in the game
pos = MAXPLAYERS + 1;
}
// add player to the position chosen
addPlayer(toAdd, pos);
newPlayers.pop(); // remove Client from list
}
// Release ownership of newPlayerListLock critical section.
LeaveCriticalSection(&newPlayerListLock);
return true;
}
bool CardGame::checkCurrentConnections() { // checks for requests from Clients
for (int i = 0; i < MAXPLAYERS; i++) { // for each possible player
if (PLAYERS[i] != NULL && PLAYERS[i]->getStatus() > 0) { // if there is a player currently connected
DEBUG_IF(PLAYERS[i]->getStatus() <= 0)
printf("\nskipping player %s, status: %c", PLAYERS[i]->getName(), PLAYERS[i]->getStatus());
checkForRequests(PLAYERS[i]); // check and execute any commands
}
}
for (int i = 0; i < MAXOBSERVERS; i++) { // for each possible player
if (OBSERVERS[i] != NULL && OBSERVERS[i]->getStatus() > 0) // if there is a player currently connected
checkForRequests(OBSERVERS[i]); // check and execute any commands
}
// return success
return true;
}
void handleRestartAns() { // runs the servers restart answer protocol
printf("\nhandling restart answer");
}
/*void CardGame::echo(Client * curPlayer) { // echoes and talks to current player
// std::string * answer;
// // send hello
// curPlayer->sendM(0, "Hello Client! welcome the Card game situation!");
//
// while (true) {
// // Save and format answer
// int result = curPlayer->getStrAnswer(answer);
// std::string answer->insert(0, "Answer received: ");
// printf(answer->c_str()); // Print out player response
//
// // Send response
// answer->insert(0, "Thank you Client for: ");
// curPlayer->sendM(0, answer);
// curPlayer->sendM(0, "would you like to send us anything else?");
// }
//
//} */
//****************************************************************************
// ::GAMEPLAY::
//****************************************************************************
void CardGame::manageEuchreGamePlay() { // plays a euchre round
// check player count
if (MAXPLAYERS != 4) {
printf("\nMax Players Error, MAXPLAYERS: %d", MAXPLAYERS);
return;
}
// Play Euchre
while (restart()) {
euchreDealCards();
euchreBiddingPhase();
euchreTricksPhase();
publishReport();
}
}
void CardGame::euchreDealCards() { // deal out euchre hand to each player
// shuffle and deal out Cards
eRound.reset();
// send dealt hand to each player
for (int i = 0; i < MAXPLAYERS; i++) // for each player
PLAYERS[i]->sendM(HAND_DEALT, eRound.handDealtString(i)); // send hand dealt with player number
}
void CardGame::euchreBiddingPhase() { // manages Euchre bidding phase
bool trumpSet = false;
while (!trumpSet) {
// flip over the trump Card so each player can see
Card top = eRound.flipKitty();
// If the stack was empty, re-deal
if (top.value == 0) {
euchreDealCards(); // re-deal
continue; // restart while loop
}
// give each player the chance to call trump, in clockwise order starting with the dealer
sendToAll(KITTY_FLP, top.chr()); // notify all players of trump Card being flipped
int ans;
for (int i = 0; i < MAXPLAYERS; i++) {
int result = PLAYERS[(i + eRound.leader) % MAXPLAYERS]->getIntAnswer(&ans, ORDER_UP); // get answer from player and ensure correct message was received
if (result > 0) {
if (ans > 0) {
orderUp(top, (i + eRound.leader) % MAXPLAYERS); // sets trump, makers and notifies all players that player n ordered up Card top
i += MAXPLAYERS; // stop asking players if they want to order up
trumpSet = true;
}
else
sendToAll(TRMP_ORD, '0'); // notify other players the current player passed, order up = pass or 'false' or 0
}
else
printf("\nPlayer connection error with player: %d, result: %d", (i + eRound.leader) % MAXPLAYERS, result);
}
// If no one bids flip over the next Card on next loop through while()
}
}
void CardGame::euchreTricksPhase() { // manages Euchre trick playing phase
int hasLead = eRound.leader;
Card* recent;
bool legal;
// When all tricks have been played, quit
while (eRound.inPlay()) {
// Get first Card, The dealer goes first
// gather one trick
for (int i = 0; i < MAXPLAYERS; i++) { // for each player, starting with the trick leader
// get/check current players play
legal = false;
while (!legal) { // while they haven't played a legal Card
recent = PLAYERS[hasLead + i]->getNextPlay(); // request play and verify legality
legal = eRound.playCard(*recent); // if play was legal, move to next player
}
// update other players of Card recently played
sendToAll(PLY_Card, recent->chr());
}
// Whoever wins the trick, goes first next trick
hasLead = eRound.wonLastTrick();
}
}
void CardGame::orderUp(Card top, int n) { // sets trump, makers and notifies all players that player n ordered up Card top
// set trump makers
eRound.orderUp(n);
// notify all players and observers
sendToAll(TRMP_ORD, 1);
// check if anyone wants to go it alone?? ***********************************
}
void CardGame::managePinochleGamePlay() {//plays a pinochle round
while (!gameOver) {
pinochleBiddingPhase();
pinochlemeldingPhase();
pinochleTricksPhase();
publishReport();
}
}
void CardGame::pinochleBiddingPhase() { //manages entire bidding phase
}
void CardGame::pinochlemeldingPhase() { //manages entire melding phase
}
void CardGame::pinochleTricksPhase() { //manages entire trick taking phase
}
void CardGame::publishReport() { //totals scores and publishes to player
}
void CardGame::diconnectPlayers() { //disconnect all network connections
}
void CardGame::saveGame() {
}
bool CardGame::restart() {
int temp;
int ans = 0;
if ()
for (int i = 0; i < totalPlayers; i++) { // send query
PLAYERS[i]->sendM(RESTART_G);
}
for (int i = 0; i < totalPlayers; i++) { // tally responses
PLAYERS[i]->getIntAnswer(&temp, RESTART_ANS);
ans += temp;
}
return (totalPlayers == ans); // return group decision
}
void CardGame::quit(int type) { // shutdown/save the game and close connections, if type == 0, don't save
//Disconnect users
for (int i = 0; i < MAXPLAYERS; ++i)
PLAYERS[i]->closeConnection();
//disconnect any observers
for (int i = 0; i < MAXOBSERVERS; ++i) //for each occupied observer spot
if (OBSERVERS[i]) //disconnect it if it exists
OBSERVERS[i]->closeConnection();
WSACleanup(); //deallocates WSA data
}
int CardGame::ready() { // Returns true if the game is at capacity
// check if there are still users in the game
if (totalPlayers < 1)
STATUS = 'Q';
// return true if the game is full
return totalPlayers == MAXPLAYERS;
}
| true |
951b7e8200030f47293571220308e3bf3720ab0c | C++ | prateeksarangi/OctoberCircuits_2k19 | /Question1.cpp | UTF-8 | 337 | 3.03125 | 3 | [] | no_license | #include<iostream>
using namespace std;
long long int factorial(long long int N){
long long int f = 1;
int i;
for(i=1; i<=N; i++)
f *= i;
return f;
}
int main(int argc, char const *argv[]){
long long int x;
int N, T, f;
cin>>T;
while(T--){
cin>>N;
f = factorial(N);
x = ((N-1)*N*f) / 2;
cout<<x<<endl;
}
return 0;
} | true |
f5daed12ff731d3ddae91785fb2b7d3acd654f12 | C++ | theroyalcoder/HF-ICT-3-SEM-AAD | /30_eigenerCode/VectorDequeList/main.cpp | UTF-8 | 3,049 | 3.46875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <deque>
#include <vector>
#include <list>
#include <map>
#include <queue>
using namespace std;
int main() {
deque<int> deque1;
// insert at the end
deque1.push_back(rand());
// insert at the start
deque1.push_front(rand());
// loop through elements
deque<int>::iterator iter1;
for (iter1=deque1.begin(); iter1!=deque1.end(); iter1++) {
cout << *iter1 << endl;
}
vector<int> vector1;
// insert at the end
vector1.push_back(rand());
// delete at a specific position
auto iter2_d = vector1.begin();
vector1.erase(iter2_d);
// loop through elements
vector<int>::iterator iter2;
for (iter2=vector1.begin(); iter2!=vector1.end(); iter2++) {
cout << *iter2 << endl;
}
list<int> list1;
// insert at the end
list1.push_back(rand());
// insert at the start
list1.push_front(rand());
// insert at a specific position
auto iter3_l = list1.begin(); iter3_l++;
list1.insert(iter3_l, rand ( ) ) ;
// loop through elements
list<int>::iterator iter3;
for (iter3=list1.begin(); iter3!=list1.end(); iter3++) {
cout << *iter3 << endl;
}
map<int, string> Mapname;
// insert
Mapname[0] = "HERZIG";
Mapname[1] = "BALE";
Mapname[0] = "WAYNE"; // old value will be overwritten
pair<map<int , string>::iterator, bool> ret;
ret = Mapname.insert(pair<int , string>(2, "PARKER"));
// ret.second is true
ret = Mapname.insert(pair<int , string>(2, "CLARK")); // ret .second is false , because key 2 already exists
// loop through elements
map<int , string>::iterator iter;
for (iter=Mapname.begin(); iter!=Mapname.end(); iter++) {
int key = iter->first;
string value = iter->second;
}
for (iter = Mapname.begin(); iter != Mapname.end(); ++iter) {
cout << iter->first << endl;
cout << iter->second << endl;
}
class Queue {
private :
Klassenname values; // stack based queue private :
Queue();
Queue(const Klassenname & obj);
Queue operator= (const Queue& obj);
virtual ~Queue();
bool deque( int & value);
bool enque( int value);
bool front( int & value);
bool back( int & value);
int size();
bool isEmpty ( ) ;
};
class Klassenname {
private :
int *values; // array based stack int maxNumberOfElement ;
int index ;
private :
Klassenname();
Klassenname(const Klassenname & obj);
Klassenname operator= ( const Klassenname & obj ) ; virtual ~Klassenname ( ) ;
bool pop(int & value);
bool push( int value);
bool top(int & value);
int size();
bool isEmpty();
};
Klassenname Klassenname::operator= (const Klassenname& b) {
this->length = b.length;
this->breadth = b.breadth;
this->height = b.height;
return *this;
}
return 0;
};
| true |
f51b8300aad277fccbd093939bcbbcb6936262bc | C++ | FabulaM24/JurassicParkTrespasserAIrip | /jp2_pc/Source/Lib/GeomDBase/Hull.cpp | WINDOWS-1252 | 26,271 | 2.515625 | 3 | [] | no_license | /***********************************************************************************************
*
* Copyright DreamWorks Interactive. 1998
*
* Implementation of Hull.hpp
*
* Purpose: A fast approximating convex hull algorithm based on the QuickHull algorithm.
*
***********************************************************************************************
*
* $Log:: /JP2_PC/Source/Lib/GeomDBase/Hull.cpp $
*
* 2 98.03.17 4:25p Mmouni
* Removed object name being passed in for debugging purposes.
*
* 1 98.02.26 9:47p Mmouni
*
**********************************************************************************************/
#include "Common.hpp"
#include "Lib/GeomDBase/Plane.hpp"
#include "Lib/Sys/DebugConsole.hpp"
#include <list>
#include <vector>
#include <algorithm>
#include <memory.h>
#include <stdio.h>
#include <string.h>
#define DODEBUG(x)
//
// Usefull constants.
//
const float f_outside_tolerance = 0.001;
const float f_colinear_tolerance = 0.0001; // 0.25 degrees
const float f_coincident_tolerance = 0.001;
//
// Type equaivalent to pv3.
//
typedef CVector3<>* Vertex;
//
// A Facet of the convex hull.
//
class Facet
{
public:
enum FacetFlags { Flipped = 1, Degenerate = 2 };
Vertex verts[3]; // Vertices of the facet.
std::list<Vertex> outside; // Vertices outside the facet.
CPlane plane; // Plane equation for the facet.
int flags; // Flags for this facet.
Facet()
{
verts[0] = 0;
verts[1] = 0;
verts[2] = 0;
flags = 0;
}
Facet(Vertex vtx0, Vertex vtx1, Vertex vtx2) : plane(*vtx0, *vtx1, *vtx2)
{
verts[0] = vtx0;
verts[1] = vtx1;
verts[2] = vtx2;
flags = 0;
}
//
// Set plane so that a point v3 is inside.
//
void Orient(const CVector3<> &v3)
{
if (plane.rDistance(v3) > 0.0f)
{
// reverse plane if point is outside.
plane = -plane;
flags |= Flipped;
}
}
};
//
//
//
class Edge
{
public:
Vertex vtx0, vtx1;
std::list<Facet>::iterator facet0, facet1;
Edge()
{
vtx0 = 0;
vtx1 = 0;
}
Edge(Vertex v0, Vertex v1)
{
if (v0 < v1)
{
vtx0 = v0;
vtx1 = v1;
}
else
{
vtx0 = v1;
vtx1 = v0;
}
}
bool operator< (const Edge& edge)
{
return (vtx0 < edge.vtx0 || (vtx0 == edge.vtx0 && vtx1 < edge.vtx1));
}
bool operator== (const Edge& edge)
{
return (vtx0 == edge.vtx0 && vtx1 == edge.vtx1);
}
};
//
// A list of facets that keeps a list of edges so that adjacent facets can
// be found quickly.
//
class FacetList : public std::list<Facet>
{
private:
// A vector of edges.
std::vector<Edge> edges;
// Return the iterator pointing to an edge.
std::vector<Edge>::iterator FindEdge(Vertex vtx0, Vertex vtx1)
{
// Binary search for edge.
std::vector<Edge>::iterator at = lower_bound(edges.begin(), edges.end(), Edge(vtx0, vtx1));
Assert(*at == Edge(vtx0, vtx1));
return at;
}
// Add an edge if it doesn't already exist.
void AddEdge(Vertex vtx0, Vertex vtx1, iterator facet)
{
// Binary search for edge.
std::vector<Edge>::iterator at = lower_bound(edges.begin(), edges.end(), Edge(vtx0, vtx1));
if (at != edges.end() && *at == Edge(vtx0, vtx1))
{
// Found, make the edge point to the facet.
if (at->facet0 == end())
at->facet0 = facet;
else if (at->facet1 == end())
at->facet1 = facet;
else
Assert(0);
}
else
{
// Insert edge (in sorted order).
std::vector<Edge>::iterator new_edge = edges.insert(at, Edge(vtx0, vtx1));
new_edge->facet0 = facet;
new_edge->facet1 = end();
}
}
// Remove the pointer to this facet from this edge.
void RemoveEdge(Vertex vtx0, Vertex vtx1, iterator facet)
{
// Binary search for edge.
std::vector<Edge>::iterator at = lower_bound(edges.begin(), edges.end(), Edge(vtx0, vtx1));
Assert(*at == Edge(vtx0, vtx1));
// Remove the pointer to this facet.
if (at->facet0 == facet)
at->facet0 = end();
else if (at->facet1 == facet)
at->facet1 = end();
else
Assert(0);
}
public:
// Add a facet.
void Add(Vertex vtx0, Vertex vtx1, Vertex vtx2)
{
// Add facet to list.
push_front(Facet(vtx0, vtx1, vtx2));
// Adjust edges for new facet.
AddEdge(vtx0, vtx1, begin());
AddEdge(vtx1, vtx2, begin());
AddEdge(vtx2, vtx0, begin());
}
// Get adjacent facet indexed by index.
iterator AdjacentFacet(iterator facet, int index1, int index2)
{
Assert(index1 >= 0 && index1 <= 2)
Assert(index2 >= 0 && index2 <= 2)
Assert(index1 != index2);
// Lookup edge based on index.
std::vector<Edge>::iterator edge = FindEdge((*facet).verts[index1], (*facet).verts[index2]);
// Return the facet that is opposite this facet.
if (edge->facet0 == facet)
{
Assert(edge->facet1 != end());
return edge->facet1;
}
else
{
Assert(edge->facet0 != end());
return edge->facet0;
}
// We should always have an adjacent facet.
Assert(0);
return end();
}
// Remove a facet.
void Remove(iterator facet)
{
// Adjust edges for removed facet.
RemoveEdge((*facet).verts[0], (*facet).verts[1], facet);
RemoveEdge((*facet).verts[1], (*facet).verts[2], facet);
RemoveEdge((*facet).verts[2], (*facet).verts[0], facet);
// Remove from list.
erase(facet);
}
// Reset the list.
void reset()
{
erase(begin(), end());
edges.erase(edges.begin(), edges.end());
}
};
//
// A class to help finding points at each extreme.
//
class Extreme
{
public:
float fv;
std::list<Vertex> verts;
Extreme()
{
fv = 0.0f;
}
Extreme(float f, Vertex v)
{
fv = f;
verts.push_front(v);
}
void Set(float f, Vertex v)
{
fv = f;
verts.push_front(v);
}
void SetMin(float f, Vertex v)
{
// Inside tolerance?
if (f < fv + f_outside_tolerance)
{
// Way inside?
if (f < fv - f_outside_tolerance)
{
fv = f;
verts.erase(verts.begin(), verts.end());
}
verts.push_front(v);
}
}
void SetMax(float f, Vertex v)
{
if (f > fv - f_outside_tolerance)
{
if (f > fv + f_outside_tolerance)
{
fv = f;
verts.erase(verts.begin(), verts.end());
}
verts.push_front(v);
}
}
};
//
// for all unvisited neighbors N of facets in V
// if p is above N
// add N to V
//
bool find_visble_neighbors
(
const FacetList::iterator &facet,
FacetList &facets,
Vertex vtx_p,
std::list<FacetList::iterator> &visible
)
{
bool bIsVisible = 0;
// Check if vertex is visible from this facet.
if (((*facet).flags & Facet::Degenerate))
{
// Degenerate facet is visisble if either of it's neighors are.
FacetList::iterator it_adj;
std::list<FacetList::iterator>::iterator itit_this;
// Add facet iterator to visible list.
visible.push_front(facet);
itit_this = visible.begin();
// Recursively look at each neighboring facet, skipping facets already in the
// visible list.
it_adj = facets.AdjacentFacet(facet, 0, 1);
if (find(visible.begin(), visible.end(), it_adj) == visible.end())
{
if (find_visble_neighbors(it_adj, facets, vtx_p, visible))
bIsVisible = 1;
}
it_adj = facets.AdjacentFacet(facet, 1, 2);
if (find(visible.begin(), visible.end(), it_adj) == visible.end())
{
if (find_visble_neighbors(it_adj, facets, vtx_p, visible))
bIsVisible = 1;
}
it_adj = facets.AdjacentFacet(facet, 2, 0);
if (find(visible.begin(), visible.end(), it_adj) == visible.end())
{
if (find_visble_neighbors(it_adj, facets, vtx_p, visible))
bIsVisible = 1;
}
if (!bIsVisible)
{
// Remove this facet from the list.
visible.erase(itit_this);
}
}
else if ((*facet).plane.rDistance(*vtx_p) > f_outside_tolerance)
{
FacetList::iterator it_adj;
// Add facet iterator to visible list.
visible.push_front(facet);
bIsVisible = 1;
// Recursively look at each neighboring facet, skipping facets already in the
// visible list.
it_adj = facets.AdjacentFacet(facet, 0, 1);
if (find(visible.begin(), visible.end(), it_adj) == visible.end())
find_visble_neighbors(it_adj, facets, vtx_p, visible);
it_adj = facets.AdjacentFacet(facet, 1, 2);
if (find(visible.begin(), visible.end(), it_adj) == visible.end())
find_visble_neighbors(it_adj, facets, vtx_p, visible);
it_adj = facets.AdjacentFacet(facet, 2, 0);
if (find(visible.begin(), visible.end(), it_adj) == visible.end())
find_visble_neighbors(it_adj, facets, vtx_p, visible);
}
return bIsVisible;
}
//******************************************************************************************
bool bGoodPlane
(
const Vertex vtx_a, // The three vertices.
const Vertex vtx_b,
const Vertex vtx_c
)
//
// Returns:
// 1 if the points form a plane.
// 0 if they are co-incident or co-linear.
//
//**********************************
{
if (Fuzzy(*vtx_a, f_coincident_tolerance) == *vtx_b)
return 0;
if (Fuzzy(*vtx_a, f_coincident_tolerance) == *vtx_c)
return 0;
if (Fuzzy(*vtx_b, f_coincident_tolerance) == *vtx_c)
return 0;
// Check for co-linear points.
float f_dot = CDir3<>(*vtx_c - *vtx_a) * CDir3<>(*vtx_c - *vtx_b);
if (f_dot >= 1.0f - f_colinear_tolerance || f_dot <= -1.0f + f_colinear_tolerance)
return 0;
return 1;
}
//
// Writes the hull data out to a simple 3d file.
//
void DumpHullSob(char *str_name, CVector3<>* av3_pts, int i_num_pts, FacetList& facets)
{
char str_buf[256];
strcpy(str_buf, "C:\\Test_Data\\");
strcat(str_buf, str_name);
strcat(str_buf, ".sob");
FILE *fp = fopen(str_buf, "w");
if (fp)
{
fprintf(fp, "%s\n", str_name);
fprintf(fp, "%d\n", i_num_pts);
fprintf(fp, "%d\n", facets.size());
for (int i = 0; i < i_num_pts; i++)
{
fprintf(fp, "%f %f %f\n", av3_pts[i].tX, av3_pts[i].tY, av3_pts[i].tZ);
}
for (FacetList::iterator it_fac = facets.begin(); it_fac != facets.end(); it_fac++)
{
if ((*it_fac).flags & Facet::Flipped)
fprintf(fp, "%d %d %d\n", (*it_fac).verts[0] - av3_pts,
(*it_fac).verts[1] - av3_pts,
(*it_fac).verts[2] - av3_pts);
else
fprintf(fp, "%d %d %d\n", (*it_fac).verts[2] - av3_pts,
(*it_fac).verts[1] - av3_pts,
(*it_fac).verts[0] - av3_pts);
}
fclose(fp);
}
}
//
// Writes the hull data out to a geo file.
//
void DumpHullGeo(char *str_name, CVector3<>* av3_pts, int i_num_pts, FacetList& facets)
{
char str_buf[256];
strcpy(str_buf, "C:\\Test_Data\\");
strcat(str_buf, str_name);
strcat(str_buf, ".geo");
FILE *fp = fopen(str_buf, "w");
if (fp)
{
fprintf(fp, "3DG1\n");
fprintf(fp, "%d\n", i_num_pts);
for (int i = 0; i < i_num_pts; i++)
{
fprintf(fp, "%f %f %f\n", av3_pts[i].tX, av3_pts[i].tY, av3_pts[i].tZ);
}
for (FacetList::iterator it_fac = facets.begin(); it_fac != facets.end(); it_fac++)
{
if ((*it_fac).flags & Facet::Flipped)
fprintf(fp, "3 %d %d %d 15\n", (*it_fac).verts[2] - av3_pts,
(*it_fac).verts[1] - av3_pts,
(*it_fac).verts[0] - av3_pts);
else
fprintf(fp, "3 %d %d %d 15\n", (*it_fac).verts[0] - av3_pts,
(*it_fac).verts[1] - av3_pts,
(*it_fac).verts[2] - av3_pts);
}
fclose(fp);
}
}
//
// Iterate through a set of points removing co-incident ones.
//
void RemoveDuplicatePoints
(
CVector3<>* av3_pts,
int &i_num_pts
)
{
int i = 0;
for (;;)
{
// Do nothing if there is only one point in the set.
if (i_num_pts <= 1)
return;
// Is the next point close to any of the remaining points.
bool b_close = false;
for (int i_rem = i + 1; i_rem < i_num_pts; i_rem++)
{
if (Fuzzy(av3_pts[i], 0.0125) == av3_pts[i_rem])
{
b_close = true;
break;
}
}
// If the point is close, replace it with the end point.
if (b_close)
{
av3_pts[i] = av3_pts[i_num_pts - 1];
--i_num_pts;
}
else
{
// Otherwise increment the current point.
++i;
}
if (i >= int(i_num_pts) - 2)
return;
}
}
//**********************************************************************************************
//
int iQuickHull
(
CVector3<>* av3_pts,
int i_num_pts
)
//
// Find the convex hull of a set of vertices using the quick hull algorithm.
//
// Returns the number of vertices in the reduced array or zero if the method
// fails to compute a convex hull.
//
//**********************************
{
int i;
FacetList facets;
Extreme extremes[6];
RemoveDuplicatePoints(av3_pts, i_num_pts);
//
// Get a list of points at each extreme.
//
extremes[0].Set(av3_pts[0].tX, &av3_pts[0]);
extremes[1].Set(av3_pts[0].tY, &av3_pts[0]);
extremes[2].Set(av3_pts[0].tZ, &av3_pts[0]);
extremes[3].Set(av3_pts[0].tX, &av3_pts[0]);
extremes[4].Set(av3_pts[0].tY, &av3_pts[0]);
extremes[5].Set(av3_pts[0].tZ, &av3_pts[0]);
for (i = 1; i < i_num_pts; i++)
{
extremes[0].SetMin(av3_pts[i].tX, &av3_pts[i]);
extremes[1].SetMin(av3_pts[i].tY, &av3_pts[i]);
extremes[2].SetMin(av3_pts[i].tZ, &av3_pts[i]);
extremes[3].SetMax(av3_pts[i].tX, &av3_pts[i]);
extremes[4].SetMax(av3_pts[i].tY, &av3_pts[i]);
extremes[5].SetMax(av3_pts[i].tZ, &av3_pts[i]);
}
//
// Create a four point simplex out of the six points with min/max co-ordinates.
//
Vertex vtx_simplex[4];
std::list<Vertex> lvtx_dont_use;
// Choose four different vertices.
int i_use_extreme = 0;
int i_simplex_cnt = 0;
std::list<Vertex>::iterator it_vtx_ext = extremes[i_use_extreme].verts.begin();
// Find vertices to use for the simplex.
while (i_simplex_cnt < 4 && i_use_extreme < 6)
{
// Pick a point from the current extreme.
vtx_simplex[i_simplex_cnt] = *it_vtx_ext;
// Make sure it isn't in the don't use list.
if (find(lvtx_dont_use.begin(), lvtx_dont_use.end(), *it_vtx_ext) == lvtx_dont_use.end())
{
// Keep this point.
i_simplex_cnt++;
// Add the points from this extreme to the don't use list.
lvtx_dont_use.splice(lvtx_dont_use.end(), extremes[i_use_extreme].verts);
// Go on to the next extreme.
i_use_extreme++;
if (i_use_extreme < 6)
it_vtx_ext = extremes[i_use_extreme].verts.begin();
}
else
{
// Try the next point in this extreme.
it_vtx_ext++;
// If there is no next point...
if (it_vtx_ext == extremes[i_use_extreme].verts.end())
{
// Go on to the next extreme.
i_use_extreme++;
if (i_use_extreme < 6)
it_vtx_ext = extremes[i_use_extreme].verts.begin();
}
}
}
if (i_simplex_cnt < 4)
{
// Degenerate convex hull, either a triangle, line or point.
CVector3<> av3_temp[3];
// Not enough points to make a good initial hull.
DODEBUG(dprintf("QuickHull Failed: not enough points for simplex\n"));
return(0);
}
// Make faces out of all combinations of the four vertices.
FacetList::iterator F;
// add facet, reverse plane if "other" point is outside.
facets.Add(vtx_simplex[0], vtx_simplex[1], vtx_simplex[2]);
F = facets.begin();
(*F).Orient(*vtx_simplex[3]);
// add facet, reverse plane if "other" point is outside.
facets.Add(vtx_simplex[0], vtx_simplex[1], vtx_simplex[3]);
F = facets.begin();
(*F).Orient(*vtx_simplex[2]);
// add facet, reverse plane if "other" point is outside.
facets.Add(vtx_simplex[0], vtx_simplex[2], vtx_simplex[3]);
F = facets.begin();
(*F).Orient(*vtx_simplex[1]);
// add facet, reverse plane if "other" point is outside.
facets.Add(vtx_simplex[1], vtx_simplex[2], vtx_simplex[3]);
F = facets.begin();
(*F).Orient(*vtx_simplex[0]);
//
// Setup the outside list for the simplex.
//
char* ac_used = (char*)_alloca(sizeof(char) * i_num_pts);
memset(ac_used, 0, sizeof(char) * i_num_pts);
// Mark points of simplex as used.
ac_used[vtx_simplex[0] - av3_pts] = 1;
ac_used[vtx_simplex[1] - av3_pts] = 1;
ac_used[vtx_simplex[2] - av3_pts] = 1;
ac_used[vtx_simplex[3] - av3_pts] = 1;
#if (1)
// for each facet F
for (F = facets.begin(); F != facets.end(); F++)
{
float f_max_dist = 0.0f;
// for each unassigned point p
for (i = 0; i < i_num_pts; i++)
{
if (!ac_used[i])
{
// if p is above F
float f_dist = (*F).plane.rDistance(av3_pts[i]);
if (f_dist > f_outside_tolerance)
{
// assign p to F's outside set
if (f_dist > f_max_dist)
{
// keep max point at the front of the list
f_max_dist = f_dist;
(*F).outside.push_front(&av3_pts[i]);
}
else
{
(*F).outside.push_back(&av3_pts[i]);
}
// mark point as used
ac_used[i] = 1;
}
}
}
}
#else
// for each unassigned point p
for (i = 0; i < i_num_pts; i++)
{
if (!ac_used[i])
{
// Farthest distance this point is from any facet.
float f_max_dist = f_outside_tolerance;
// Facet that point is farthest outside.
FacetList::iterator it_max_facet = facets.end();
// for each facet F
for (F = facets.begin(); F != facets.end(); F++)
{
// if p is above F
float f_dist = (*F).plane.rDistance(av3_pts[i]);
if (f_dist > f_max_dist)
{
// keep track of this facet.
f_max_dist = f_dist;
it_max_facet = F;
}
}
if (it_max_facet != facets.end())
{
// mark point as used
ac_used[i] = 1;
// assign p to it_max_facet's outside set
if (!(*it_max_facet).outside.empty())
{
float f_cur_max_dist = (*it_max_facet).plane.rDistance(*(*it_max_facet).outside.front());
if (f_max_dist > f_cur_max_dist)
{
// keep max point at the front of the list
(*it_max_facet).outside.push_front(&av3_pts[i]);
}
else
{
// put non-max points at end.
(*it_max_facet).outside.push_back(&av3_pts[i]);
}
}
else
{
// first point in outside list.
(*it_max_facet).outside.push_front(&av3_pts[i]);
}
}
}
}
#endif
//
// Construct the convex hull by adding outside points.
//
int done = 0;
while (!done)
{
done = 1;
for (F = facets.begin(); F != facets.end(); F++)
{
// if F has a non-empty outside set
if (!(*F).outside.empty())
{
done = 0;
// select the furthest point p of F's outside set
Vertex vtx_p = (*F).outside.front();
(*F).outside.pop_front();
DODEBUG(dprintf("QuickHull: add point %d to facet %d,%d,%d\n", vtx_p - av3_pts,
(*F).verts[0] - av3_pts, (*F).verts[1] - av3_pts, (*F).verts[2] - av3_pts));
// initialize the visible set V to F
std::list<FacetList::iterator> V;
// Find all the neighbors of F that P is visible from.
find_visble_neighbors(F, facets, vtx_p, V);
Assert(!V.empty())
// the boundary of V is the set of horizon ridges H
std::list<FacetList::iterator>::iterator itit_fac;
std::list<Edge> H;
for (itit_fac = V.begin(); itit_fac != V.end(); itit_fac++)
{
FacetList::iterator it_adj;
// Find which adjacent facet(s) is(are) not in V.
it_adj = facets.AdjacentFacet(*itit_fac, 0, 1);
if (find(V.begin(), V.end(), it_adj) == V.end())
{
H.push_front(Edge((**itit_fac).verts[0], (**itit_fac).verts[1]));
}
it_adj = facets.AdjacentFacet(*itit_fac, 1, 2);
if (find(V.begin(), V.end(), it_adj) == V.end())
{
H.push_front(Edge((**itit_fac).verts[1], (**itit_fac).verts[2]));
}
it_adj = facets.AdjacentFacet(*itit_fac, 2, 0);
if (find(V.begin(), V.end(), it_adj) == V.end())
{
H.push_front(Edge((**itit_fac).verts[2], (**itit_fac).verts[0]));
}
}
#if (0)
DODEBUG(dprintf("Horizon Poly:"));
// Order horizon edges to form a polygon.
list<Edge>::iterator it_edge_cur = H.begin();
while (it_edge_cur != H.end())
{
list<Edge>::iterator it_edge_next = it_edge_cur;
it_edge_next++;
// find matching edge for it_edge_cur.
for (list<Edge>::iterator it_edge = it_edge_next; it_edge != H.end(); it_edge++)
{
if ((*it_edge_cur).vtx1 == (*it_edge).vtx0)
{
// Swap it_edge and it_edge_next.
iter_swap(it_edge, it_edge_next);
break;
}
else if ((*it_edge_cur).vtx1 == (*it_edge).vtx1)
{
// Reverse edge.
swap((*it_edge).vtx0, (*it_edge).vtx1);
// Swap it_edge and it_edge_next.
iter_swap(it_edge, it_edge_next);
break;
}
}
DODEBUG(dprintf(" %d", (*it_edge_cur).vtx0 - av3_pts));
it_edge_cur++;
}
DODEBUG(dprintf("\n"));
#endif
// delete the facets in V
// get all the points outside facets in V
// do it now so that new faces get proper edges
std::list<Vertex> outside;
for (itit_fac = V.begin(); itit_fac != V.end(); itit_fac++)
{
// Move vertices outside facet into combined outside list.
outside.splice(outside.begin(), (**itit_fac).outside);
// Remove from facets list.
facets.Remove(*itit_fac);
}
V.erase(V.begin(), V.end());
// Compute pseudo centroid of polygon formed by horizon ridges H.
std::list<Edge>::iterator R = H.begin();
i = 1;
CVector3<> v3_avg = *(*R).vtx0;
v3_avg += *(*R).vtx1;
R++;
while (R != H.end())
{
v3_avg += *(*R).vtx0;
v3_avg += *(*R).vtx1;
R++;
i++;
}
v3_avg /= (float)(i*2);
// for each ridge R in H
for (R = H.begin(); R != H.end(); R++)
{
FacetList::iterator it_new;
// create a new facet from R and p
facets.Add((*R).vtx0, (*R).vtx1, vtx_p);
it_new = facets.begin();
// orient facet correctly
(*it_new).Orient(v3_avg);
if (!bGoodPlane((*R).vtx0, (*R).vtx1, vtx_p))
{
// bad facet, flag it.
(*it_new).flags |= Facet::Degenerate;
DODEBUG(dprintf("Degenerate Facet (%d,%d,%d)\n",
(*F).verts[0] - av3_pts,
(*F).verts[1] - av3_pts,
(*F).verts[2] - av3_pts));
}
// keep new facet in a list.
V.push_front(it_new);
}
#if (0)
// Re-compute planes for degenerate facets.
for (itit_fac = V.begin(); itit_fac != V.end(); itit_fac++)
{
if (((**itit_fac).flags & Facet::Degenerate))
{
// Normal is average of adjacent normals.
FacetList::iterator it_adj;
CVector3<> v3_normal;
it_adj = facets.AdjacentFacet(*itit_fac, 0, 1);
v3_normal = (*it_adj).plane.d3Normal;
it_adj = facets.AdjacentFacet(*itit_fac, 1, 2);
v3_normal += (*it_adj).plane.d3Normal;
it_adj = facets.AdjacentFacet(*itit_fac, 2, 0);
v3_normal += (*it_adj).plane.d3Normal;
v3_normal *= (1.0f/3.0f);
// Use any point for the center of the plane.
(**itit_fac).plane.d3Normal = CDir3<>(v3_normal);
(**itit_fac).plane.rD = -(*(**itit_fac).verts[0] * (**itit_fac).plane.d3Normal);
}
}
#endif
#if (1)
// for each new facet F'
for (itit_fac = V.begin(); itit_fac != V.end(); itit_fac++)
{
std::list<Vertex>::iterator it_vtx_next;
float f_max_dist = 0.0f;
// for each unassigned point q in an outside set of a facet V
for (std::list<Vertex>::iterator it_vtx = outside.begin(); it_vtx != outside.end(); it_vtx = it_vtx_next)
{
it_vtx_next = it_vtx;
it_vtx_next++;
// if q is above F'
float f_dist = (**itit_fac).plane.rDistance(**it_vtx);
if (f_dist > f_outside_tolerance &&
!((**itit_fac).flags & Facet::Degenerate))
{
if (f_dist > f_max_dist)
{
// assign q to F's outside set (at front of list).
(**itit_fac).outside.splice((**itit_fac).outside.begin(), outside, it_vtx);
f_max_dist = f_dist;
}
else
{
// assign q to F's outside set (at end of list).
(**itit_fac).outside.splice((**itit_fac).outside.end(), outside, it_vtx);
}
}
}
}
#else
// for each unassigned point q in an outside set of a facet in V
list<Vertex>::iterator it_vtx_next;
for (list<Vertex>::iterator it_vtx = outside.begin(); it_vtx != outside.end(); it_vtx = it_vtx_next)
{
it_vtx_next = it_vtx;
it_vtx_next++;
float f_max_dist = f_outside_tolerance;
FacetList::iterator it_max_facet = facets.end();
// for each new facet F'
for (itit_fac = V.begin(); itit_fac != V.end(); itit_fac++)
{
// if q is above F'
float f_dist = (**itit_fac).plane.rDistance(**it_vtx);
if (f_dist > f_max_dist &&
!((**itit_fac).flags & Facet::Degenerate))
{
// keep track of this facet.
f_max_dist = f_dist;
it_max_facet = *itit_fac;
}
}
if (it_max_facet != facets.end())
{
if (!(*it_max_facet).outside.empty())
{
float f_cur_max_dist = (*it_max_facet).plane.rDistance(*(*it_max_facet).outside.front());
if (f_max_dist > f_cur_max_dist)
{
// assign q to it_max_facet's outside set (at front of list).
(*it_max_facet).outside.splice((*it_max_facet).outside.begin(), outside, it_vtx);
}
else
{
// assign q to it_max_facet's outside set (at end of list).
(*it_max_facet).outside.splice((*it_max_facet).outside.end(), outside, it_vtx);
}
}
else
{
// assign q to it_max_facet's outside set (at front of list).
(*it_max_facet).outside.splice((*it_max_facet).outside.begin(), outside, it_vtx);
}
}
}
#endif
break;
}
}
}
// Dump information for the hull.
DODEBUG(DumpHullGeo("Hull", av3_pts, i_num_pts, facets));
//
// Pack the vertices in the convex hull.
//
memset(ac_used, 0, sizeof(char) * i_num_pts);
// Mark used vertices.
for (F = facets.begin(); F != facets.end(); F++)
{
ac_used[(*F).verts[0] - av3_pts] = 1;
ac_used[(*F).verts[1] - av3_pts] = 1;
ac_used[(*F).verts[2] - av3_pts] = 1;
}
//
// Test to make sure the Hull encloses all points.
//
for (F = facets.begin(); F != facets.end(); F++)
{
for (i = 0; i < i_num_pts; i++)
{
if ((*F).plane.rDistance(av3_pts[i]) > 10.0f * f_outside_tolerance &&
!((*F).flags & Facet::Degenerate))
{
DODEBUG(dprintf("QuickHull Failed: point %d not enclosed by facet (%d,%d,%d), %f out\n",
i, (*F).verts[0] - av3_pts, (*F).verts[1] - av3_pts, (*F).verts[2] - av3_pts,
(*F).plane.rDistance(av3_pts[i]) - f_outside_tolerance));
// Oh well.
return(0);
}
}
}
// Pack used vertices.
int i_num_used = 0;
for (i = 0; i < i_num_pts; i++)
{
if (ac_used[i])
av3_pts[i_num_used++] = av3_pts[i];
}
DODEBUG(dprintf("QuickHull: points = %d\n", i_num_used));
return(i_num_used);
}
| true |
0d18f3845c673f65bab2f29cf977ecd102ac3528 | C++ | google-code/asf-viewer | /AsfViewer/AsfReader/AsfHeader.h | UTF-8 | 566 | 2.53125 | 3 | [] | no_license | #pragma once
#include "AsfError.h"
#include <string>
#include <regex>
#include <map>
namespace Asf {
class AsfHeader
// Saves pairs of AsfFile properties and its values
{
public:
AsfHeader(std::istream& inputStream);
std::string operator[](const std::string& parametr) const { return values.at(parametr); }
void print(std::ostream& outputStream) const;
~AsfHeader(void) {}
private:
void addProperty(const std::string& propertyLine);
const std::tr1::regex pattern;
std::map<std::string, std::string> values;
};
} // end of namespace
| true |
08603b0bc4c081af80ce771626c060f0bb4c03a2 | C++ | firebreath/indexeddb | /Root/Support/DatabaseLocation.h | UTF-8 | 1,776 | 2.6875 | 3 | [] | no_license | /**********************************************************\
Copyright Brandon Haynes
http://code.google.com/p/indexeddb
GNU Lesser General Public License
\**********************************************************/
#ifndef BRANDONHAYNES_INDEXEDDB_SUPPORT_DATABASELOCATION_H
#define BRANDONHAYNES_INDEXEDDB_SUPPORT_DATABASELOCATION_H
#include <string>
#include <boost/filesystem.hpp>
namespace BrandonHaynes {
namespace IndexedDB {
namespace Implementation {
///<summary>
/// This utility class is used to retreive operating system-specific paths for implementations. It was
/// designed with Berkeley DB in mind, but is probably useful across other environments.
///</summary>
class DatabaseLocation
{
public:
// Gets a valid database storage path for this origin, specific to a given user (via an environment variable)
static const std::string getDatabasePath(const std::string& origin, const std::string& databaseName);
// Gets a valid object storage path for this origin, specific to a given user (and underneath the database path)
static const std::string getObjectStorePath(const std::string& origin, const std::string& databaseName, const std::string& objectStoreName);
// Given a path, performs some sanity checks on it to ensure that there is no cross-origin or naming issues
static void ensurePathValid(const std::string& path);
private:
DatabaseLocation() { }
// Stores a reference to the user-specific home
static ::boost::filesystem::path userHome;
// Stores a relative reference to the database path
static ::boost::filesystem::path databaseHome;
// A set of invalid filename characters specific to "this" operating system
static const char* illegalFilenameCharacters;
};
}
}
}
#endif | true |
a5afa48b4140585925e963569bdfcbbcc658ad9c | C++ | chicolismo/NewFakeBox2 | /dropboxUtil.h | UTF-8 | 2,463 | 2.53125 | 3 | [] | no_license | #ifndef __DROPBOX_UTIL_H__
#define __DROPBOX_UTIL_H__
#define MAX_DEVICES 2
#define MAX_NAME_SIZE 256
#define BUFFER_SIZE 1024
#define EMPTY_DEVICE (-1)
#include <string>
#include <map>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <openssl/ossl_typ.h>
enum ConnectionType { Normal, Sync, ServerConnection };
// Possíveis resultados da tentativa de conexão
enum ConnectionResult { Success, Error, SSLError, CantAccept };
enum Command { Upload, Download, Delete, ListServer, Exit, IsAlive, Hold, Release };
struct FileInfo {
char filename_[MAX_NAME_SIZE];
char extension_[MAX_NAME_SIZE];
time_t last_modified_;
size_t bytes_;
SSL *holder;
explicit FileInfo();
void set_filename(const char *filename);
void set_filename(const std::string &filename);
std::string filename() const;
void set_extension(const char *extension);
void set_extension(const std::string &extension);
std::string extension() const;
void set_last_modified(time_t time);
time_t last_modified() const;
void set_bytes(size_t bytes);
size_t bytes() const;
std::string string() const;
};
struct Client {
std::string user_id;
bool is_logged;
int connected_devices[MAX_DEVICES];
int sockets[MAX_DEVICES];
std::vector<FileInfo> files;
//Semaphore sem;
std::mutex user_mutex;
// Methods
explicit Client(std::string user_id);
explicit Client(const char *user_id);
};
typedef std::map<std::string, Client *> ClientDict;
bool read_socket(int socket_fd, void *buffer, size_t count);
bool write_socket(int socket_fd, const void *buffer, size_t count);
void send_string(int socket_fd, const std::string &input);
std::string receive_string(int socket_fd);
void send_bool(int socket_fd, bool value);
bool read_bool(int socket_fd);
bool send_file(int to_socket_fd, FILE *in_file, size_t file_size);
bool read_file(int from_socket_fd, FILE *out_file, size_t file_size);
// Versões SSL das mesmas funções
bool read_socket(SSL *ssl, void *buffer, size_t count);
bool write_socket(SSL *ssl, const void *buffer, size_t count);
void send_string(SSL *ssl, const std::string &input);
std::string receive_string(SSL *ssl);
void send_bool(SSL *ssl, bool value);
bool read_bool(SSL *ssl);
bool send_file(SSL *to_ssl, FILE *in_file, size_t file_size);
bool read_file(SSL *from_ssl, FILE *out_file, size_t file_size);
void show_certificate(SSL *ssl);
#endif
| true |
39f2e9623a5d4f4cd710ab4714467ea30a89def5 | C++ | smasimore/MastersThesis | /fsw/include/Device.hpp | UTF-8 | 4,703 | 3.1875 | 3 | [] | no_license | /**
* Base device class for implementing sensors and actuators. Device objects are
* the interface between the Data Vector and the FPGA API.
*
* PRE-CONDITIONS
* #1 The FPGA must be initialized and a session opened before initializing any
* devices. This only needs to be done once for the entire program and not per
* device. The FPGA takes ~1 second to fully initialize even though the
* initialize/open methods return. The caller must sleep to ensure
* initialization completes before initializing any devices.
*
* POST-CONDITIONS
* #1 The FPGA session must be closed and finalized after all devices are no
* longer in use.
*
* IMPLEMENTING A DEVICE
*
* 1. Extend the Device base class to create YourDevice.
* 2. Define struct Config_t, which will contain any device-specific
* configuration (e.g. which DIO pin to use) and will be passed to
* YourDevice on initialization.
* 3. Implement the constructor
* YourDevice (kSession, kPDataVector, kConfig, kRet));
* 4. Implement the run method, which will be called periodically.
*
* See LEDDevice for an example.
*
* USING A DEVICE
*
* 1. Call Device::createNew<YourDevice,
* struct YourDevice::YourConfig> with an initialized
* FPGA session, Data Vector, the relevant device config data, and a
* unique_ptr to store the initialized device pointer in.
* 2. Call YourDevice->run () for each loop of your main periodic thread.
*
* WARNINGS:
*
* #1 In the current FPGA configuration, on initialization the DIO pins are
* set as inputs and have a floating value. Qualitatively, this floating
* value is ~.7 volts. Once the pin is set to be an output pin, this goes
* to 0 or 3.3V, depending on how it is set.
*
* #2 After initializing an FPGA session, the process must wait for at least
* 1 second for it to complete initializaion before initializing any
* devices. Otherwise FPGA commands (e.g. setting a pin as an output in
* with a low value) will be delayed until the FPGA initialization is
* complete. This can result in the pin reading high even though the
* Device has been initialized with a low value.
*/
#ifndef DEVICE_HPP
#define DEVICE_HPP
#include <stdint.h>
#include <memory>
#include "Errors.hpp"
#include "NiFpga.h"
#include "DataVector.hpp"
class Device
{
public:
/**
* Entry point for creating a new device object. Any config validation
* must be done by the specific device constructor. Defined in the
* header so that the templatized functions do not need to each be
* instantiated explicitly.
*
* @param kSession Initialized and open FPGA session.
* @param kDataVector Initialized Data Vector for this node.
* @param kConfig Device's config data.
* @param kPDeviceRet Pointer to return device.
*
* @ret E_SUCCESS Device successfully created.
* E_DATA_VECTOR_NULL Data Vector pointer null.
* [other] Constructor error returned by device.
*/
template <class T_Device, class T_Config>
static Error_t createNew (NiFpga_Session& kSession,
std::shared_ptr<DataVector> kPDataVector,
T_Config kConfig,
std::unique_ptr<T_Device>& kPDeviceRet)
{
Error_t ret = E_SUCCESS;
// Verify Data Vector param not null.
if (kPDataVector == nullptr)
{
return E_DATA_VECTOR_NULL;
}
// Create device.
kPDeviceRet.reset (new T_Device (kSession, kPDataVector, kConfig,
ret));
if (ret != E_SUCCESS)
{
kPDeviceRet.reset (nullptr);
return ret;
}
return E_SUCCESS;
}
/**
* Run device logic once.
*
* @ret E_SUCCESS Device ran successfully.
* [other] Error returned by device.
*/
virtual Error_t run () = 0;;
protected:
/**
* FPGA session.
*/
NiFpga_Session& mSession;
/**
* Data Vector.
*/
std::shared_ptr<DataVector> mPDataVector;
/**
* Constructor. Must be called by derived device constructors.
*/
Device (NiFpga_Session& kSession,
std::shared_ptr<DataVector> kPDataVector);
};
#endif
| true |
5066cde41595b893f3df0657f0ec9cba5916732a | C++ | upupming/algorithm | /upupming/1052.cpp | UTF-8 | 1,327 | 3.125 | 3 | [
"MIT"
] | permissive | /**
1. 统计所有用到的数的下标
2. 将用到的数进行排序
3. 对有序下标分配 next 值
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int address[100005], key[100005], nxt[100005], pos[100005];
int n, head;
// pos 记录 node 的下标,used 记录真正在链表中的下标
vector<int> used;
int cmp(int a, int b) { return key[a] < key[b]; }
int main() {
scanf("%d%d", &n, &head);
for (int i = 0; i < n; i++) {
scanf("%d %d %d", &address[i], &key[i], &nxt[i]);
pos[address[i]] = i;
}
int current = head;
while (current != -1) {
used.push_back(pos[current]);
current = nxt[pos[current]];
}
if (used.size() == 0) {
printf("0 -1\n");
return 0;
}
// sort 空数组会发生 segmentation fault:begin()+1 is past the end()
sort(used.begin(), used.end(), cmp);
printf("%d %05d\n", used.size(), address[used[0]]);
// 注意 used 为空的情况!!!不要把第二个 printf 放在外部
int i;
for (i = 0; i < used.size(); i++) {
if (i != used.size() - 1)
printf("%05d %d %05d\n", address[used[i]], key[used[i]], address[used[i+1]]);
else
printf("%05d %d %d\n", address[used[i]], key[used[i]], -1);
}
return 0;
} | true |
a6c98a44224b4bef659051bb76694f9759ef180c | C++ | UnknownGi/Codechef-Solution-Closed- | /Easy/Problem #13 - Little Elephant and Permutations/sol.cpp | UTF-8 | 487 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
#define REPN(i,a,b) for(int i=a; i<b; ++i)
using namespace std;
int main ( ) {
freopen("input.txt", "r", stdin);
int t; scanf("%d", &t);
while ( t-- ) {
int n; scanf("%d", &n);
int a[n];
REPN(i,0,n) scanf("%d", &a[i]);
int local=0, inv=0;
REPN(i,0,n) {
if ( i+1 < n && a[i] > a[i+1] ) ++local;
REPN(j,0,n) {
if ( i!=j && i<j && a[i]>a[j] ) ++inv;
}
}
local==inv? printf("YES\n") : printf("NO\n");
}
}
| true |
3c74308df129006469646f97c327c0863f1b9b65 | C++ | Min1307/Leetcode | /117. Populating Next Right Pointers in Each Node II.cpp | UTF-8 | 759 | 3.34375 | 3 | [] | no_license | //117. Populating Next Right Pointers in Each Node II
class Solution {
public:
Node* connect(Node* root) {
if(!root) return nullptr;
Node *ro = root;
Node * pre = new Node(0);
pre->next = nullptr;
Node * re = pre;
while(root)
{
if(root->left)
{
pre->next = root->left;
pre = pre->next;
}
if(root->right)
{
pre->next = root->right;
pre = pre->next;
}
root = root->next;
if(!root)
{
pre = re;
root = re->next;
re->next = nullptr;
}
}
return ro;
}
}; | true |
13e6ca875fba12cfbadb90cf333225e98c2431f1 | C++ | harshbawari/CP_and_DSA | /CodeForces/Practice/old/turtle.cpp | UTF-8 | 1,351 | 3.3125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int m, n, mat[100][100];
cin >> m >> n;
//Input Matrix
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cin >> mat[i][j];
//Traverse all elements of matrix
//Check for elements present at i-1, j-1, i+1, j+1
//increment count if another 1 found found and continue
int count = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (mat[i][j] == 1)
{
if (i - 1 >= 0 && mat[i - 1][j] == 1)
{
//cout << "1:" << i - 1 << mat[i - 1][j] << endl;
count++;
}
else if (j - 1 >= 0 && mat[i][j - 1] == 1)
{
//cout << "2:" << j - 1 << mat[i - 1][j] << endl;
count++;
}
else if (i + 1 < m && mat[i + 1][j] == 1)
{
//cout << "3:" << i + 1 << mat[i - 1][j] << endl;
count++;
}
else if (j + 1 < n && mat[i][j + 1] == 1)
{
//cout << "4:" << j + 1 << mat[i - 1][j] << endl;
count++;
}
}
}
}
cout << count;
} | true |
f8a1924a2d213e948674dc22fed22adcebbccd67 | C++ | jariasf/Online-Judges-Solutions | /CodeSignal/InterviewPractice/containsDuplicates.cpp | UTF-8 | 426 | 3.078125 | 3 | [] | no_license | /*******************************************
***Problema: Contains Duplicates
***Juez: CodeSignal
***Tipo: Hashing
***Autor: Jhosimar George Arias Figueroa
*******************************************/
bool containsDuplicates(std::vector<int> a) {
int n = a.size();
unordered_set<int> hash;
for( int i = 0 ; i < n ; ++i ){
if( hash.find(a[i]) != hash.end() ) return true;
hash.insert(a[i]);
}
return false;
}
| true |
cb8428db3d40bc99b8e0e24d915c6c6de100f776 | C++ | OmriGrossW/Cyber-Attack | /include/CyberWorm.h | UTF-8 | 694 | 3.015625 | 3 | [] | no_license | #ifndef CYBER_WORM
#define CYBER_WORM
#include <iostream>
#include <string>
#include <vector>
class CyberWorm
{
private:
const std::string cyber_worm_os_;
const std::string cyber_worm_name_;
const int cyber_worm_dormancy_time_;
CyberWorm(); // Prevent the use of an empty constructor
public:
CyberWorm(std::string cyber_worm_os, std::string cyber_worm_name, int cyber_worm_dormancy_time); //constructor
CyberWorm(const CyberWorm& other); //copy constructor;
const std::string get_cyber_worm_os(); //worm os getter
const std::string get_cyber_worm_name(); //worm name getter
const int get_cyber_worm_dormancy_time(); //dormancy time getter
};
#endif
| true |
139b652e7cd96839b03205fabde0403932b2fb7c | C++ | theradeonxt/FastImageEditor | /ImageProcessing/Config/ModuleSetupPerformer.h | UTF-8 | 2,155 | 2.765625 | 3 | [
"MIT"
] | permissive | //! =============================================================================
//! \file
//! \brief
//! This is a sample description
//!
//! =============================================================================
#ifndef IMPROC_MODULE_SETUP_PERFORMER_H
#define IMPROC_MODULE_SETUP_PERFORMER_H
#include "Common.h"
#include "ModuleSetupDetails.hpp" // Note: Do not remove, needed by module implementations
#include <cstdint>
#include <functional>
// Forard declarations
namespace Config {
class ModuleConfig;
}
namespace Config
{
class ModuleSetupPerformer
{
public:
//! \brief Constructor
//! Registers a config for the module associated with the given entry key
//! \param [in] name: The module entryKey (function signature).
//! \param [in] entryPoint: Wrapper object for call abstraction.
ModuleSetupPerformer(const std::string& entryKey, const std::function<int32_t(void**)>& entryPoint);
//! \brief Destructor
~ModuleSetupPerformer(){}
private:
//! \brief Parses the full module name to obtain its real name (without suffixes)
//! and the codepath given by its suffix.
//! \param [in] name: The full module name.
//! \param [out] moduleName: The real module name.
//! \param [out] level: The codepath associated with the suffix.
void extractModuleInfo(const std::string& name, std::string& moduleName, SIMDLevel &level);
//! \brief Adds the given codepath detail to the specified module.
//! \param [in] config: Pointer to the module config.
//! \param [in] level: The codepath detail.
void appendConfigDetails(READWRITE(ModuleConfig*) config, SIMDLevel level);
//! \brief Creates a new config for the given module containing the given codepath detail.
//! \param [in] moduleName: The module real name.
//! \param [in] levelDetails: The codepath detail.
void createConfigWithDetails(const std::string& moduleName, SIMDLevel level);
};
}
#endif /* IMPROC_MODULE_SETUP_PERFORMER_H */
| true |
92855d3a3a303832ff335c9babaf2f129070427f | C++ | aayushvats/CPP_AllKindsOfStuff | /XI/ANI_MAN.CPP | UTF-8 | 3,660 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <dos.h>
int main() {
/* request auto detection */
int gdriver = DETECT, gmode, err;
int radius = 10, x, y, midy;
/* initialize graphic mode */
initgraph(&gdriver, &gmode, "C:\\TURBOC3\\BGI");
err = graphresult();
if (err != grOk) {
/* error occurred */
printf("Graphics Error: %s\n",
grapherrormsg(err));
return 0;
}
x =50;
midy = getmaxy() / 2;
y = midy - 100;
/*
* used 5 stick man (still/image)
* position to get walking animation
*/
while (x < getmaxx() - 25)
{
/* clears graphic screen */
cleardevice();
setlinestyle(SOLID_LINE, 1, 3);
/* road for stick man */
line(0, midy, getmaxx(), midy);
/* image 1 - first position of stick man */
circle(x, y, radius);
line(x, y + radius, x, y + radius + 50);
/* leg design */
line(x, y + radius + 50, x - 10, midy);
line(x, y + radius + 50, x + 10, midy - 30);
line(x + 10, midy - 30, x + 10, midy);
/* hand motion */
line(x, y + radius + 10, x - 15, y + radius + 30);
line(x - 15, y + radius + 30, x + 15, y + radius + 40);
delay(150);
/* image 2 - second position of stick man */
cleardevice();
/* forwarding the position of stick man */
x++;
setlinestyle(SOLID_LINE, 1, 3);
line(0, midy, getmaxx(), midy);
circle(x, y, radius);
line(x, y + radius, x, y + radius + 50);
/* leg design */
line(x, y + radius + 50, x - 15, midy);
line(x, y + radius + 50, x + 10, midy - 30);
line(x + 10, midy - 30, x + 10, midy);
/* hand motion */
line(x, y + radius + 5, x - 10, y + radius + 20);
line(x - 10, y + radius + 20, x - 10, y + radius + 45);
line(x, y + radius + 5, x + 5, y + radius + 25);
line(x + 5, y + radius + 25, x + 15, y + radius + 45);
delay(100);
/* image 3 */
cleardevice();
setlinestyle(SOLID_LINE, 1, 3);
line(0, midy, getmaxx(), midy);
x++;
circle(x, y, radius);
line(x, y + radius, x, y + radius + 50);
/* leg design */
line(x, y + radius + 50, x - 20, midy);
line(x, y + radius + 50, x + 20, midy);
/* hand motion */
line(x, y + radius + 5, x - 20, y + radius + 20);
line(x - 20, y + radius + 20, x - 20, y + radius + 30);
line(x, y + radius + 5, x + 20, y + radius + 25);
line(x + 20, y + radius + 25, x + 30, y + radius + 30);
delay(150);
/* image 4 */
cleardevice();
x++;
setlinestyle(SOLID_LINE, 1, 3);
line(0, midy, getmaxx(), midy);
circle(x, y, radius);
line(x, y + radius, x, y + radius + 50);
/* leg design */
line(x, y + radius + 50, x - 8, midy - 30);
line(x - 8, midy - 30, x - 25, midy);
line(x, y + radius + 50, x + 10, midy - 30);
line(x + 10, midy - 30, x + 12, midy);
/* hand motion */
line(x, y + radius + 5, x - 10, y + radius + 10);
line(x - 10, y + radius + 10, x - 10, y + radius + 30);
line(x, y + radius + 5, x + 15, y + radius + 20);
line(x + 15, y + radius + 20, x + 30, y + radius + 20);
delay(100);
/* image 5 */
cleardevice();
x++;
setlinestyle(SOLID_LINE, 1, 3);
line(0, midy, getmaxx(), midy);
circle(x, y, radius);
line(x, y + radius, x, y + radius + 50);
/* leg design */
line(x, y + radius + 50, x + 3, midy);
line(x, y + radius + 50, x + 8, midy - 30);
line(x + 8, midy - 30, x - 20, midy);
/* hand motion */
line(x, y + radius + 5, x - 15, y + radius + 10);
line(x - 15, y + radius + 10, x - 8, y + radius + 25);
line(x, y + radius + 5, x + 15, y + radius + 20);
line(x + 15, y + radius + 20, x + 30, y + radius + 20);
delay(150);
x++;
}
getch();
/* deallocate memory allocated for graphic screen */
closegraph();
return 0;
} | true |
cb9586a4004cf659cda69c038a48dfbd21156c3c | C++ | GyanPrakashRaj/dsacamp | /13 Tries/max_xor_trie.cpp | UTF-8 | 1,426 | 3.96875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class node{
public:
node *left; //0
node *right; // 1
};
class trie{
node*root;
public:
trie(){
root = new node();
}
void insert(int n){
//bits of that number in the trie
node* temp = root;
for(int i=31;i>=0;i--){
int bit = (n>>i)&1;
if(bit==0){
if(temp->left==NULL){
temp->left = new node();
}
//go to that node
temp = temp->left;
}
else{
if(temp->right==NULL){
temp->right = new node();
}
temp = temp->right;
}
}
//Insertion is Done
}
int max_xor_helper(int value){
int current_ans = 0;
node* temp = root;
for(int j=31;j>=0;j--){
int bit =(value>>j)&1;
if(bit==0){
//find the opp value
if(temp->right!=NULL){
temp = temp->right;
current_ans += (1<<j);
}
else{
temp = temp->left;
}
}
else{
//look for a zero
if(temp->left!=NULL){
temp = temp->left;
current_ans += (1<<j);
}
else{
temp = temp->right;
}
}
}
return current_ans;
}
int max_xor(int *input,int n){
int max_xor = 0;
for(int i=0;i<n;i++){
int value = input[i];
insert(value);
int current_xor = max_xor_helper(value);
max_xor = max(max_xor,current_xor);
}
return max_xor;
}
};
int main(){
int input[] = {3,10,5,25,9,2};
int n = sizeof(input)/sizeof(int);
trie t;
cout<< t.max_xor(input,n)<<endl;
return 0;
}; | true |
e79441d9ddbc9a2e80dedd5e96b0d1f2cfcc9179 | C++ | PineTreePizza/roll-back-engine | /src/core/audio/audio_helper.h | UTF-8 | 1,176 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifndef AUDIO_HELPER_H
#define AUDIO_HELPER_H
#include "../global_dependencies.h"
class AudioHelper {
public:
static void PlayMusic(const std::string &musicId) {
static AssetManager *assetManager = GD::GetContainer()->assetManager;
Mix_PlayMusic(assetManager->GetMusic(musicId), -1);
}
static void StopMusic() {
Mix_HaltMusic();
}
static void PauseMusic() {
Mix_PauseMusic();
}
static void PlaySound(const std::string &soundId) {
static AssetManager *assetManager = GD::GetContainer()->assetManager;
Mix_PlayChannel(-1, assetManager->GetSound(soundId), 0);
}
static void SetMusicVolume(int volume) {
Mix_VolumeMusic(volume);
}
static void SetSoundVolume(int volume) {
static AssetManager *assetManager = GD::GetContainer()->assetManager;
for (auto const &pair : assetManager->GetAllSounds()) {
Mix_Chunk *soundChunk = pair.second;
Mix_VolumeChunk(soundChunk, volume);
}
}
static void SetAllVolume(int volume) {
SetMusicVolume(volume);
SetSoundVolume(volume);
}
};
#endif //AUDIO_HELPER_H
| true |
d0ee73a5e097fa21741ce221a627918b0cd605a4 | C++ | DragonWingsL/Cocos2d-x-Projects | /AircraftWar/Classes/Enemy.h | GB18030 | 2,457 | 2.953125 | 3 | [] | no_license |
// EnemyǷװ˷ɻ
#ifndef __Enemy_H__
#define __Enemy_H__
#include "Common.h"
#include "Bullet.h"
class Enemy : public Sprite
{
public:
enum TYPE{ SMALL, MIDDLE, BIG };
static Enemy* create(TYPE type)
{
Enemy* enemy = new Enemy;
enemy->init(type);
enemy->autorelease();
return enemy;
}
bool init(TYPE type)
{
Sprite::initWithFile(Util::format(type + 1, "Enemy", ".png"));
_type = type;
int hp[] = { 10, 50, 200 };
_hp = hp[type];
// Сɻ256Сɻ4ڴӴϷ
int speed[] = { 256, 128, 50 };
_speed = speed[type];
int damage[] = { 20, 40, 100 };
_damage = damage[type];
_curCD = 0;
int shootCD[] = { 60, 120, 250 };
_shootCD = shootCD[type];
int score[] = { 1000, 3000, 10000 };
_score = score[type];
// ˶л
scheduleUpdate();
return true;
}
void update(float dt)
{
setPositionY( getPositionY() - dt*_speed );
}
bool canFire()
{
_curCD++;
if (_curCD != _shootCD)
return false;
_curCD = 0;
return true;
}
void fire(__Array* bullets)
{
Bullet* b = Bullet::create(_damage);
bullets->addObject(b);
getParent()->addChild(b);
// ӵλҪƫƵԭΪɻêVec2(0, 0)
float off = this->getBoundingBox().size.width / 2;
b->setPosition(this->getPosition()+Vec2(off, 0));
b->runAction(
MoveBy::create(winSize.height/(_speed * 2), Vec2(0, -winSize.height)));
}
// лӵĽӿ
void shoot(__Array* bullets)
{
// лѾͲٷӵ
if (_hp <= 0) return;
if (canFire())
fire(bullets);
}
void killed()
{
// ִбըȻɾ
SpriteFrameCache* cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile(ANI_PLIST_PFBoom);
// __Array* frames = __Array::create();
Vector<SpriteFrame *> frames;
for (int i = 0; i < 18; ++i)
{
char* frameName = Util::format(i + 1, "Boom_", ".png");
SpriteFrame* frame = cache->getSpriteFrameByName(frameName);
frames.pushBack(frame);
}
Animation* animation = Animation::createWithSpriteFrames(frames, .05f);
Animate* animate = Animate::create(animation);
RemoveSelf* remove = RemoveSelf::create();
this->runAction(Sequence::create(animate, remove, NULL));
}
protected:
friend class SceneGame;
int _hp;
TYPE _type;
int _speed;
int _damage;
int _shootCD;
int _curCD;
int _score;
};
#endif
| true |
eb0c98a0a0a75df7412a99608a9539cfccd1e352 | C++ | jmccl/acme-lw | /lib/acme-lw.h | UTF-8 | 2,926 | 2.921875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "acme-exception.h"
#include <ctime>
#include <list>
#include <memory>
namespace acme_lw
{
struct Certificate
{
std::string fullchain;
std::string privkey;
// Note that neither of the 'Expiry' calls below require 'privkey'
// to be set; they only rely on 'fullchain'.
/**
Returns the number of seconds since 1970, i.e., epoch time.
Due to openssl quirkiness on older versions (< 1.1.1?) there
might be a little drift from a strictly accurate result, but
it will be close enough for the purpose of determining
whether the certificate needs to be renewed.
*/
::time_t getExpiry() const;
/**
Returns the 'Not After' result that openssl would display if
running the following command.
openssl x509 -noout -in fullchain.pem -text
For example:
May 6 21:15:03 2018 GMT
*/
std::string getExpiryDisplay() const;
};
struct AcmeClientImpl;
/**
* Each AcmeClient assumes access from a single thread, but different
* instances can be instantiated in different threads.
*/
class AcmeClient
{
public:
/**
The signingKey is the Acme account private key used to sign
requests to the acme CA, in pem format.
*/
AcmeClient(const std::string& signingKey);
~AcmeClient();
/**
The implementation of this function allows Let's Encrypt to
verify that the requestor has control of the domain name.
The callback may be called once for each domain name in the
'issueCertificate' call. The callback should do whatever is
needed so that a GET on the 'url' returns the 'keyAuthorization',
(which is what the Acme protocol calls the expected response.)
Note that this function may not be called in cases where
Let's Encrypt already believes the caller has control
of the domain name.
*/
typedef void (*Callback) ( const std::string& domainName,
const std::string& url,
const std::string& keyAuthorization);
/**
Issue a certificate for the domainNames.
The first one will be the 'Subject' (CN) in the certificate.
throws std::exception, usually an instance of acme_lw::AcmeException
*/
Certificate issueCertificate(const std::list<std::string>& domainNames, Callback);
// Contact the Let's Encrypt production or staging environments
enum class Environment { PRODUCTION, STAGING };
/**
Call once before instantiating AcmeClient.
Note that this calls Let's Encrypt servers and so can throw
if they're having issues.
*/
static void init(Environment env = Environment::PRODUCTION);
// Call once before application shutdown.
static void teardown();
private:
std::unique_ptr<AcmeClientImpl> impl_;
};
}
| true |
48fd1811df03966bc1cb12603be9e8d2f214c054 | C++ | hecongy/Cpp-Primer-Exercises-5th-ed | /ch03/ex3_25.cpp | UTF-8 | 1,310 | 3.84375 | 4 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
//原程序
void index()
{
//以10分为一个分数段统计成绩的数量:0~9, 10~19, ..., 90~99, 100
vector<unsigned> scores(11,0); //11个分数段,全部初始化为0
unsigned grade;
while(cin >> grade){ //读取成绩
if(grade <= 100) //只处理有效的成绩
++scores[grade/10]; //将对应分数段的计数值加1
}
cout<<"Statistics are:"<<endl;
for(int i = 0; i < 11; i ++)
{
if(i!=10)
{
cout<< i*10 <<"~"<<i*10+9<<": "<<scores[i]<<endl;
}
else
{
cout<< "100: "<<scores[i]<<endl;
}
}
}
//迭代器版本
void iteration()
{
//以10分为一个分数段统计成绩的数量:0~9, 10~19, ..., 90~99, 100
vector<unsigned> scores(11,0); //11个分数段,全部初始化为0
unsigned grade;
while(cin >> grade){ //读取成绩
if(grade <= 100) //只处理有效的成绩
++(*(scores.begin()+grade/10)); //将对应分数段的计数值加1
}
cout<<"Statistics are:"<<endl;
for(auto b = scores.cbegin(); b!=scores.cend(); b++)
{
if(b!=scores.cend()-1)
{
cout<< (b-scores.cbegin())*10 <<"~"<<(b-scores.cbegin())*10+9<<": "<<*b<<endl;
}
else
{
cout<< "100: "<<*b<<endl;
}
}
}
int main()
{
iteration();
return 0;
} | true |
66a605b2410b62fb3233b1289f521f94d2cd4135 | C++ | KaiserKatze/win-vc-rtdl | /DllTest/dllmain.cpp | UTF-8 | 2,728 | 2.90625 | 3 | [] | no_license | // dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
// @see: https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
/*
The DLL is being loaded into the virtual address space of
the current process as a result of the process starting up
or as a result of a call to LoadLibrary. DLLs can use
this opportunity to initialize any instance data or to use
the TlsAlloc function to allocate a thread local storage (TLS) index.
The lpReserved parameter indicates whether the DLL is being
loaded statically or dynamically.
*/
case DLL_PROCESS_ATTACH:
/*
The current process is creating a new thread. When this occurs,
the system calls the entry-point function of all DLLs currently
attached to the process. The call is made in the context of
the new thread. DLLs can use this opportunity to initialize
a TLS slot for the thread. A thread calling the DLL entry-point
function with DLL_PROCESS_ATTACH does not call the DLL entry-point
function with DLL_THREAD_ATTACH.
Note that a DLL's entry-point function is called with this value
only by threads created after the DLL is loaded by the process.
When a DLL is loaded using LoadLibrary, existing threads do not
call the entry-point function of the newly loaded DLL.
*/
case DLL_THREAD_ATTACH:
/*
A thread is exiting cleanly.
If the DLL has stored a pointer to allocated memory in a TLS slot,
it should use this opportunity to free the memory.
The system calls the entry-point function of all currently
loaded DLLs with this value. The call is made in the context of
the exiting thread.
*/
case DLL_THREAD_DETACH:
/*
The DLL is being unloaded from the virtual address space of
the calling process because it was loaded unsuccessfully or
the reference count has reached zero (the processes has
either terminated or called FreeLibrary one time for each time
it called LoadLibrary).
The lpReserved parameter indicates whether the DLL is being
unloaded as a result of a FreeLibrary call, a failure to load,
or process termination.
The DLL can use this opportunity to call the TlsFree function
to free any TLS indices allocated by using TlsAlloc and
to free any thread local data.
Note that the thread that receives the DLL_PROCESS_DETACH
notification is not necessarily the same thread that received
the DLL_PROCESS_ATTACH notification.
*/
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
| true |
1470e146229480ef508cbad2830540f60a3de23f | C++ | connerturmon/opengl | /src/include/Camera.h | UTF-8 | 1,194 | 3.015625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
enum CameraDirection
{
FORWARD,
BACK,
LEFT,
RIGHT,
DOWN,
UP
};
class Camera
{
public:
Camera(
glm::vec3 initial_position = glm::vec3(0.0f, 0.0f, 0.0f),
float sensitivity = 0.1f,
float speed = 2.0f);
glm::vec3 getPosition() const { return camera_pos; }
glm::vec3 getFront() const { return camera_front; }
glm::vec3 getUp() const { return camera_up; }
float getYaw() const { return yaw; }
float getPitch() const { return pitch; }
void setSensitivty(float sensitivity) { Camera::sensitivity = sensitivity; }
void setCamSpeed(float speed) { camera_speed = speed; }
glm::mat4 viewMatrix() const
{
return glm::lookAt(
camera_pos,
camera_pos + camera_front,
camera_up);
}
void processInput(CameraDirection direction, float delta_time);
void processMouseInput(float xoffset, float yoffset);
private:
glm::vec3 camera_pos;
glm::vec3 camera_front;
glm::vec3 camera_up;
glm::vec3 world_up;
float yaw, pitch;
float sensitivity;
float camera_speed;
}; | true |
6620968d55bebfae61c58acc05c320b0890d1a33 | C++ | DHANUSH-6/Datastructures | /Sorting DataStructures/MergeSort.cpp | UTF-8 | 1,414 | 3.765625 | 4 | [] | no_license | #include<iostream>
void Merge(int array[], int lowerbound,int mid,int upperbound)
{
int i = lowerbound;
int j = mid+1;
int k = lowerbound;
int temp[50];
while(i<=mid && j<=upperbound)
{
if(array[i]<=array[j])
{
temp[k] = array[i];
i++;
}
else{
temp[k] = array[j];
j++;
}
k++;
}
if(i>mid)
{
while(j<=upperbound)
{
temp[k] = array[j];
j++ , k++;
}
}
else
{
while(i<=mid)
{
temp[k] = array[i];
i++ , k++;
}
}
for (k = lowerbound; k <= upperbound; k++)
{
array[k] = temp[k];
}
}
void MergeSort(int array[], int lowerbound,int upperbound)
{
if(lowerbound<upperbound)
{
int mid= (lowerbound + upperbound) / 2;
MergeSort(array,lowerbound,mid);
MergeSort(array,mid + 1,upperbound);
Merge(array,lowerbound,mid,upperbound);
}
}
int main()
{
int n;
int array[50];
std::cout << "Enter the Total Number of elements needs to be sorted:";
std::cin >> n;
std::cout << "Enter " << n << " Elements:";
for (int i = 0; i < n; i++)
std::cin >> array[i];
MergeSort(array, 0, n-1);
std::cout << "Sorted array is : ";
for (int i = 0; i < n; i++)
std::cout << array[i] << " ";
} | true |
02a9ae8773bd76a2d839546ebb6298ca2cf5269f | C++ | shaharshalev/FANC | /parser.hpp | UTF-8 | 28,526 | 2.53125 | 3 | [] | no_license | #ifndef _PARSER_H
#define _PARSER_H
#include <string>
#include <iostream>
#include <vector>
#include <typeinfo>
#include <sstream>
#include <stdbool.h>
#include <stdlib.h> /* atoi */
#include "output.hpp"
#include "registers.hpp"
#include "bp.hpp"
#include "assembler_coder.hpp"
#include <assert.h> /* assert */
using namespace std;
using namespace output;
extern int yylineno;
extern int yyparse(void);
#define YYSTYPE FanC::Node*
namespace FanC {
class Relop;
class Id;
class BooleanOperation;
class RelationalOperation;
class EqualityOperation;
class Multiplicative;
class Additive;
class Number;
template<typename CheckType, typename InstanceType>
bool isInstanceOf(InstanceType *instance) {
return (dynamic_cast<CheckType *>(instance) != NULL);
}
template<typename CheckType, typename InstanceType1, typename InstanceType2>
bool isSameType(InstanceType1 *instance1, InstanceType2 *instance2) {
return (dynamic_cast<CheckType *>(instance1) != NULL && dynamic_cast<CheckType *>(instance2) != NULL);
}
enum BoolOp {
And, Or
};
enum WhileOp {
Break, Continue
};
enum IdentifierType {
VariableType, FunctionType
};
class Node {
protected:
AssemblerCoder &assembler;
Registers ®isters;
CodeBuffer &codeBuffer;
public:
Node():assembler(AssemblerCoder::getInstance())
,registers(Registers::getInstance())
,codeBuffer(CodeBuffer::instance())
{
}
virtual ~Node(){}
};
//Label Marker- a label creator in some place
class M : public Node {
public:
string label; // the "quad" - label or address in our case it is just a label
M() : label("") {
label = codeBuffer.genLabel();
}
};
class N : public Node {
public:
vector<int> nextList;
N() : nextList() {
nextList = codeBuffer.makelist(assembler.j());//to be patched
}
};
class ReturnType : public Node {
public:
virtual string typeName() = 0;
virtual ReturnType *clone() = 0;
virtual bool canBeAssigned(ReturnType *other) {
return this->typeName() == other->typeName();
}
virtual ~ReturnType() {}
};
class Type : public ReturnType {
public:
virtual string typeName() { return "Error<typeName method was called from Type class>"; }
Type *clone() {
return new Type();
}
virtual ~Type() {}
};
class StringType : public Type {
public:
virtual string typeName() { return "STRING"; }
StringType *clone() {
return new StringType();
}
virtual ~StringType() {}
};
class Void : public ReturnType {
public:
virtual string typeName() { return "VOID"; }
Void *clone() {
return new Void();
}
virtual ~Void() {}
};
class ByteType : public Type {
public:
virtual string typeName() { return "BYTE"; }
ByteType *clone() {
return new ByteType();
}
virtual ~ByteType() {}
};
class IntType : public Type {
public:
virtual string typeName() { return "INT"; }
IntType *clone() {
return new IntType();
}
bool canBeAssigned(ReturnType *other) {
return this->typeName() == other->typeName() || other->typeName() == ByteType().typeName();
}
virtual ~IntType() {}
};
class BooleanType : public Type {
public:
virtual string typeName() { return "BOOL"; }
BooleanType *clone() {
return new BooleanType();
}
virtual ~BooleanType() {}
};
class Statement : public Node {
public:
vector<int> continueList;
vector<int> breakList;
Statement() : Node(), continueList(), breakList() {
}
};
class Statements : public Node {
public:
vector<Statement *> statements;
explicit Statements(Statement *statement) : statements() {
add(statement);
}
Statements *add(Statement *statement) {
statements.push_back(statement);
return this;
}
virtual ~Statements() {
for (vector<Statement *>::iterator it = statements.begin(); it != statements.end(); ++it) {
delete *it;
}
}
};
class Expression : public Node {
public:
ReturnType *type;
vector<int> trueList;
vector<int> falseList;
string registerName;
explicit Expression(ReturnType *_type) : type(_type), trueList(), falseList(), registerName("") {}
virtual Id *isPreconditionable(){}
bool isBoolean() {
return this->type->typeName() == BooleanType().typeName();
}
bool isNumric() {
bool value = isInstanceOf<ByteType>(type) || isInstanceOf<IntType>(type);
return value;
}
virtual ~Expression() {
delete type;
}
};
class Operation : public Node {
public:
virtual ~Operation() {}
};
class BinaryOperation : public Operation {
public:
string op;
explicit BinaryOperation(string text) : op(text) {}
virtual ~BinaryOperation() {}
};
class Relop : public Operation {
public:
string op;
explicit Relop(string text) : op(text) {}
virtual ~Relop() {}
};
class BooleanOperation : public Operation {
public:
BoolOp op;
explicit BooleanOperation(BoolOp o) : op(o) {}
virtual ~BooleanOperation() {
}
};
class BinaryExpression : public Expression {
public:
Expression *leftExp;
Expression *rightExp;
Operation *op;
Id *isPreconditionable() {
Id *id = leftExp->isPreconditionable();
if (id != NULL) return id;
id = rightExp->isPreconditionable();
return id;
}
BinaryExpression(Expression *_leftExp, Expression *_rightExp, Operation *_op)
: Expression(NULL), leftExp(_leftExp), rightExp(_rightExp), op(_op) {
if (isInstanceOf<Relop>(_op)) {
if (leftExp->isNumric() && rightExp->isNumric()) {
this->type = new BooleanType();
string _operation = ((Relop *) _op)->op;
int cmdAddress;
if (_operation == "==") {
cmdAddress = assembler.beq(leftExp->registerName, rightExp->registerName);
} else if (_operation == "!=") {
cmdAddress = assembler.bne(leftExp->registerName, rightExp->registerName);
} else if (_operation == "<=") {
cmdAddress = assembler.ble(leftExp->registerName, rightExp->registerName);
} else if (_operation == "<") {
cmdAddress = assembler.blt(leftExp->registerName, rightExp->registerName);
} else if (_operation == ">=") {
cmdAddress = assembler.bge(leftExp->registerName, rightExp->registerName);
} else { // _operation is >
cmdAddress = assembler.bgt(leftExp->registerName, rightExp->registerName);
}
this->trueList = codeBuffer.makelist(cmdAddress);
this->falseList = codeBuffer.makelist(assembler.j());
registers.regFree(leftExp->registerName);
registers.regFree(rightExp->registerName);
} else {
errorMismatch(yylineno);
exit(1);
}
} else if (isInstanceOf<BooleanOperation>(_op)) {
assert(false);// should go to the second ctor
} else if (isInstanceOf<Multiplicative>(_op) || isInstanceOf<Additive>(_op)) {
if (leftExp->isNumric() && rightExp->isNumric()) {
this->type = getLargerType();
this->registerName = leftExp->registerName;
string _operator = ((BinaryOperation *) _op)->op;
if (isInstanceOf<Multiplicative>(_op)) {
if (_operator == "*") {
assembler.mul(registerName, leftExp->registerName, rightExp->registerName);
} else if (_operator == "/") {
assembler.div(registerName, leftExp->registerName, rightExp->registerName);
}
} else { //Additive
if (_operator == "+")
assembler.addu(registerName, leftExp->registerName, rightExp->registerName);
else {
assembler.subu(registerName, leftExp->registerName, rightExp->registerName);
}
}
} else {
errorMismatch(yylineno);
exit(1);
}
if (this->type->typeName() == ByteType().typeName()) {
assembler.andi(registerName, registerName, 255);
}
registers.regFree(rightExp->registerName);
}
}
BinaryExpression(Expression *_leftExp, Expression *_rightExp, BooleanOperation *_op, M *beforeRhsMarker)
: Expression(NULL), leftExp(_leftExp), rightExp(_rightExp), op(_op) {
if (leftExp->isBoolean() && rightExp->isBoolean()) {
this->type = new BooleanType();
BoolOp b = _op->op;
switch (b) {
case And:
assembler.comment("start-AND backpatching:");
codeBuffer.bpatch(leftExp->trueList,beforeRhsMarker->label);
this->trueList=rightExp->trueList;
this->falseList=codeBuffer.merge(leftExp->falseList,rightExp->falseList);
assembler.comment("end- AND backpatching:");
registers.regFree(leftExp->registerName);
registers.regFree(rightExp->registerName);
break;
case Or:
codeBuffer.bpatch(leftExp->falseList,beforeRhsMarker->label);
this->falseList=rightExp->falseList;
this->trueList=codeBuffer.merge(leftExp->trueList,rightExp->trueList);
registers.regFree(leftExp->registerName);
registers.regFree(rightExp->registerName);
break;
}
} else {
errorMismatch(yylineno);
exit(1);
}
}
private:
ReturnType *getLargerType() {
if (isSameType<ByteType>(leftExp->type, rightExp->type)
|| isSameType<IntType>(leftExp->type, rightExp->type)) {
return leftExp->type->clone();
} else {
return new IntType();
}
}
public:
virtual ~BinaryExpression() {
delete leftExp;
delete rightExp;
delete op;
}
};
class UnaryExpression : public Expression {
public:
explicit UnaryExpression(ReturnType *_type) : Expression(_type) {}
virtual ~UnaryExpression() {}
};
class Not : public UnaryExpression {
public:
Expression *exp;
explicit Not(Expression *_exp) : UnaryExpression(new BooleanType()), exp(_exp) {
if (!exp->isBoolean()) {
errorMismatch(yylineno);
exit(1);
}
trueList = exp->falseList;
falseList = exp->trueList;
}
Id *isPreconditionable() {
return NULL;
}
virtual ~Not() {
delete (exp);
};
};
class Multiplicative : public BinaryOperation {
public:
explicit Multiplicative(string text) : BinaryOperation(text) {}
virtual ~Multiplicative() {}
};
class Additive : public BinaryOperation {
public:
explicit Additive(string text) : BinaryOperation(text) {}
virtual ~Additive() {}
};
class RelationalOperation : public Relop {
public:
explicit RelationalOperation(string text) : Relop(text) {}
virtual ~RelationalOperation() {}
};
class EqualityOperation : public Relop {
public:
explicit EqualityOperation(string text) : Relop(text) {}
virtual ~EqualityOperation() {}
};
class Boolean : public UnaryExpression {
public:
bool value;
explicit Boolean(bool val) : UnaryExpression(new BooleanType()), value(val) {
if (val) {
trueList = codeBuffer.makelist(assembler.j());
} else {
falseList = codeBuffer.makelist(assembler.j());
}
}
Id *isPreconditionable() {
return NULL;
}
virtual ~Boolean() {
}
};
class Id : public UnaryExpression {
public:
string name;
int offset;
IdentifierType idType;
friend bool operator==(const Id &, const Id &);
friend bool operator!=(const Id &, const Id &);
explicit Id(string text) : UnaryExpression(new Type()), name(text), idType(VariableType) {}
Id(string text, ReturnType *_type, IdentifierType _idType) : UnaryExpression(_type),
name(text), idType(_idType) {}
explicit Id(Id *id) : UnaryExpression(id->type->clone()) {
name = id->name;
offset = id->offset;
idType = id->idType;
}
Id *isPreconditionable() {
if (offset < 0)return NULL;
return this;
}
Id *changeIdTypeToFunction() {
idType = FunctionType;
return this;
}
Id *updateType(Type *t) {
delete this->type;
this->type = t;
return this;
}
bool isFunction() {
return idType == FunctionType;
}
virtual ~Id() {}
};
class String : public UnaryExpression {
public:
string value;
string label;
explicit String(string text) : UnaryExpression(new StringType()), value(text), label("") {
//label = CodeBuffer::instance().genLabel();
label = assembler.genDataLabel();
assembler.emitStringToDataForString(label, value);
registerName = registers.regAlloc();
assembler.la(registerName, label);
}
Id *isPreconditionable() {
return NULL;
}
virtual ~String() {}
};
class Number : public UnaryExpression {
public:
int value;
Number(string text, Type *_type) : UnaryExpression(_type), value(atoi(text.c_str())) {}
Number(int val, Type *_type) : UnaryExpression(_type), value(val) {
registerName = registers.regAlloc();
assembler.li(registerName, val);
}
Id *isPreconditionable() {
return NULL;
}
virtual ~Number() {
}
};
class Integer : public Number {
public:
explicit Integer(Number *n) : Number(n->value, new IntType()) {
delete n;
}
virtual ~Integer() {
}
};
class Byte : public Number {
public:
explicit Byte(Number *num) : Number(num->value, new ByteType()) {
delete num; //check
if (value > 255) {
stringstream stream;
stream << value;
errorByteTooLarge(yylineno, stream.str());
exit(1);
}
}
virtual ~Byte() {}
};
class FormalDec : public Node {
public:
Type *type;
Id *id;
FormalDec(Type *_type, Id *_id) : type(_type), id(_id) {
}
virtual ~FormalDec() {
delete type;
}
};
class FormalList : public Node {
public:
vector<FormalDec *> decelerations;
FormalList() {}
explicit FormalList(FormalDec *formalDec) {
add(formalDec);
}
FormalList *add(FormalDec *formalDec) {
decelerations.insert(decelerations.begin(), formalDec);
return this;
}
int size() { return decelerations.size(); }
virtual ~FormalList() {}
};
class PreCondition : public Node {
public:
Expression *exp;
explicit PreCondition(Expression *_exp,M* trueMarker) : exp(_exp) {
codeBuffer.bpatch(exp->trueList,trueMarker->label);
}
Id *isExpressionValid() {
return exp->isPreconditionable();
}
virtual ~PreCondition() {
delete exp;
}
};
class PreConditions : public Node {
public:
vector<PreCondition *> preconditions;
PreConditions() {}
PreConditions *add(PreCondition *precond) {
preconditions.insert(preconditions.begin(), precond);
return this;
}
int size() {
return preconditions.size();
}
Id *isValid() {
vector<PreCondition *>::iterator it = preconditions.begin();
while (it != preconditions.end()) {
Id *i = (*it)->isExpressionValid();
if (i != NULL)
return i;
++it;
}
return NULL;
}
virtual ~PreConditions() {
for (vector<PreCondition *>::iterator it = preconditions.begin(); it != preconditions.end(); ++it) {
delete *it;
}
}
};
class ExpressionList : public Node {
public:
vector<Expression *> expressions;
ExpressionList() {}
explicit ExpressionList(Expression *exp) {
expressions.insert(expressions.begin(), exp);
}
ExpressionList *add(Expression *exp) {
expressions.insert(expressions.begin(), exp);
return this;
}
virtual ~ExpressionList() {
for (vector<Expression *>::iterator it = expressions.begin(); it != expressions.end(); ++it) {
delete *it;
}
}
};
class FuncDec : public Node {
public:
ReturnType *returnType;
Id *id;
FormalList *arguments;
PreConditions *conditions;
friend bool operator==(const FuncDec &, const FuncDec &);
friend bool operator!=(const FuncDec &, const FuncDec &);
FuncDec(ReturnType *_returnType,
Id *_id, FormalList *_arguments,
PreConditions *_conditions) : returnType(_returnType),
id(_id),
arguments(_arguments),
conditions(_conditions) {}
vector<string> *getArgsAsString() {
vector<FormalDec *>::iterator it = this->arguments->decelerations.begin();
vector<string> *typesName = new vector<string>();
while (it != arguments->decelerations.end()) {
typesName->push_back((*it)->type->typeName());
++it;
}
return typesName;
}
bool isArgumentListMatch(ExpressionList *expList) {
vector<Expression *>::iterator expIt = expList->expressions.begin();
vector<FormalDec *>::iterator formalIt = this->arguments->decelerations.begin();
while ((expIt != expList->expressions.end()) && (formalIt != arguments->decelerations.end())) {
Expression *currentExp = *expIt;
FormalDec *currentArgument = *formalIt;
if (!currentArgument->type->canBeAssigned(currentExp->type))
return false;
++expIt;
++formalIt;
}
if (expIt == expList->expressions.end() && formalIt == arguments->decelerations.end())
return true;
return false;
}
virtual ~FuncDec() {
delete returnType;
delete id;
delete arguments;
delete conditions;
}
};
class Call : public UnaryExpression {
public:
Id *id;
ExpressionList *expressions;
Call(ReturnType *_returnType, Id *_id, ExpressionList *_expressions)
: UnaryExpression(_returnType->clone()), id(_id), expressions(_expressions) {
assembler.comment("call to function - saving regs");
vector<string> used = registers.getUsedRegisters();
saveAndFreeRegs(used);
assembler.subu("$sp", "$sp", WORD_SIZE * 2);
assembler.sw("$fp", WORD_SIZE, "$sp");
assembler.sw("$ra", 0, "$sp");
int argsSize = expressions->expressions.size();
assembler.subu("$sp", "$sp", WORD_SIZE * argsSize);
for (int i = 0; i < argsSize; i++) {
string ® = expressions->expressions[i]->registerName;
assembler.sw(reg, i * WORD_SIZE, "$sp");
Registers::getInstance().regFree(reg);
}
assembler.subu("$fp","$sp",WORD_SIZE);//we didnt load the new fp
assembler.comment("jump to function - " + id->name);
assembler.jal(id->name);
assembler.comment("return from functionn - " + id->name + " restoring the regs");
assembler.addu("$sp", "$sp", WORD_SIZE * argsSize);
assembler.lw("$ra", 0, "$sp");
assembler.lw("$fp", WORD_SIZE, "$sp");
assembler.addu("$sp", "$sp", WORD_SIZE * 2);
restoreRegs(used);
assembler.comment("end Call");
}
Id *isPreconditionable() {
vector<Expression *>::iterator it = expressions->expressions.begin();
while (it != expressions->expressions.end()) {
Id *i = (*it)->isPreconditionable();
if (NULL != i)
return i;
++it;
}
return NULL;
}
virtual ~Call() {
delete expressions;
delete id;
}
private:
void restoreRegs(vector<string> ®s) {
assembler.comment("restore all used regs");
for (int i = 0; i < regs.size(); i++) {
assembler.lw(regs[i], WORD_SIZE * i, "$sp");
//registers.markAsUsed(regs[i]);
}
assembler.addu("$sp", "$sp", regs.size() * WORD_SIZE);
}
void saveAndFreeRegs(vector<string> ®s) {
assembler.comment("save all used regs");
assembler.subu("$sp", "$sp", regs.size() * WORD_SIZE);
for (int i = 0; i < regs.size(); i++) {
assembler.sw(regs[i], WORD_SIZE * i, "$sp");
//registers.regFree(regs[i]);
}
}
};
class Scope {
public:
vector<Id *> variables;
vector<FuncDec *> functions;
Scope *parent;
Scope() : variables(), functions(), parent(NULL) {
}
explicit Scope(Scope *_parent) : parent(_parent) {}
void addVariable(Id *id) {
variables.push_back(id);
}
void addFunction(FuncDec *func) {
func->id->changeIdTypeToFunction();
functions.push_back(func);
Id *i = new Id(func->id);
variables.push_back(i);
}
private:
bool isFunctionExistInScope(FuncDec *func) {
vector<FuncDec *>::iterator it = functions.begin();
while (it != functions.end()) {
FuncDec *currentFunc = *it;
if (*func == *currentFunc)
return true;
++it;
}
return false;
}
FuncDec *getFunctionInScope(Id *id) {
for (vector<FuncDec *>::iterator it = functions.begin(); it != functions.end(); ++it) {
FuncDec *currentFunc = *it;
if (*currentFunc->id == *id) {
return *it;
}
}
return NULL;
}
public:
/**
* the method check if function exist in this scope or above.
* @param func is the function
* @return true if exists, false otherwise
*/
bool isFunctionExist(FuncDec *func) {
if (isFunctionExistInScope(func)) {
return true;
} else if (NULL != parent) {
return parent->isFunctionExist(func);
} else {
return false;
}
}
virtual FuncDec *getFunction(Id *id) {
FuncDec *found = getFunctionInScope(id);
if (NULL != found) {
return found;
} else if (NULL != parent) {
return parent->getFunction(id);
} else {
return NULL;
}
}
private:
Id *getVariableInScope(Id *id) {
vector<Id *>::iterator it = variables.begin();
while (it != variables.end()) {
Id *currentId = *it;
if (*id == *currentId)
return *it;
++it;
}
return NULL;
}
public:
/**
* the method gets a variable/function Id from this scope or parents scopes.
* @param id
* @return the id from the symbolTable, NULL if no such id exist
*/
Id *getVariable(Id *id) {
Id *found = getVariableInScope(id);
if (NULL != found) {
return found;
} else if (NULL != parent) {
return parent->getVariable(id);
} else {
return NULL;
}
}
void printIds() {
for (vector<Id *>::iterator it = variables.begin(); it != variables.end(); ++it) {
if ((*it)->isFunction()) {
FuncDec *fun = getFunction(*it);
vector<string> *args = fun->getArgsAsString();
string func_type = makeFunctionType(fun->returnType->typeName(), *args);
delete args;
//output::printID((*it)->name, 0, func_type);
} else {
//output::printID((*it)->name, (*it)->offset, (*it)->type->typeName());
}
}
}
virtual void endScope() {
//output::endScope();
printIds();
}
virtual ~Scope() {
for (vector<Id *>::iterator it = variables.begin(); it != variables.end(); ++it) {
delete *it;
}
for (vector<FuncDec *>::iterator it = functions.begin(); it != functions.end(); ++it) {
delete *it;
}
}
};//End of class Scope
class WhileScope : public Scope {
public:
explicit WhileScope(Scope *_parent) : Scope(_parent) {}
virtual ~WhileScope() {}
};
class FunctionScope : public Scope {
public:
FuncDec *func;
explicit FunctionScope(Scope *_parent) : Scope(_parent), func(NULL) {}
void updateFunctionScope(FuncDec *_func) {
func = _func;
if (NULL != this->parent)
parent->addFunction(_func);
}
void updateFunctionScope(PreConditions *preconditions) {
func->conditions = preconditions;
}
FuncDec *getFunction() {
return func;
}
void endScope() {
//output::endScope();
//output::printPreconditions(func->id->name, func->conditions->size());
printIds();
}
virtual ~FunctionScope() {}
};
}
#endif //_PARSER_H | true |
f9071c531caa6358773f70fcb1f4d17cd84d0563 | C++ | Alleno/exercism | /cpp/sieve/sieve.cpp | UTF-8 | 845 | 3.515625 | 4 | [] | no_license | #include "sieve.h"
#include <numeric>
namespace sieve {
std::vector<int> primes(int upto)
{
std::vector<int> all_values(upto-1); // or should we just default init and then call .reserve?
std::iota(all_values.begin(), all_values.end(), 2);
for (auto val : all_values)
{
if (val == 0) continue;
int index = val - 2;
for (std::vector<int>::size_type i = index+val; i < all_values.size(); i += val)
{
all_values[i] = 0;
}
}
auto new_end = remove_if(all_values.begin(), all_values.end(), [](int x) { return x == 0; });
all_values.erase(new_end, all_values.end());
return all_values; //https://stackoverflow.com/questions/15704565/efficient-way-to-return-a-stdvector-in-c
}
} // namespace sieve
| true |
b13ee238460765fd359706a50c6ebb509a362f13 | C++ | spinos/gorse | /core/grd/LocalGridLookupRule.h | UTF-8 | 7,105 | 2.578125 | 3 | [] | no_license | /*
* LocalGridLookupRule.h
* gorse
*
* first find cell by bvh
* then find closest primitve in cell
*
* 2019/8/10
*/
#ifndef ALO_GRD_LOCAL_GRID_LOOK_UP_RULE_H
#define ALO_GRD_LOCAL_GRID_LOOK_UP_RULE_H
#include <bvh/BVH.h>
#include <bvh/BVHRayTraverseRule.h>
#include <math/rayBox.h>
namespace alo {
namespace grd {
struct LocalGridPrimitveLookupResult {
Int2 _instanceRange;
int _instanceId;
float _q[3];
int _u[3];
Vector3F _nml;
float _t0;
LocalGridPrimitveLookupResult()
{
_instanceRange.set(0,0);
_instanceId = -1;
}
bool isEmptySpace() const
{ return _instanceRange.x >= _instanceRange.y; }
bool hasInstanceRange() const
{ return _instanceRange.x < _instanceRange.y; }
};
struct LocalGridLookupResult {
bvh::RayTraverseResult _rayBvh;
LocalGridPrimitveLookupResult _primitive;
};
template<typename T, typename Tp>
class LocalGridLookupRule {
const T *m_grid;
bvh::RayTraverseRule m_rayBvhRule;
const Tp *m_primitiveRule;
int m_maxNumStep;
const float *m_originCellSize;
float m_invCellSize;
float m_delta;
int m_dim[3];
public:
typedef LocalGridLookupResult LookupResultTyp;
typedef LocalGridPrimitveLookupResult PrimitiveResultTyp;
LocalGridLookupRule();
void setPrimitiveRule(const Tp *x);
void attach(const T *grid);
void detach();
bool isEmpty() const;
bool lookup(LocalGridLookupResult &result, const float *rayData) const;
float mapDistance(LocalGridPrimitveLookupResult &result, const float *q) const;
void mapNormal(LocalGridPrimitveLookupResult &result, const float *q) const;
void setMaxNumStep(const int &x);
protected:
private:
bool processLeaf(LocalGridLookupResult &result, const float *rayData) const;
/// among cells in a leaf
int findClosestHit(bvh::RayTraverseResult &result, float *t, float *rayD) const;
bool intersectPrimitive(LocalGridPrimitveLookupResult &result,
const float *tLimit,
const float *rayData) const;
void computeCellCoord(int* u, const float* p) const;
int computeCellInd(const int* u) const;
};
template<typename T, typename Tp>
LocalGridLookupRule<T, Tp>::LocalGridLookupRule() : m_grid(nullptr),
m_maxNumStep(128)
{}
template<typename T, typename Tp>
void LocalGridLookupRule<T, Tp>::setPrimitiveRule(const Tp *x)
{ m_primitiveRule = x; }
template<typename T, typename Tp>
void LocalGridLookupRule<T, Tp>::attach(const T *grid)
{
m_originCellSize = grid->originCellSize();
m_invCellSize = 1.f / m_originCellSize[3];
m_delta = 1e-3f * m_originCellSize[3];
const int d = grid->resolution();
m_dim[0] = d;
m_dim[1] = d * d;
m_dim[2] = m_dim[0] - 1;
m_rayBvhRule.attach(grid->boundingVolumeHierarchy());
m_grid = grid;
}
template<typename T, typename Tp>
void LocalGridLookupRule<T, Tp>::detach()
{
m_grid = nullptr;
}
template<typename T, typename Tp>
bool LocalGridLookupRule<T, Tp>::isEmpty() const
{ return m_grid == nullptr; }
template<typename T, typename Tp>
bool LocalGridLookupRule<T, Tp>::lookup(LocalGridLookupResult &result, const float *rayData) const
{
bvh::RayTraverseResult &bvhResult = result._rayBvh;
m_rayBvhRule.begin(bvhResult);
for(;;) {
m_rayBvhRule.traverse(bvhResult, rayData);
if(m_rayBvhRule.end(bvhResult) ) break;
if(processLeaf(result, rayData) ) return true;
}
return false;
}
template<typename T, typename Tp>
bool LocalGridLookupRule<T, Tp>::processLeaf(LocalGridLookupResult &result, const float *rayData) const
{
bvh::RayTraverseResult &bvhResult = result._rayBvh;
LocalGridPrimitveLookupResult &primitiveResult = result._primitive;
float tmpRay[8];
memcpy(tmpRay, rayData, 32);
tmpRay[6] = bvhResult._t0;
tmpRay[7] = bvhResult._t1;
float t[2];
for(int i=bvhResult._primBegin;i<bvhResult._primEnd;++i) {
int firstHit = findClosestHit(bvhResult, t, tmpRay);
if(firstHit < 0) break;
t[0] += m_delta;
const int &celli = m_grid->primitiveIndex(firstHit);
const int vi = m_grid->hasCell(celli);
if(vi < 0)
primitiveResult._instanceRange.set(0, m_grid->numObjects());
else
primitiveResult._instanceRange = m_grid->c_mappedCell(vi);
if(intersectPrimitive(primitiveResult, t, rayData)) return true;
/// advance to exit point
tmpRay[6] = t[1] + m_delta;
tmpRay[7] = bvhResult._t1;
}
return false;
}
template<typename T, typename Tp>
int LocalGridLookupRule<T, Tp>::findClosestHit(bvh::RayTraverseResult &result, float *t, float *rayD) const
{
const float t0 = rayD[6];
const float t1 = rayD[7];
int prim = -1;
t[0] = 1e10f;
for(int i=result._primBegin;i<result._primEnd;++i) {
const float *primBox = (const float *)&m_grid->primitiveBox(i);
if(rayAabbIntersect(rayD, primBox)) {
if(t[0] > rayD[6]) {
/// closer
t[0] = rayD[6];
t[1] = rayD[7];
prim = i;
}
}
rayD[6] = t0;
rayD[7] = t1;
}
return prim;
}
template<typename T, typename Tp>
bool LocalGridLookupRule<T, Tp>::intersectPrimitive(LocalGridPrimitveLookupResult &result,
const float *tLimit,
const float *rayData) const
{
float tt = tLimit[0];
for(int i=0;i<m_maxNumStep;++i) {
rayProgress(result._q, rayData, tt);
float d = m_primitiveRule->mapDistance(result._q,
m_grid->c_indices(), result._instanceRange,
result._instanceId);
if(d < m_delta) break;
if(d < tt * 1e-5f) break;
tt += d * .8f;
if(tt > tLimit[1]) return false;
}
m_primitiveRule->mapNormal(result._nml, result._q,
result._instanceId);
result._t0 = tt;
return true;
}
template<typename T, typename Tp>
void LocalGridLookupRule<T, Tp>::setMaxNumStep(const int &x)
{ m_maxNumStep = x; }
template<typename T, typename Tp>
void LocalGridLookupRule<T, Tp>::computeCellCoord(int* u, const float* p) const
{
u[0] = (p[0] - m_originCellSize[0]) * m_invCellSize;
u[1] = (p[1] - m_originCellSize[1]) * m_invCellSize;
u[2] = (p[2] - m_originCellSize[2]) * m_invCellSize;
Clamp0b(u[0], m_dim[2]);
Clamp0b(u[1], m_dim[2]);
Clamp0b(u[2], m_dim[2]);
}
template<typename T, typename Tp>
int LocalGridLookupRule<T, Tp>::computeCellInd(const int* u) const
{ return (u[2]*m_dim[1] + u[1]*m_dim[0] + u[0]); }
template<typename T, typename Tp>
float LocalGridLookupRule<T, Tp>::mapDistance(LocalGridPrimitveLookupResult &result, const float *q) const
{
memcpy(result._q, q, 12);
movePointOntoBox(result._q, m_grid->fieldAabb() );
computeCellCoord(result._u, result._q);
const int celli = computeCellInd(result._u);
const int vi = m_grid->hasCell(celli);
if(vi < 0)
result._instanceRange.set(0, m_grid->numObjects());
else
result._instanceRange = m_grid->c_mappedCell(vi);
return m_primitiveRule->mapDistance(q,
m_grid->c_indices(), result._instanceRange,
result._instanceId);
}
template<typename T, typename Tp>
void LocalGridLookupRule<T, Tp>::mapNormal(LocalGridPrimitveLookupResult &result, const float *q) const
{
mapDistance(result, q);
m_primitiveRule->mapNormal(result._nml, result._q,
result._instanceId);
}
} /// end of namepsace grd
} /// end of namespace alo
#endif
| true |
a88ceedeff73102a6193cf9f35e4dddc510ecce9 | C++ | DimaPhil/ITMO | /Cpp/year2013/list/List/node.cpp | UTF-8 | 697 | 3.46875 | 3 | [] | no_license | #include "node.h"
#include <string>
using std::string;
node::node()
{
this->value = "";
this->next = this;
this->previous = this;
}
node::node(string const& value)
{
this->value = value;
this->next = this;
this->previous = this;
}
node::node(string const& value, node *previous, node *next)
{
this->value = value;
this->previous = previous;
this->next = next;
}
node::node(const node &other)
{
this->value = other.value;
this->next = other.next;
this->previous = other.previous;
}
node& node::operator = (const node &other)
{
this->value = other.value;
this->next = other.next;
this->previous = other.previous;
return *this;
}
| true |
1863257f18162f86c433c88a431c48df9539c75a | C++ | rushingJustice/C-programming-and-matlab-projects | /Finite Elements - Direct Sitffness Methods/Programs from E-book/Example13_1_1/main.cpp | UTF-8 | 587 | 2.6875 | 3 | [] | no_license | /*********************************************
Example 13.1.1
Copyright(c) 2005-06, S. D. Rajan
Object-Oriented Numerical Analysis
*********************************************/
#include "isection.h"
int main ()
{
CISection First ("W36X300", 88.3f, 1110.0f, 156.0f, 300.0f);
First.Display ();
CISection Second ("W21X201", 59.2f, 461.0f, 86.1f, 201.0f);
Second.Display ();
CISection Third;
Third.SetProperties ("W12X336", 98.8f, 483.0f, 177.0f, 336.0f);
Third.Display ();
CISection Fourth (Second);
// Fourth.Set (Second); // alternate way
Fourth.Display ();
return 0;
} | true |
13f5b7ccf690b23290d546e0aa6db74795fbb828 | C++ | Egoushka/University | /II course/Data Calculation System/3/DataCalculatingSystem_3-main/Project11/Source.cpp | WINDOWS-1251 | 18,070 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <windows.h>
#include <locale.h>
#include <regex>
#include <map>
int calculateSize(std::ifstream&);
void controller();
void firstEx();
void additionFirstEx();
void secondEx();
void additionSecondEx();
void thirdEx();
void additionThirdEx();
void additionThirdEx2();
void additionThirdEx3();
void fourEx();
void additionFourEx();
void fifth();
int main() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
controller();
return 0;
}
void controller() {
int choice;
std::cout << "Enter the exercice\n";
std::cin >> choice;
std::cin.ignore();
switch (choice) {
case 1: {
// ( Shakespeare_Winter'sTale.txt);
firstEx();
break;
}
case 2: {
// 1.1;
additionFirstEx();
break;
}
case 3: {
//
secondEx();
break;
}
case 4: {
// 1.2
additionSecondEx();
break;
}
case 5: {
// 3.3.
thirdEx();
break;
}
// 1.3 1.4.
case 6: {
additionThirdEx();
break;
}
case 7: {
additionThirdEx2();
break;
}
case 8: {
additionThirdEx3();
break;
}
case 9: {
// 3.4. ;
fourEx();
break;
}
case 10: {
// 1.5 1.6;
additionFourEx();
break;
}
case 11: {
//
fifth();
break;
}
default:
break;
}
}
int calculateSize(std::ifstream& someFile) {
someFile.seekg(0, std::ios::end);
int size = someFile.tellg();
someFile.seekg(0, std::ios::beg);
return size;
}
void firstEx() {
int length;
char* buffer;
char separators[]{'.','!',';'};
int separatorsLenght = 3;
std::ifstream ist("Shakespeare_WintersTale.txt");
if (!ist.is_open()) {
std::cout<< "Opens error\n";
return;
}
length = calculateSize(ist);
buffer = new char[length];
ist.read(buffer, length);
ist.close();
//start - ,
//end -
for (int index = 0,start = 0, end; buffer[index] != 0; ++index) {
// , start < end
if (buffer[index] == '?') {
end = index + 1;
while (start != end) {
std::cout<< buffer[start];
start++;
}
start++;
std::cout<< '\n';
}
for (int separatorIndex = 0; separatorIndex < separatorsLenght; ++separatorIndex) {
if (separators[separatorIndex] == buffer[index]) {
start = index + 1;
}
}
}
delete[] buffer;
}
void additionFirstEx() {
int length;
char* buffer;
char separators[]{ '.','?',';' };
int separatorsLenght = 3;
std::ifstream ist("text.txt");
std::ofstream os("text2.txt");
if (!ist.is_open() || !os.is_open()) {
std::cout<< "Opens error\n";
return;
}
length = calculateSize(ist);
buffer = new char[length];
ist.read(buffer, length);
ist.close();
for (int index = 0, start = 0, end; buffer[index] != 0; ++index) {
if (buffer[index] == '!') {
end = index + 1;
while (start != end) {
// ,
os << buffer[start];
start++;
}
start++;
std::cout<< '\n';
}
for (int separatorIndex = 0; separatorIndex < separatorsLenght; ++separatorIndex) {
if (separators[separatorIndex] == buffer[index]) {
start = index + 1;
}
}
}
delete[] buffer;
}
void secondEx() {
{
std::ofstream os("z3.dat", std::ios::binary);
if (!os.is_open()) {
std::cout << "Opens error\n";
return;
}
const int intsArrSize = 10;
const int charsArrSize = 5;
double doubleNum1 = 36.14;
double doubleNum2 = 0.3543;
int intsArr[intsArrSize];
char charsArr[charsArrSize];
// :)
for (int index = 0; index < intsArrSize; ++index)
intsArr[index] = index;
for (int index = 0; index < charsArrSize; ++index)
charsArr[index] = 70 + index;
// 16 (double - 8 byte)
os.write((char*)&doubleNum1, sizeof(doubleNum1));
os.write((char*)&doubleNum2, sizeof(doubleNum2));
// os.write((char*)intsArr, intArrSize * sizeof(int));
// - 10 , 4 * 10
for (int index = 0; index < intsArrSize; ++index)
os.write((char*)&intsArr[index], sizeof(intsArr[index]));
//2 * 5
for (int index = 0; index < charsArrSize; ++index)
os.write((char*)&charsArr[index], sizeof(charsArr[index]));
os.close();
{
std::ifstream ist("z3.dat", std::ios::binary);
if (!ist.is_open()) {
std::cout << "Opens error\n";
}
ist.seekg(0, std::ios::end);
int lenght = ist.tellg();
std::cout << lenght << '\n';
ist.close();
std::ofstream os("z3.dat", std::ios::binary | std::ios::app);
if (!os.is_open()) {
std::cout << "Opens error\n";
}
os.write((char*)&lenght, sizeof(lenght));
os.close();
}
}
}
void additionSecondEx() {
std::ofstream os("z3.dat", std::ios::binary);
std::ifstream ist("Shakespeare_WintersTale.txt", std::ios::binary );
if (!(os.is_open())&&ist.is_open()) {
std::cout<< "Opens error\n";
return;
}
int bufSize;
char* buf;
ist.seekg(0, std::ios::end);
bufSize = ist.tellg();
ist.seekg(0, std::ios::beg);
buf = new char[bufSize];
ist.read(buf, bufSize);
os.write((char*)buf, sizeof(char) * bufSize);
os.close();
}
void thirdEx() {
const int arrSize = 10;
int arr[arrSize];
for (int index = 0; index < arrSize; ++index) {
arr[index] = index;
}
std::ofstream ofs("z3_3.txt", std::ios::binary );
if (!ofs.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
ofs.write((char*)arr, sizeof(arr));
ofs.close();
int newNum;
int numIndex;
std::cout<< "Enter the number and its index\n";
std::cin >> newNum >> numIndex;
std::fstream fst("z3_3.txt", std::ios::binary | std::ios::in | std::ios::out);
if (!fst.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
fst.seekg(0, std::ios::end);
int lenght = fst.tellg();
std::cout<< "The file size ist: " << lenght << "bytes\n";
int possition = numIndex * sizeof(int);
std::cout<< "Position of the edited element: " << possition << '\n';
fst.seekp(possition, std::ios::beg);
fst.write((char*)&newNum, sizeof(int));
fst.seekg(0);
fst.read((char*)&arr, sizeof(arr));
for (int index = 0; index < arrSize; ++index)
std::cout<< arr[index] << " ";
}
void additionThirdEx() {
int arrSize;
std::cout<< "Enter the size of array\n";
std::cin >> arrSize;
int* arr = new int[arrSize];
for (int index = 0; index < arrSize; ++index) {
arr[index] = index;
}
std::ofstream ofs("z3_3.txt", std::ios::binary );
if (!ofs.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
//
ofs.write((char*)arr, sizeof(arr) * arrSize);
ofs.close();
int newNum;
int numIndex;
std::fstream fst("z3_3.txt", std::ios::binary | std::ios::in | std::ios::out);
std::cout<< "Enter the number and its index\n";
std::cin >> newNum >> numIndex;
if (!fst.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
fst.seekg(0, std::ios::end);
int lenght = fst.tellg();
std::cout<< "The file size ist: " << lenght << "bytes\n";
//
int possition = numIndex * sizeof(int);
std::cout<< "Position of the edited element: " << possition << '\n';
//
fst.seekp(possition, std::ios::beg);
//
fst.write((char*)&newNum, sizeof(int));
fst.seekp(0);
fst.read((char*)arr, sizeof(arr) * arrSize);
for (int index = 0; index < arrSize; ++index)
{
std::cout<< arr[index] << " ";
}
}
void additionThirdEx2() {
int arrSize;
std::cout<< "Enter the size of array\n";
std::cin >> arrSize;
int** arr = new int*[arrSize];
for (int index = 0; index < arrSize; ++index) {
arr[index] = new int[arrSize];
}
for (int index = 0; index < arrSize; ++index) {
for (int index2 = 0; index2 < arrSize; ++index2) {
arr[index][index2] = index2 + index * arrSize;
std::cout<< arr[index][index2] << " ";
}
std::cout<< "\n";
}
std::ofstream ofs("z3_3.txt", std::ios::binary );
if (!ofs.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
for(int index = 0; index < arrSize; ++index)
for(int index2 = 0; index2 < arrSize; ++index2)
ofs.write((char*)&arr[index][index2], sizeof(int));
ofs.close();
int newNum;
int numIndex;
int numIndex2;
std::cout<< "Enter the number and its index1 && index2\n";
std::cin >> newNum >> numIndex >> numIndex2;
std::fstream fst("z3_3.txt", std::ios::binary | std::ios::in | std::ios::out);
if (!fst.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
fst.seekg(0, std::ios::end);
int lenght = fst.tellg();
std::cout<< "The file size ist: " << lenght << "bytes\n";
//
int possition = (numIndex * arrSize* sizeof(int)) + numIndex2 * sizeof(int) ;
std::cout<< "Position of the edited element: " << possition << '\n';
//
fst.seekp(possition, std::ios::beg);
fst.write((char*)&newNum, sizeof(int));
fst.seekg(0);
for (int index = 0; index < arrSize; ++index)
for (int index2 = 0; index2 < arrSize; ++index2)
fst.read((char*)&arr[index][index2], sizeof(int));
for (int index = 0; index < arrSize; ++index) {
for (int index2 = 0; index2 < arrSize; ++index2) {
std::cout<< arr[index][index2] << " ";
}
std::cout<< "\n";
}
}
void additionThirdEx3() {
const int arrSize = 10;
int arr[arrSize];
for (int index = 0; index < arrSize; ++index) {
arr[index] = index;
}
for (int index = 0; index < arrSize; ++index) {
std::cout<< arr[index] << " ";
}
std::ofstream ofs("z3_3.txt", std::ios::binary );
if (!ofs.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
for (int index = 0; index < arrSize; ++index)
ofs.write((char*)&arr[index], sizeof(int));
ofs.close();
int newNum;
int numIndex;
int numIndex2;
std::cout<< "Enter the index you want to delete\n";
std::cin >> numIndex;
std::fstream fst("z3_3.txt", std::ios::binary | std::ios::in | std::ios::out);
if (!fst.is_open()) {
std::cout<< "An error has occurred\n";
return;
}
fst.seekg(0, std::ios::end);
int lenght = fst.tellg();
std::cout<< "The file size ist: " << lenght << "bytes\n";
int possition = (numIndex * sizeof(int)) - sizeof(int);
//
int tmp[arrSize - 1];
fst.seekp(possition, std::ios::beg);
//
for (int index = numIndex + 1 ; index < arrSize; ++index) {
fst.write((char*)&arr[index], sizeof(int));
}
fst.seekg(0);
fst.read((char*)arr, sizeof(arr));
fst.seekg(0);
fst.seekg(0, std::ios::end);
lenght = fst.tellg();
std::cout << "The file size ist: " << lenght << "bytes\n";
for (int index = 0; index < arrSize-1; ++index) {
std::cout<< arr[index] << " ";
}
fst.close();
}
void fourEx() {
std::ifstream firstFile;
std::ifstream secondFile;
firstFile.open("first.dat");
secondFile.open("second.txt");
if (!(firstFile.is_open() && secondFile.is_open())) {
std::cout<< "The error was occure\n";
return;
}
char* firstBuf;
char* secondBuf;
int firstBufSize = 0;
int secondBufSize = 0;
firstBufSize = calculateSize(firstFile);
secondBufSize = calculateSize(secondFile);
// ,
if (firstBufSize != secondBufSize) {
std::cout<< "Files have different sizes and content\n";
return;
}
firstBuf = new char[firstBufSize];
secondBuf = new char[secondBufSize];
firstFile.read((char*)firstBuf, sizeof(int) * firstBufSize);
secondFile.read((char*)secondBuf, sizeof(int) * secondBufSize);
// , (index < secondBufSize)
for (int index = 0; index < firstBufSize; ++index)
{
if (firstBuf[index] != secondBuf[index]) {
std::cout<< "Files have different content\n";
return;
}
}
std::cout<< "Files are absolutely identical\n";
}
void additionFourEx() {
std::ifstream firstFile;
std::ifstream secondFile;
firstFile.open("first.txt");
secondFile.open("second.txt");
if (!(firstFile.is_open() && secondFile.is_open())) {
std::cout<< "The error was occure\n";
return;
}
char* firstBuf;
char* secondBuf;
int firstBufSize = 0;
int secondBufSize = 0;
bool isEquals = true;
firstBufSize = calculateSize(firstFile);
secondBufSize = calculateSize(secondFile);
if (firstBufSize != secondBufSize) {
std::cout<< "Files have different sizes and content\n";
isEquals = false;
}
firstBuf = new char[firstBufSize];
secondBuf = new char[secondBufSize];
firstFile.read((char*)firstBuf, sizeof(int) * firstBufSize);
secondFile.read((char*)secondBuf, sizeof(int) * secondBufSize);
if (isEquals) {
for (int index = 0; index < firstBufSize && index < secondBufSize; ++index)
{
if (firstBuf[index] != secondBuf[index]) {
std::cout<< "Files have different content\n";
isEquals = false;
}
}
if (isEquals)
std::cout<< "Files are absolutely identical\n";
}
bool isContainFirst, isContainSecond;
for (int index = 0, index2, index3; index < firstBufSize && index < secondBufSize; ++index) {
isContainFirst = true, isContainSecond = true;
for (index2 = 0, index3 = index; index2 < firstBufSize && index2 < secondBufSize; ++index2, ++index3) {
// , '
if (isContainFirst && firstBuf[index3] != secondBuf[index2]) {
isContainFirst = false;
if (!isContainFirst && !isContainSecond) {
break;
}
}
if (isContainSecond && secondBuf[index3] != firstBuf[index2]) {
isContainSecond = false;
if (!isContainFirst && !isContainSecond) {
break;
}
}
}
if (isContainFirst|| isContainSecond) {
std::cout<< "One file ist part of another one\n";
break;
}
}
}
void fifth() {
std::ifstream ist("dates.txt", std::ios::binary );
std::ofstream ost("collected.txt");
if (!(ist.is_open() && ost.is_open())) {
std::cout<< "The error has occure\n";
return;
}
// regex
std::tr1::regex rx("\\d{2}.{1}\\d{2}.{1}\\d{4}");
char* buf;
int bufSize;
std::map<std::string, int> dates;
std::string str = "";
bufSize = calculateSize(ist);
buf = new char[bufSize];
ist.read(buf, bufSize);
buf[bufSize] = '\0';
for (int index = 0; index <= bufSize; ++index) {
if (buf[index] == ' ' || buf[index] == '\n' ||buf[index] == '\r'|| buf[index] == '\0') {
// , ""
if (regex_search(str.begin(), str.end(), rx)) {
dates[str]++;
}
str = "";
std::cout<< std::endl;
continue;
}
std::cout<< buf[index];
str += buf[index];
}
std::map<std::string, int> ::iterator it = dates.begin();
//
for (int index = 0; it != dates.end(); ++index,++it) {
ost << it->first << " -> " << it->second << std::endl;
}
} | true |
936507ccac77ac04e0f85fa75db8bb0a94f5882c | C++ | henryoier/leetcode | /259_3SumSmaller/259_3SumSmaller.cpp | UTF-8 | 893 | 3.046875 | 3 | [] | no_license | /*************************************************************************
> File Name: 259_3SumSmaller.cpp
> Author: Sheng Qin
> Mail: sheng.qin@yale.edu
> Created Time: Sat Oct 15 22:07:02 2016
************************************************************************/
#include<iostream>
using namespace std;
class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
if(nums.size() < 3)
return 0;
sort(nums.begin(), nums.end());
int result = 0;
for(int i = 0; i < nums.size() - 2; i++){
int j = i + 1, k = nums.size() - 1;
while(j < k){
if(nums[i] + nums[j] + nums[k] >= target)
k--;
else{
result += k - j;
j++;
}
}
}
return result;
}
};
| true |
9470186b886231fde2337c0144c629475a50aabc | C++ | edict-game-program/shooting_game_1 | /SystemForLearning0409/SystemForLearning/Game/SpecialEnemy.cpp | SHIFT_JIS | 9,936 | 2.546875 | 3 | [] | no_license | #include "SpecialEnemy.h"
#include <cmath>
#include <Sprite.h>
#include <Collision.h>
#include "ShootingGame.h"
#include "SpriteAnime.h"
#include "Player.h"
#include "Bullet.h"
#if COLLISION_VISIBLE
#include <PrimitiveEdgeSprite.h>
#endif
static const int cRushAttackFrame = 20;
static const int cPreliminaryRushFrame = 20; // bV\̃t[
SpecialEnemy::SpecialEnemy(ShootingGame* manager)
: GameObject(manager)
, m_sprites()
, m_spriteAnime(nullptr)
, m_collision(nullptr)
, m_behaviorState(BehaviorState::Appear)
, m_stateWait(0)
, m_status(Status_None)
, m_life(0)
, m_shotWait(0)
, m_dirX(0.0f)
, m_dirY(0.0f)
, m_speed(0.0f)
, m_basePositionX(0.0f)
, m_basePositionY(0.0f)
, m_rushStep(0)
, m_rushMoveWait(0)
, m_rushTargetX(0.0f)
, m_rushTargetY(0.0f)
, m_returnPositionX(0.0f)
, m_returnPositionY(0.0f)
, m_rushSpeed(0.0f)
, m_barrageStep(0)
, m_barrageShotWait(0)
#if COLLISION_VISIBLE
, m_collisionSprite{}
#endif
{
}
SpecialEnemy::~SpecialEnemy(void)
{
if (m_spriteAnime)
{
delete m_spriteAnime;
m_spriteAnime = nullptr;
}
for (auto it = m_sprites.begin(); it != m_sprites.end(); ++it)
{
core2d::Sprite::destroy(*it);
}
m_sprites.clear();
removeCollision();
if (m_collision)
{
delete m_collision;
m_collision = nullptr;
}
#if COLLISION_VISIBLE
if (m_collisionSprite)
{
core2d::PrimitiveEdgeSprite::destroy(m_collisionSprite);
m_collisionSprite = nullptr;
}
#endif
}
//
void SpecialEnemy::onFirstUpdate()
{
m_life = 30; //
auto mgr = GameObject::manager();
m_positionX = mgr->getAvalableDisplayWidth() + 64.0f;
m_positionY = mgr->getAvalableDisplayHeight() * 0.5f;
// _
m_basePositionX = mgr->getDisplayWidth() * 0.8f;
m_basePositionY = mgr->getAvalableDisplayHeight() * 0.5f;
setBehaviorState(BehaviorState::Appear);
// XvCgAj[V̍쐬
int imageId[] =
{
ImageId::ImageSpecialEnemy1,
ImageId::ImageSpecialEnemy2,
ImageId::ImageSpecialEnemy1,
ImageId::ImageSpecialEnemy3,
ImageId::ImageEnemyBomb1, // GăGtFNg
ImageId::ImageEnemyBomb2,
ImageId::ImageEnemyBomb3,
ImageId::ImageEnemyBomb4,
ImageId::ImageEnemyBomb5,
};
m_spriteAnime = new SpriteAnime();
int num = sizeof(imageId) / sizeof(int);
for (int i = 0; i < num; ++i)
{
//core2d::Sprite* sprite = new core2d::Sprite(imageId[i]);
core2d::Sprite* sprite = new core2d::Sprite(imageId[i], 128, 128);
sprite->setPriority(static_cast<unsigned int>(DrawPriority::Enemy));
m_sprites.push_back(sprite);
m_spriteAnime->addSprite(sprite);
}
m_spriteAnime->playLoop(0, 3);
auto sprite = m_sprites[0];
m_collision = new core2d::Collision::RectF(core2d::Collision::PointF(-100.f, -100.f), sprite->getWidth(), sprite->getHeight());
m_collision->setActive(false);
addCollision(m_collision);
#if COLLISION_VISIBLE
m_collisionSprite = new core2d::BoxEdgeSprite(sprite->getWidth(), sprite->getHeight());
m_collisionSprite->setPosition(-100.0f, -100.0f);
m_collisionSprite->setColor(0.0f, 1.0f, 0.5f);
#endif
}
// {XL̍XV
void SpecialEnemy::update(void)
{
setSpritesColor(1.0f, 1.0f, 1.0f);
if (m_status == Status_Dead)
{
return;
}
switch (getBehaviorState())
{
case BehaviorState::Appear:
m_positionX -= 1.f;
if (m_positionX < m_basePositionX)
{
m_positionX = m_basePositionX;
setBehaviorState(BehaviorState::Transition);
m_dirX = 0.0f;
m_dirY = -1.0f;
m_speed = 1.0f;
}
break;
case BehaviorState::Transition:
if (--m_stateWait < 0)
{
setBehaviorState(BehaviorState::Move);
m_collision->setActive(true);
}
break;
case BehaviorState::Move:
m_positionY += m_dirY * m_speed;
if (m_dirY > 0.0f)
{
float distance = abs(m_basePositionY - m_positionY);
if (distance > 140.f)
{
m_dirY = -1.0f;
}
}
else if (m_dirY < 0.0f)
{
float distance = abs(m_basePositionY - m_positionY);
if (distance > 140.f)
{
m_dirY = 1.0f;
}
}
// Iɒe
if (--m_shotWait < 0)
{
EnemyBullet* bullet = manager()->createEnemyBullet(ImageEnemyBullet3);
bullet->setPosition(m_positionX - 64.0f, m_positionY);
bullet->setDirection(-1.0f, 0.0f);
bullet->setSpeed(6.0f);
m_shotWait = 180;
}
// _ɍsω
if (--m_stateWait < 0)
{
switch (rand() % 3)
{
default:
case 0:
setBehaviorState(BehaviorState::Move);
break;
case 1:
setBehaviorState(BehaviorState::Rush);
m_rushStep = 0;
m_rushTargetX = m_sprites[0]->getWidth() + 16.0f;
m_rushTargetY = m_positionY;
m_returnPositionX = m_positionX;
m_returnPositionY = m_positionY;
m_rushMoveWait = cRushAttackFrame;
break;
case 2:
setBehaviorState(BehaviorState::Barrage);
m_barrageStep = 0;
m_barrageShotWait = 30;
break;
}
}
break;
case BehaviorState::Rush:
if (updateRush())
{
setBehaviorState(BehaviorState::Transition);
}
break;
case BehaviorState::Barrage:
if (updateBarrage())
{
setBehaviorState(BehaviorState::Transition);
}
break;
}
setSpritesPosition(m_positionX, m_positionY);
m_spriteAnime->update();
m_collision->setPosition(m_positionX, m_positionY);
#if COLLISION_VISIBLE
m_collisionSprite->setPosition(m_positionX, m_positionY);
m_collisionSprite->setActive(getCollisionVisible());
#endif
}
// Փ˂ƂɌĂ
void SpecialEnemy::onCollision(core2d::Collision::CollisionBase* myCollision, core2d::Collision::CollisionBase* targetCollision, GameObject* target)
{
if (isDestroy()) return;
if (m_status == Status_Dead) return;
unsigned int tag = target->getTag();
if (tag == GameObjectTag::PlayerBulletTag)
{
target->setDestroy(); //̒e
setSpritesColor(2.0f, 2.0f, 2.0f);
PlayerBullet* bullet = dynamic_cast<PlayerBullet*>(target);
int damage = bullet->getDamage();
m_life -= damage;
if (m_life <= 0)
{
m_status = Status_Dead;
m_spriteAnime->stop();
//m_spriteAnime->playOnce(4, 8, true);
manager()->notifySpecialEnemyDead(getId());
manager()->addScore(10000);
m_collision->setActive(false);
}
}
}
void SpecialEnemy::setSpritesPosition(float x, float y)
{
for (auto it = m_sprites.begin(); it != m_sprites.end(); ++it)
{
(*it)->setPosition(x, y);
}
}
void SpecialEnemy::setSpritesColor(float r, float g, float b, float a)
{
for (auto it = m_sprites.begin(); it != m_sprites.end(); ++it)
{
(*it)->setMaterialColor(r, g, b, a);
}
}
void SpecialEnemy::setBehaviorState(BehaviorState state)
{
switch (state)
{
case BehaviorState::Transition: m_stateWait = 40; break;
case BehaviorState::Move: m_stateWait = 480; break;
case BehaviorState::Rush: m_stateWait = cPreliminaryRushFrame; break;
case BehaviorState::Barrage: m_stateWait = 30; break;
default: break; // ݒȂ
}
m_behaviorState = state;
}
SpecialEnemy::BehaviorState SpecialEnemy::getBehaviorState(void)
{
return m_behaviorState;
}
// ːis̍XV
bool SpecialEnemy::updateRush(void)
{
bool end = false;
if (m_rushStep == 0)
{
if (--m_rushMoveWait < 0)
{
setBehaviorState(BehaviorState::Rush);
++m_rushStep;
m_rushMoveWait = 20;
m_rushTargetX = m_sprites[0]->getWidth() * 0.5f + 16.0f;
m_rushTargetY = m_positionY;
m_returnPositionX = m_positionX;
m_returnPositionY = m_positionY;
m_rushSpeed = abs(m_rushTargetX - m_returnPositionX) / static_cast<float>(cRushAttackFrame);
}
else
{
float halfFrame = static_cast<float>(cPreliminaryRushFrame / 2);
float sub = abs(halfFrame - m_rushMoveWait);
float distance = (1.0f - sub / halfFrame) * 8.f;
float omega = DEG_TO_RAD(112.0f);
m_positionX = m_returnPositionX + cosf(omega * m_rushMoveWait) * distance;
m_positionY = m_returnPositionY + sinf(omega * m_rushMoveWait) * distance;
}
}
else if (m_rushStep == 1)
{
if (--m_rushMoveWait < 0)
{
++m_rushStep;
}
}
else if (m_rushStep == 2)
{
m_positionX -= m_rushSpeed;
if (m_positionX < m_rushTargetX)
{
m_positionX = m_rushTargetX;
m_positionY = m_rushTargetY;
m_rushMoveWait = 10;
++m_rushStep;
}
}
else if(m_rushStep == 3)
{
if (--m_rushMoveWait < 0)
{
++m_rushStep;
}
}
else if (m_rushStep == 4)
{
m_positionX += m_rushSpeed * 0.9f;
if (m_positionX > m_returnPositionX)
{
m_positionX = m_returnPositionX;
m_positionY = m_returnPositionY;
++m_rushStep;
m_rushMoveWait = 20;
}
}
else
{
if (--m_rushMoveWait < 0)
{
end = true;
}
}
return end;
}
// es̍XV
bool SpecialEnemy::updateBarrage(void)
{
bool end = false;
if (m_barrageStep == 0)
{
if (--m_barrageShotWait < 0)
{
++m_barrageStep;
m_barrageShotWait = 20;
}
}
else if (m_barrageStep == 1)
{
if (--m_barrageShotWait < 0)
{
shotBarrage(12, 0.0f, 4.0f);
m_barrageShotWait = 90;
++m_barrageStep;
}
}
else if (m_barrageStep == 2)
{
if (--m_barrageShotWait < 0)
{
shotBarrage(12, 0.5f, 4.0f);
m_barrageShotWait = 40;
++m_barrageStep;
}
}
else if (m_barrageStep == 3)
{
if (--m_barrageShotWait < 0)
{
shotBarrage(12, 0.0f, 4.0f);
m_barrageShotWait = 50;
++m_barrageStep;
}
}
else
{
if (--m_barrageShotWait < 0)
{
end = true;
}
}
return end;
}
// e쐬
void SpecialEnemy::shotBarrage(int shotCount, float shiftRatio, float speed)
{
if (shotCount < 1) return;
auto mgr = manager();
float omega = DEG_TO_RAD(360.0f / static_cast<float>(shotCount));
float shift = omega * shiftRatio;
for (int i = 0; i < shotCount; ++i)
{
float radian = omega * i + shift;
auto bullet = mgr->createEnemyBullet(ImageId::ImageEnemyBullet1);
bullet->setPosition(m_positionX - 64.0f, m_positionY);
bullet->setDirection(cosf(radian), sinf(radian));
bullet->setSpeed(speed);
bullet->setSpriteScale(4.f , 4.f);
}
} | true |
10c1e7e2aceb6fcf913f72e8d2a0d8f33b8d3207 | C++ | quangh33/Coding-Interview-Practice | /Leetcode/graph/997. Find the Town Judge.cpp | UTF-8 | 565 | 2.640625 | 3 | [] | no_license | //
// Created by Hoang, Quang on 2019-09-02.
//
// https://leetcode.com/problems/find-the-town-judge/
class Solution {
public:
int findJudge(int N, vector <vector<int>> &trust) {
int in[N + 1];
int out[N + 1];
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
for (auto pair: trust) {
int u = pair[0];
int v = pair[1];
in[v]++;
out[u]++;
}
for (int i = 1; i <= N; i++)
if (in[i] == N - 1 && out[i] == 0) return i;
return -1;
}
};
| true |
bf31b6f60287b4681ae3bbc34940a2cddeb6417d | C++ | SayaUrobuchi/uvachan | /Kattis/speeding.cpp | UTF-8 | 335 | 2.609375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n, i, x, y, t, lx, ly, best;
while (scanf("%d", &n) == 1)
{
for (i=0, best=0; i<n; i++)
{
scanf("%d%d", &x, &y);
if (i)
{
t = (y-ly)/(x-lx);
if (t > best)
{
best = t;
}
}
lx = x;
ly = y;
}
printf("%d\n", best);
}
return 0;
}
| true |
686b1793a086881df704b24b82fd4eaf39307046 | C++ | gaoxinge/something | /hpc/mpi/doc/A Comprehensive MPI Tutorial Resource/main6.cpp | UTF-8 | 4,054 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
#include <mpi.h>
using namespace std;
void decompose_domain(int domain_size, int world_rank, int world_size, int *subdomain_start, int *subdomain_size) {
*subdomain_start = domain_size / world_size * world_rank;
*subdomain_size = domain_size / world_size;
if (world_rank == world_size - 1) {
*subdomain_size += domain_size % world_size;
}
}
typedef struct {
int location;
int num_steps_left_in_walk;
} Walker;
void initialize_walkers(int num_walkers_per_proc, int max_walk_size, int subdomain_start, int subdomain_size, vector<Walker> *incoming_walkers) {
Walker walker;
for (int i = 0; i < num_walkers_per_proc; i++) {
walker.location = subdomain_start;
walker.num_steps_left_in_walk = (1.0 * rand() / RAND_MAX) * max_walk_size;
incoming_walkers->push_back(walker);
}
}
void walk(Walker *walker, int subdomain_start, int subdomain_size, int domain_size, vector<Walker> *outgoing_walkers) {
while (walker->num_steps_left_in_walk > 0) {
if (walker->location == subdomain_start + subdomain_size) {
if (walker->location == domain_size) {
walker->location = 0;
}
outgoing_walkers->push_back(*walker);
break;
} else {
walker->location++;
walker->num_steps_left_in_walk--;
}
}
}
void send_outgoing_walkers(vector<Walker> *outgoing_walkers, int world_rank, int world_size) {
MPI_Send(outgoing_walkers->data(), outgoing_walkers->size() * sizeof(Walker), MPI_BYTE, (world_rank + 1) % world_size, 0, MPI_COMM_WORLD);
outgoing_walkers->clear();
}
void receive_incoming_walkers(vector<Walker> *incoming_walkers, int world_rank, int world_size) {
int incoming_rank = world_rank == 0 ? world_size - 1 : world_rank - 1;
MPI_Status status;
MPI_Probe(incoming_rank, 0, MPI_COMM_WORLD, &status);
int incoming_walkers_size;
MPI_Get_count(&status, MPI_BYTE, &incoming_walkers_size);
incoming_walkers->resize(incoming_walkers_size / sizeof(Walker));
MPI_Recv(incoming_walkers->data(), incoming_walkers_size, MPI_BYTE, incoming_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
int main(int argc, char **argv) {
int domain_size = atoi(argv[1]);
int max_walk_size = atoi(argv[2]);
int num_walkers_per_proc = atoi(argv[3]);
MPI_Init(NULL, NULL);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
srand(time(NULL) * world_rank);
int subdomain_start, subdomain_size;
vector<Walker> incoming_walkers, outgoing_walkers;
decompose_domain(domain_size, world_rank, world_size, &subdomain_start, &subdomain_size);
initialize_walkers(num_walkers_per_proc, max_walk_size, subdomain_start, subdomain_size, &incoming_walkers);
cout << "Process " << world_rank << " initiated " << num_walkers_per_proc << " walkers in subdomain " << subdomain_start << " - " << subdomain_start + subdomain_size - 1 << endl;
int maximum_sends_recvs = max_walk_size / (domain_size / world_size) + 1;
for (int m = 0; m < maximum_sends_recvs; m++) {
for (int i = 0; i < incoming_walkers.size(); i++) {
walk(&incoming_walkers[i], subdomain_start, subdomain_size, domain_size, &outgoing_walkers);
}
cout << "Process " << world_rank << " sending " << outgoing_walkers.size() << " outgoing walkers to process " << (world_rank + 1) % world_size << endl;
if (world_rank % 2 == 0) {
send_outgoing_walkers(&outgoing_walkers, world_rank, world_size);
receive_incoming_walkers(&incoming_walkers, world_rank, world_size);
} else {
receive_incoming_walkers(&incoming_walkers, world_rank, world_size);
send_outgoing_walkers(&outgoing_walkers, world_rank, world_size);
}
cout << "Process " << world_rank << " received " << incoming_walkers.size() << " incoming walkers " << endl;
}
cout << "Process " << world_rank << " done" << endl;
MPI_Finalize();
return 0;
}
| true |
03accd1715b346d88384da8acd21937a792daae1 | C++ | akhil-singh-parmar/algo.cpp | /bubblesort.cpp | UTF-8 | 648 | 3.609375 | 4 | [] | no_license | #include<iostream>
using namespace std;
void bubblesort(int arr[],int n)
{
for (int i = 0; i < n-1; i++)
{
for(int j=1;j<n-i;j++)
{
if(arr[j-1]>arr[j])
{
int temp;
temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
}
}
}
}
void printarray(int arr[],int n)
{
cout<<"the elements of this array are ";
for(int k=0;k<n;k++)
cout<<arr[k]<<" ";
}
int main()
{ int n;
cout<<"enter the size of array";
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"the unsorted array is ";
printarray(arr,n);
bubblesort(arr,n);
}
| true |
ababa4114e308fb4d89423e7e3793f4b35869f60 | C++ | supperking03/AladdinGame | /game/scripts/EnemyController.cpp | UTF-8 | 5,196 | 2.59375 | 3 | [] | no_license | #include "EnemyController.h"
#include "EnemyDirectionController.h"
#include "../Macros.h"
#include "WeaponController.h"
USING_NAMESPACE_ALA;
ALA_CLASS_SOURCE_1(EnemyController, ala::GameObjectComponent)
EnemyController::EnemyController(ala::GameObject* gameObject, const int health, const std::function<int(WeaponController*)> &damageCalculator, const std::string& name)
:GameObjectComponent(gameObject, name),
_maxYDistance(50),
_startX(0),
_minX(0),
_maxX(0),
_health(health),
_directionController(NULL),
_aladdinTransform(NULL),
_transform(NULL),
_stateManager(NULL),
_maxAttackRange(70),
_resetRange(GameManager::get()->getVisibleWidth() * 0.7f),
_collidingCharcoalBurner(false),
_damageCalculator(damageCalculator)
{
}
bool EnemyController::isCollidingCharcoalBurner() const
{
return _collidingCharcoalBurner;
}
bool EnemyController::willReset() const
{
return abs(_aladdinTransform->getPositionX() - _transform->getPositionX()) >= _resetRange;
}
bool EnemyController::canSeeAladdin() const
{
const auto aladdinPosition = _aladdinTransform->getPositionX();
const auto yDistanceToAladdin = abs(_aladdinTransform->getPositionY() - _transform->getPositionY());
if(yDistanceToAladdin > _maxYDistance)
{
return false;
}
if (aladdinPosition >= _minX - _maxAttackRange && aladdinPosition <= _maxX + _maxAttackRange)
{
return true;
}
return false;
}
bool EnemyController::canAttackAladdin() const
{
const auto xDistanceToAladdin = abs(_aladdinTransform->getPositionX() - _transform->getPositionX());
const auto yDistanceToAladdin = abs(_aladdinTransform->getPositionY() - _transform->getPositionY());
return xDistanceToAladdin <= _maxAttackRange && yDistanceToAladdin <= _maxYDistance;
}
bool EnemyController::canGoLeft() const
{
return _transform->getPositionX() > _minX;
}
bool EnemyController::canGoRight() const
{
return _transform->getPositionX() < _maxX;
}
void EnemyController::clampPosition() const
{
if(_transform->getPositionX() > _maxX)
{
_transform->setPositionX(_maxX);
}
if (_transform->getPositionX() < _minX)
{
_transform->setPositionX(_minX);
}
}
void EnemyController::updateDirection() const
{
if (_directionController->getAladdinDirection() < 0)
{
_directionController->setLeft();
}
else
{
_directionController->setRight();
}
}
float EnemyController::getStartX() const
{
return _startX;
}
float EnemyController::getMinX() const
{
return _minX;
}
float EnemyController::getMaxX() const
{
return _maxX;
}
void EnemyController::setStartX(const float startX)
{
_startX = startX;
}
void EnemyController::setMinX(const float minX)
{
_minX = minX;
}
void EnemyController::setMaxX(const float maxX)
{
_maxX = maxX;
}
float EnemyController::getMaxAttackRange() const
{
return _maxAttackRange;
}
void EnemyController::setMaxAttackRange(const float maxAttackRange)
{
_maxAttackRange = maxAttackRange;
}
float EnemyController::getMaxYDistance() const
{
return _maxYDistance;
}
void EnemyController::setMaxYDistance(const float maxYDistance)
{
_maxYDistance = maxYDistance;
}
int EnemyController::getHealth() const
{
return _health;
}
void EnemyController::setHealth(const int health)
{
_health = health;
}
void EnemyController::onInitialize()
{
const auto gameManager = GameManager::get();
const auto gameObject = getGameObject();
_directionController = gameObject->getComponentT<EnemyDirectionController>();
_stateManager = gameObject->getComponentT<StateManager>();
_transform = gameObject->getTransform();
_aladdinTransform = gameManager->getObjectByTag(ALADDIN_TAG)->getTransform();
_transform->setPositionX(_startX);
}
void EnemyController::onTriggerEnter(const ala::CollisionInfo& collision)
{
const auto otherCollider = collision.getColliderA()->getGameObject() == getGameObject()
? collision.getColliderB()
: collision.getColliderA();
const auto otherObject = otherCollider->getGameObject();
const auto selfCollider = collision.getColliderA() == otherCollider
? collision.getColliderB()
: collision.getColliderA();
if (selfCollider->getTag() == ENEMY_TAG)
{
if ((otherCollider->getTag() == ALADDIN_WEAPON_TAG)) {
onHit(otherCollider->getGameObject()->getComponentT<WeaponController>());
}
}
if(otherCollider->getTag() == CHARCOAL_BURNER_TAG)
{
_collidingCharcoalBurner = true;
}
}
void EnemyController::onTriggerExit(const ala::CollisionInfo& collision)
{
const auto otherCollider = collision.getColliderA()->getGameObject() == getGameObject()
? collision.getColliderB()
: collision.getColliderA();
if (otherCollider->getTag() == CHARCOAL_BURNER_TAG)
{
_collidingCharcoalBurner = false;
}
}
void EnemyController::onOutOfHealth() const
{
GameManager::get()->getPrefab("Explosion")->instantiate(_transform->getPosition());
getGameObject()->release();
}
void EnemyController::onHit(WeaponController* weaponController)
{
if (_stateManager->getCurrentStateName() == "hit") return;
_stateManager->changeState("hit");
_health -= _damageCalculator(weaponController);
if (_health <= 0)
{
onOutOfHealth();
}
}
| true |
d09727f13c901da61012c98ad3e2085a4743ac1c | C++ | linsen1983/adobe-pdf-library-samples | /CPlusPlus/Sample_Source/ContentModification/PDFUncompress/PDFUncompress.cpp | UTF-8 | 12,771 | 2.5625 | 3 | [] | no_license | //
// Copyright (c) 2010-2017, Datalogics, Inc. All rights reserved.
//
// For complete copyright information, see:
// http://dev.datalogics.com/adobe-pdf-library/adobe-pdf-library-c-language-interface/license-for-downloaded-pdf-samples/
//
// The PDFUncompress sample is a utility that demonstrates how to completely un-compress the elements within a PDF
// document into a readable form.
//
// Nearly all PDF documents feature compressed elements to make the documents more efficient to use, and most of the time
// these documents are left in their compressed state even when being opened in a browser or viewing tool. But sometimes
// it is necessary to completely uncompress a PDF document so that it can be opened and all of its contents viewed in detail
// in a text editor. This would be useful if you want to find the reason for a problem with a PDF document or set of PDF documents,
// or with a workflow that generates PDF documents.
//
// For example, this sample also uncompresses font streams that are embedded in the document. The fonts are normally compressed
// using the Flate compression algorithm, but PDFUncompress can render this font content as ASCII or Hexadecimal characters.
//
// For more detail see the description of the PDFUncompress sample program on our Developer’s site,
// http://dev.datalogics.com/adobe-pdf-library/sample-program-descriptions/c1samples#pdfuncompress
#include "CosCalls.h"
#include "InitializeLibrary.h"
#include "APDFLDoc.h"
#include "PDFUncompress.h"
#define INPUT_DIR "../../../../Resources/Sample_Input/"
#define INPUT_FILE "CopyContent.pdf"
#define OUTPUT_FILE "PDFUncompress-out.pdf"
int main (int argc, char* argv[])
{
// Initialize library
APDFLib libInit;
if (libInit.isValid() == false)
{
ASErrorCode errCode = libInit.getInitError();
APDFLib::displayError ( errCode );
return errCode;
}
std::string csInputFile(argc > 1 ? argv[1] : INPUT_DIR INPUT_FILE);
std::string csOutputFile(argc > 2 ? argv[2] : OUTPUT_FILE);
std::cout << "Will uncompress file " << csInputFile.c_str() << " and save as " << csOutputFile.c_str() << std::endl;
// Open input document
PDDoc pdDoc;
DURING
ASPathName InPath = APDFLDoc::makePath ( csInputFile.c_str() );
pdDoc = PDDocOpen(InPath, NULL, NULL, true);
ASFileSysReleasePath(NULL, InPath);
HANDLER
std::cout << "Could not open file " << csInputFile.c_str() << std::endl;
APDFLib::displayError(ERRORCODE);
return ERRORCODE;
END_HANDLER
// Determine if copying is permitted from this document
bool DocumentEncrypted(false);
DURING
PDDocAuthorize (pdDoc, pdPermAll, NULL);
PDDocSetNewCryptHandler (pdDoc, ASAtomNull);
HANDLER
DocumentEncrypted = true;
END_HANDLER
if (DocumentEncrypted)
{
PDDoc DocCopy;
DURING
DocCopy = PDDocCreate ();
PDDocInsertPages (DocCopy, PDBeforeFirstPage, pdDoc, 0, PDAllPages, PDInsertAll, NULL, NULL, NULL, NULL);
HANDLER
std::cout << "Document is encoded, and copy is not permitted!\n";
return -2;
END_HANDLER
}
int CurrentPage ( 0 );
int Pages = PDDocGetNumPages (pdDoc);
DURING
for (CurrentPage = 0; CurrentPage < Pages; CurrentPage++)
{
PDPage Page = PDDocAcquirePage (pdDoc, CurrentPage);
CosObj cosPage = PDPageGetCosObj (Page);
CosObj Content = CosDictGet (cosPage, ASAtomFromString ("Contents"));
switch (CosObjGetType (Content))
{
case CosStream:
Content = Uncompress (Content);
CosDictPut (cosPage, ASAtomFromString ("Contents"), Content);
break;
case CosArray:
for (int ContentElement = 0; ContentElement < CosArrayLength (Content); ContentElement++)
{
CosObj Stream;
Stream = CosArrayGet (Content, ContentElement);
CosArrayPut (Content, ContentElement, Uncompress (Stream));
}
break;
case CosNull:
break;
default:
break;
}
Content = CosDictGet (cosPage, ASAtomFromString ("Annots"));
if (CosObjGetType (Content) != CosNull)
{
for (int count = 0; count < CosArrayLength (Content); count++)
{
CosObj NewAnnot;
NewAnnot = UncompressAnnot (CosArrayGet (Content, count));
if (CosObjGetType (NewAnnot) != CosNull)
CosArrayPut (Content, count, NewAnnot);
}
}
Content = CosDictGet (cosPage, ASAtomFromString ("Resources"));
if (CosObjGetType (Content) != CosNull)
{
CosObj Xobjs = CosDictGet (Content, ASAtomFromString ("XObject"));
if (CosObjGetType (Xobjs) == CosDict)
CosObjEnum (Xobjs, CompressXobj, &Xobjs);
}
PDPageRelease (Page);
}
HANDLER
std::cout << "Problem uncompressing page " << CurrentPage+1 << std::endl;
return -3;
END_HANDLER
PDDocEnumResources (pdDoc, 0, Pages-1, ASAtomNull, UncompressResource, pdDoc);
DURING
// Save document
ASPathName path = APDFLDoc::makePath ( csOutputFile.c_str() );
PDDocSaveParamsRec docSaveParamsRec;
memset(&docSaveParamsRec, 0, sizeof(docSaveParamsRec));
docSaveParamsRec.size = sizeof(PDDocSaveParamsRec);
docSaveParamsRec.saveFlags = PDSaveFull | PDSaveCollectGarbage;
docSaveParamsRec.newPath = path;
docSaveParamsRec.major = 1;
docSaveParamsRec.minor = 1;
docSaveParamsRec.saveFlags2 = PDSaveUncompressed;
PDDocSaveWithParams(pdDoc, &docSaveParamsRec);
HANDLER
{
std::cout << "Problem writing file \"" << csOutputFile.c_str() << "\"" << std::endl;
return -8;
}
END_HANDLER
PDDocRelease (pdDoc);
return 0;
}
CosObj Uncompress (CosObj Stream)
{
CosObj Filter;
CosObj NewStream;
CosObj CosDict;
ASStm Stm;
if (CosObjGetType (Stream) != CosStream)
return (Stream);
Filter = CosDictGet (Stream, ASAtomFromString ("Filter"));
if (CosObjGetType (Filter) == CosNull)
return (Stream);
CosDict = CosStreamDict (Stream);
CosDict = CosObjCopy (CosDict, CosObjGetDoc (Stream), TRUE);
CosDictRemove (CosDict, ASAtomFromString ("Filter"));
CosDictRemove (CosDict, ASAtomFromString ("DecodeParms"));
CosDictRemove (CosDict, ASAtomFromString ("Length"));
Stm = CosStreamOpenStm (Stream, cosOpenFiltered);
NewStream = CosNewStream (CosObjGetDoc (Stream), TRUE, Stm, 0, TRUE,
CosDict, CosNewNull(), -1);
ASStmClose (Stm);
return (NewStream);
}
ASBool UncompressResource (CosObj Key, CosObj Value, void* clientData)
{
const char *KeyName, *DictType;
CosType KeyType = CosObjGetType (Key);
CosType ValueType = CosObjGetType (Value);
if (CosObjGetType (Key) == CosName)
KeyName = ASAtomGetString (CosNameValue (Key));
if (KeyType == CosDict)
{
ASAtom Type;
CosObj TypeObj;
TypeObj = CosDictGet (Key, ASAtomFromString ("Type"));
if (CosObjGetType (TypeObj) == CosName)
{
Type = CosNameValue (TypeObj);
DictType = ASAtomGetString (Type);
}
else
Type = ASAtomNull;
if (Type == ASAtomFromString ("Font"))
{
CosObj ToUnicode, CIDToGIDMap, CIDSet, FontDesc, DescFont;
ToUnicode = CosDictGet (Key, ASAtomFromString ("ToUnicode"));
if (!CosObjEqual (ToUnicode, CosNewNull()))
{
ToUnicode = Uncompress (ToUnicode);
CosDictPut (Key, ASAtomFromString ("ToUnicode"), ToUnicode);
}
ToUnicode = CosDictGet (Key, ASAtomFromString ("Encoding"));
if (CosObjGetType (ToUnicode) == CosStream)
{
ToUnicode = Uncompress (ToUnicode);
CosDictPut (Key, ASAtomFromString ("Encoding"), ToUnicode);
}
DescFont = CosDictGet (Key, ASAtomFromString ("DescendantFonts"));
if (!CosObjEqual (DescFont, CosNewNull()))
{
DescFont = CosArrayGet (DescFont, 0);
CIDToGIDMap = CosDictGet (DescFont, ASAtomFromString ("CIDToGIDMap"));
if (!CosObjEqual (CIDToGIDMap, CosNewNull()))
{
CIDToGIDMap = Uncompress (CIDToGIDMap);
CosDictPut (DescFont, ASAtomFromString ("CIDToGIDMap"), CIDToGIDMap);
}
FontDesc = CosDictGet (DescFont, ASAtomFromString ("FontDescriptor"));
if (!CosObjEqual (FontDesc, CosNewNull()))
{
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("CISSet"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("CISSet"), CIDSet);
}
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("FontFile"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("FontFile"), CIDSet);
}
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("FontFile2"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("FontFile2"), CIDSet);
}
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("FontFile3"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("FontFile3"), CIDSet);
}
}
}
else
{
FontDesc = CosDictGet (Key, ASAtomFromString ("FontDescriptor"));
if (!CosObjEqual (FontDesc, CosNewNull()))
{
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("CISSet"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("CISSet"), CIDSet);
}
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("FontFile"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("FontFile"), CIDSet);
}
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("FontFile2"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("FontFile2"), CIDSet);
}
CIDSet = CosDictGet (FontDesc, ASAtomFromString ("FontFile3"));
if (CosObjGetType (CIDSet) == CosStream)
{
CIDSet = Uncompress (CIDSet);
CosDictPut (FontDesc, ASAtomFromString ("FontFile3"), CIDSet);
}
}
}
}
if (KeyType == CosStream)
Uncompress (Key);
if (ValueType == CosStream)
Uncompress (Value);
}
return (TRUE);
}
ASBool CompressXobj (CosObj Key, CosObj Value, void *Data)
{
CosObj NewXobj = Uncompress (Value);
CosDictPut (*(CosObj *) Data, CosNameValue (Key), NewXobj);
return TRUE;
}
ASBool SubAnnot (CosObj Key, CosObj Value, void *Data)
{
CosType Type = CosObjGetType (Value);
if (Type == CosStream)
CosDictPut (*(CosObj*)Data, CosNameValue (Key), Uncompress (Value));
if (Type == CosDict)
CosObjEnum (Value, SubAnnot, &Value);
return TRUE;
}
CosObj UncompressAnnot (CosObj Annot)
{
CosObj APDict;
if (CosObjGetType (Annot) != CosDict)
return (CosNewNull());
APDict = CosDictGet (Annot, ASAtomFromString ("AP"));
if (CosObjGetType (APDict) == CosNull)
return (CosNewNull());
if (CosObjGetType (APDict) == CosStream)
return (Uncompress (APDict));
CosObjEnum (APDict, SubAnnot, &APDict);
return (CosNewNull());
}
| true |
8f133bda4ec4194db0f96dfbbbd45dad1774fcea | C++ | jacksonn455/Exercicios | /Função com argumento2.cpp | WINDOWS-1250 | 510 | 3.515625 | 4 | [] | no_license | #include <cstdio>
#include <cstdlib>
int mult3 (int a, int b, int c){
return a*b*c;
}
int main (void){
int valor1, valor2, valor3, resultado;
printf ("Digite 3 valores que serao multiplicados\n");
scanf ("%d %d %d", &valor1, &valor2, &valor3);
getchar ();
resultado=mult3(valor1, valor2, valor3);
//Valor1 ser int a, valor2 ser int b e valor3 ser int c
printf ("O resultado e %d\n\n", resultado);
system ("pause");
return EXIT_SUCCESS; //o mesmo que return 0.
}
| true |
c7eba7f6c80106ae11a240cf3bceb4c812f7d90f | C++ | JeonSheungGyu/ContagionCity | /server/Server(신서버)/ConsoleApplication1/CombatCollision.h | UHC | 1,333 | 2.625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
const int COLLISION_FUNC_TYPE = 5;
enum
{
CC_CircleAround = 0,
CC_CircleFront,
CC_Eraser,
CC_PointCircle,
ETC_CheckUser
};
// Լ ü
struct CollisionFuncArray
{
using FuncType = void(*)(const WORD, std::vector< std::pair<WORD, int>>&, const FLOAT, const FLOAT);
FuncType Func;
CollisionFuncArray() { Func = nullptr; }
};
class CombatCollision
{
public:
// ij ֺ
static void CircleAround(const WORD id, std::vector< std::pair<WORD, int>>& InfoList, const FLOAT x, const FLOAT z);
// ij
static void CircleFront(const WORD id, std::vector< std::pair<WORD, int>>& InfoList, const FLOAT x, const FLOAT z);
//
static void Eraser(const WORD id, std::vector< std::pair<WORD, int>>& InfoList, const FLOAT x, const FLOAT z);
// Ʈ
static void PointCircle(const WORD id, std::vector< std::pair<WORD, int>>& InfoList, const FLOAT x, const FLOAT z);
//
static void CheckUser(const WORD id, std::vector< std::pair<WORD, int>>& InfoList, const FLOAT x, const FLOAT z);
//RayCast
static BOOL RayCast(const XMFLOAT3& Pos, const XMFLOAT3& Dir, FLOAT dist, const BoundingSphere object)
{
FXMVECTOR pos(XMLoadFloat3(&Pos));
FXMVECTOR dir(XMLoadFloat3(&Dir));
return object.Intersects(pos, dir, dist);
}
}; | true |
5f162ffd1c1d876d77984d601c64d1688b887aeb | C++ | swd543/cppTut | /dictionary-predictive/src/main.cpp | UTF-8 | 926 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <unordered_set>
#include "mappifier.hpp"
using namespace std;
int main()
{
std::cout << "I will read the dictionary provided and list all anagrams present." << std::endl;
fstream file;
file.open("./words.txt", ios::in);
if (file.is_open())
{
cout << "Building index..." << endl;
unordered_map<size_t, unordered_set<string>> index;
string s;
while (getline(file, s))
{
mappifier<char, int> m;
m.mappify(s);
auto hash = m.hash();
if (index.count(hash) == 0)
{
unordered_set<string> tmp;
tmp.insert(s);
index[hash] = tmp;
}
else
{
index[hash].insert(s);
}
}
for (auto e : index)
{
if (e.second.size() == 1)
{
continue;
}
for (auto s : e.second)
{
cout << s << " ";
}
cout << endl;
}
}
} | true |
4ce1400bb6754211df85c773ab5ec6e7ae23e525 | C++ | BobuDragos/Arduino | /Matrices/Matrix_with_LEDMatrixDriver/Matrix_with_LEDMatrixDriver.ino | UTF-8 | 9,488 | 2.578125 | 3 | [] | no_license | #include <LEDMatrixDriver.hpp>
// This draw a moving sprite on your LED matrix using the hardware SPI driver Library by Bartosz Bielawski.
// Example written 16.06.2017 by Marko Oette, www.oette.info
// Define the ChipSelect pin for the led matrix (Dont use the SS or MISO pin of your Arduino!)
// Other pins are Arduino specific SPI pins (MOSI=DIN, SCK=CLK of the LEDMatrix) see https://www.arduino.cc/en/Reference/SPI
const uint8_t LEDMATRIX_CS_PIN = 9;
// Number of 8x8 segments you are connecting
const int LEDMATRIX_SEGMENTS = 4;
const int LEDMATRIX_WIDTH = LEDMATRIX_SEGMENTS * 8;
// The LEDMatrixDriver class instance
LEDMatrixDriver lmd(LEDMATRIX_SEGMENTS, LEDMATRIX_CS_PIN);
LEDMatrixDriver lmd2(LEDMATRIX_SEGMENTS / 2, LEDMATRIX_CS_PIN);
byte StickmanFrames[6][8] = {{B00011000, B00100100, B00100100, B00011000, B01111110, B00011000, B00100100, B01000010},
{B00011000, B00100100, B00100100, B00011010, B01111100, B00011000, B01100100, B00000010},
{B00011000, B00100100, B00100100, B00011010, B00111100, B01011000, B00110100, B00000100},
{B00011000, B00100100, B00100100, B00011010, B00111100, B01011000, B00011000, B00011000},
{B00011000, B00100100, B00100100, B00011010, B00111100, B01011000, B00010100, B00010000},
{B00011000, B00100100, B00100100, B00011000, B00111110, B01011000, B00010100, B00010100}
};
const uint8_t windmill[] =
{
0x91, 0x4a, 0x34, 0x5d, 0xba, 0x2c, 0x52, 0x89
};
byte font[95][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, // SPACE
{0x10, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18}, // EXCL
{0x28, 0x28, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00}, // QUOT
{0x00, 0x0a, 0x7f, 0x14, 0x28, 0xfe, 0x50, 0x00}, // #
{0x10, 0x38, 0x54, 0x70, 0x1c, 0x54, 0x38, 0x10}, // $
{0x00, 0x60, 0x66, 0x08, 0x10, 0x66, 0x06, 0x00}, // %
{0, 0, 0, 0, 0, 0, 0, 0}, // &
{0x00, 0x10, 0x18, 0x18, 0x08, 0x00, 0x00, 0x00}, // '
{0x02, 0x04, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04}, // (
{0x40, 0x20, 0x10, 0x10, 0x10, 0x10, 0x10, 0x20}, // )
{0x00, 0x10, 0x54, 0x38, 0x10, 0x38, 0x54, 0x10}, // *
{0x00, 0x08, 0x08, 0x08, 0x7f, 0x08, 0x08, 0x08}, // +
{0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x08}, // COMMA
{0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00}, // -
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06}, // DOT
{0x00, 0x04, 0x04, 0x08, 0x10, 0x20, 0x40, 0x40}, // /
{0x00, 0x38, 0x44, 0x4c, 0x54, 0x64, 0x44, 0x38}, // 0
{0x04, 0x0c, 0x14, 0x24, 0x04, 0x04, 0x04, 0x04}, // 1
{0x00, 0x30, 0x48, 0x04, 0x04, 0x38, 0x40, 0x7c}, // 2
{0x00, 0x38, 0x04, 0x04, 0x18, 0x04, 0x44, 0x38}, // 3
{0x00, 0x04, 0x0c, 0x14, 0x24, 0x7e, 0x04, 0x04}, // 4
{0x00, 0x7c, 0x40, 0x40, 0x78, 0x04, 0x04, 0x38}, // 5
{0x00, 0x38, 0x40, 0x40, 0x78, 0x44, 0x44, 0x38}, // 6
{0x00, 0x7c, 0x04, 0x04, 0x08, 0x08, 0x10, 0x10}, // 7
{0x00, 0x3c, 0x44, 0x44, 0x38, 0x44, 0x44, 0x78}, // 8
{0x00, 0x38, 0x44, 0x44, 0x3c, 0x04, 0x04, 0x78}, // 9
{0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00}, // :
{0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x08}, // ;
{0x00, 0x10, 0x20, 0x40, 0x80, 0x40, 0x20, 0x10}, // <
{0x00, 0x00, 0x7e, 0x00, 0x00, 0xfc, 0x00, 0x00}, // =
{0x00, 0x08, 0x04, 0x02, 0x01, 0x02, 0x04, 0x08}, // >
{0x00, 0x38, 0x44, 0x04, 0x08, 0x10, 0x00, 0x10}, // ?
{0x00, 0x30, 0x48, 0xba, 0xba, 0x84, 0x78, 0x00}, // @
{0x00, 0x1c, 0x22, 0x42, 0x42, 0x7e, 0x42, 0x42}, // A
{0x00, 0x78, 0x44, 0x44, 0x78, 0x44, 0x44, 0x7c}, // B
{0x00, 0x3c, 0x44, 0x40, 0x40, 0x40, 0x44, 0x7c}, // C
{0x00, 0x7c, 0x42, 0x42, 0x42, 0x42, 0x44, 0x78}, // D
{0x00, 0x78, 0x40, 0x40, 0x70, 0x40, 0x40, 0x7c}, // E
{0x00, 0x7c, 0x40, 0x40, 0x78, 0x40, 0x40, 0x40}, // F
{0x00, 0x3c, 0x40, 0x40, 0x5c, 0x44, 0x44, 0x78}, // G
{0x00, 0x42, 0x42, 0x42, 0x7e, 0x42, 0x42, 0x42}, // H
{0x00, 0x7c, 0x10, 0x10, 0x10, 0x10, 0x10, 0x7e}, // I
{0x00, 0x7e, 0x02, 0x02, 0x02, 0x02, 0x04, 0x38}, // J
{0x00, 0x44, 0x48, 0x50, 0x60, 0x50, 0x48, 0x44}, // K
{0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x7c}, // L
{0x00, 0x82, 0xc6, 0xaa, 0x92, 0x82, 0x82, 0x82}, // M
{0x00, 0x42, 0x42, 0x62, 0x52, 0x4a, 0x46, 0x42}, // N
{0x00, 0x3c, 0x42, 0x42, 0x42, 0x42, 0x44, 0x38}, // O
{0x00, 0x78, 0x44, 0x44, 0x48, 0x70, 0x40, 0x40}, // P
{0x00, 0x3c, 0x42, 0x42, 0x52, 0x4a, 0x44, 0x3a}, // Q
{0x00, 0x78, 0x44, 0x44, 0x78, 0x50, 0x48, 0x44}, // R
{0x00, 0x38, 0x40, 0x40, 0x38, 0x04, 0x04, 0x78}, // S
{0x00, 0x7e, 0x90, 0x10, 0x10, 0x10, 0x10, 0x10}, // T
{0x00, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x3e}, // U
{0x00, 0x42, 0x42, 0x42, 0x42, 0x44, 0x28, 0x10}, // V
{0x80, 0x82, 0x82, 0x92, 0x92, 0x92, 0x94, 0x78}, // W
{0x00, 0x42, 0x42, 0x24, 0x18, 0x24, 0x42, 0x42}, // X
{0x00, 0x44, 0x44, 0x28, 0x10, 0x10, 0x10, 0x10}, // Y
{0x00, 0x7c, 0x04, 0x08, 0x7c, 0x20, 0x40, 0xfe}, // Z
// (the font does not contain any lower case letters. you can add your own.)
}; // {}, //
byte InvaderFrames[2][8] = { {0x18, 0x3c, 0x7e, 0xdb, 0xff, 0x24, 0x5a, 0xa5},
{0x18, 0x3c, 0x7e, 0xdb, 0xff, 0x24, 0x5a, 0x42},
};
byte PacmanFrames[2][8] = { {0x3c, 0x7e, 0xdf, 0xff, 0xf0, 0xff, 0x7e, 0x3c},
{0x3c, 0x7e, 0xdc, 0xf8, 0xf8, 0xfc, 0x7e, 0x3c},
};
byte BunnyFrames[2][8] = { {0x66, 0x66, 0x66, 0xff, 0x81, 0xa5, 0x99, 0x7e},
{0x66, 0xe7, 0x66, 0xff, 0x81, 0xa5, 0x99, 0x7e}
};
byte DandoFrames[2][8] = { {0x00, 0xff, 0x81, 0xa5, 0x81, 0x81, 0xff, 0x00},};
byte GhostFrames[5][8] = { {0x18, 0x7e, 0xff, 0xbd, 0xff, 0xff, 0xff, 0xa5},
{0x18, 0x7e, 0xbd, 0xff, 0xff, 0xff, 0xff, 0xa5},
{0x18, 0x7e, 0xdb, 0xff, 0xff, 0xff, 0xff, 0xa5},
{0x18, 0x7e, 0xff, 0xdb, 0xff, 0xff, 0xff, 0xa5},
{0x18, 0x7e, 0x99, 0x99, 0xff, 0xff, 0xff, 0xa5}
};
byte Ghost2Frames[1][8] = {0x3c, 0x7e, 0xd7, 0xff, 0xc3, 0xff, 0xff, 0xdb};
int AnimIndex = 0;
const int AnimDelay = 100;
char text[] = "** LED MATRIX DEMO! ** (1234567890) ++ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" ++ <$%/=?'.@,> --";
int x = 0, y = 0; // start top left
void setup() {
// init the display
lmd.setEnabled(true);
lmd.setIntensity(0); // 0 = low, 10 = high
lmd2.setEnabled(true);
lmd2.setIntensity(2); // 0 = low, 10 = high
}
void loop() {
for (int x = -7; x <= LEDMATRIX_WIDTH; x++) {
lmd.clear();
drawSprite( (byte*)&StickmanFrames[AnimIndex], x, 0, 8, 8 );
AnimIndex = (AnimIndex + 1) % (sizeof(StickmanFrames) / sizeof(StickmanFrames[0]));
lmd.display();
delay(AnimDelay);
}
for (int x = -7; x <= LEDMATRIX_WIDTH + 36; x++) {
lmd.clear();
AnimIndex = (AnimIndex + 1) % (sizeof(GhostFrames) / sizeof(GhostFrames[0]));
drawSprite( (byte*)&InvaderFrames[AnimIndex % 2], x, 0, 8, 8 );
drawSprite( (byte*)&PacmanFrames[AnimIndex % 2], x - 9, 0, 8, 8 );
drawSprite( (byte*)&BunnyFrames[AnimIndex % 2], x - 18, 0, 8, 8 );
drawSprite( (byte*)&DandoFrames[AnimIndex % 2], x - 27, 0, 8, 8 );
drawSprite( (byte*)&GhostFrames[AnimIndex], x - 36, 0, 8, 8 );
lmd.display();
delay(AnimDelay);
}
// int len = strlen(text);
// DrawTextUp(text, len, x, 0);
// delay(AnimDelay);
// if ( --x < len * -8 ) {
// x = LEDMATRIX_WIDTH;
// }
//drawSprite( (byte*)&windmill[0], 0, 0, 8, 8 );
}
void DrawTextDown(char* text, int len, int x, int y ) {
for ( int idx = 0; idx < len; idx ++ )
{
int c = text[idx] - 32;
// stop if char is outside visible area
if ( x + idx * 8 > LEDMATRIX_WIDTH)
return;
// only draw if char is visible
if ( 8 + x + idx * 8 > LEDMATRIX_WIDTH / 2 + 7)
drawSprite( font[c], x + idx * 8, y, 8, 8 );
}
}
void DrawTextUp(char* text, int len, int x, int y ) {
for ( int idx = 0; idx < len; idx ++ )
{
int c = text[idx] - 32;
// stop if char is outside visible area
if ( x + idx * 8 > LEDMATRIX_WIDTH / 2 - 7)
return;
// only draw if char is visible
if ( 8 + x + idx * 8 > 0)
drawSprite( font[c], x + idx * 8, y, 8, 8 );
}
}
void DrawTextBoth(char* text, int len, int x, int y ) {
for ( int idx = 0; idx < len; idx ++ )
{
int c = text[idx] - 32;
// stop if char is outside visible area
if ( x + idx * 8 > LEDMATRIX_WIDTH / 2)
return;
// only draw if char is visible
if ( 8 + x + idx * 8 > 0)
drawSprite2( font[c], x + idx * 8, y, 8, 8 );
}
}
void drawSprite( byte* sprite, int x, int y, int width, int height ) {
// The mask is used to get the column bit from the sprite row
byte mask = B10000000;
for ( int iy = 0; iy < height; iy++ )
{
for ( int ix = 0; ix < width; ix++ )
{
lmd.setPixel(x + ix, y + iy, (bool)(sprite[iy] & mask ));
// shift the mask by one pixel to the right
mask = mask >> 1;
}
// reset column mask
mask = B10000000;
}
lmd.display();
}
void drawSprite2( byte* sprite, int x, int y, int width, int height ) {
// The mask is used to get the column bit from the sprite row
byte mask = B10000000;
for ( int iy = 0; iy < height; iy++ )
{
for ( int ix = 0; ix < width; ix++ )
{
lmd2.setPixel(x + ix, y + iy, (bool)(sprite[iy] & mask ));
// shift the mask by one pixel to the right
mask = mask >> 1;
}
// reset column mask
mask = B10000000;
}
lmd2.display();
}
void drawString(char* text, int len, int x, int y ) {
for ( int idx = 0; idx < len; idx ++ )
{
int c = text[idx] - 32;
// stop if char is outside visible area
if ( x + idx * 8 > LEDMATRIX_WIDTH )
return;
// only draw if char is visible
if ( 8 + x + idx * 8 > 0 )
drawSprite( font[c], x + idx * 8, y, 8, 8 );
}
}
| true |
183eb32fa4ac10b6ded94a177434c696484d83a6 | C++ | helfo2/UFMG-CP-training | /rot1201.cpp | UTF-8 | 1,871 | 2.75 | 3 | [] | no_license | /* Nome: Henrique Eustaquio Lopes Ferreira
* Matricula: 2015068990
* Problema resolvido: UVA NAO CADASTRA
* Roteiro 12 - Problema
* Estratégias:
*/
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <list>
using namespace std;
#define sz(a) int((a).size())
#define pb push_back
#define mp make_pair
#define p push
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define sc(a) scanf("%d", &a)
#define sc2(a, b) scanf("%d%d", &a, &b)
#define sc3(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define scs(a) scanf("%s", a)
#define pri(x) printf("%d\n", x)
#define prie(x) printf("%d ", x)
#define BUFF ios::sync_with_stdio(false);
#define db(x) cerr << #x << " == " << x << endl
#define fr(i, L) for(int i = 0; i < L; i++)
typedef long long int ll;
typedef long double ld;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef vector<ii> vii;
typedef vector< vii> vvii;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fll;
const ld pi = acos(-1);
const int MOD = 1e9 + 9;
using namespace std;
int count(vi& c, int m) {
vi a(m + 1, 0);
a[0] = 1;
for(int i = 0; i < 5; i++) {
for(int j = c[i]; j <= m; j++) {
a[j] += a[j - c[i]];
}
}
return a[m];
}
int main(void) {
int n, m;
vi c(5);
c[0] = 1; c[1] = 5; c[2] = 10; c[3] = 25; c[4] = 50;
sc(n);
m = count(c, n);
if(m != 1)
printf("There are %d ways to produce %d cents change.\n", m, n);
else
printf("There is only 1 way to produce %d cents change.\n", n);
return 0;
} | true |
993b1d4998263e1fdb090eceb895fdf9e3292cf7 | C++ | wnykuang/studycpp | /chapt5/practise/problem10.cpp | UTF-8 | 449 | 3.40625 | 3 | [] | no_license | #include <iostream>
int main(){
using namespace std;
int rows;
cout << "Enter number of rows: ";
cin >> rows;
int row;
for (row = 0; row < rows; ++ row){
int numberofdot = rows - row - 1;
int numberofstar = row + 1;
for(int i = 0; i < numberofdot; ++i){
cout << ".";
}
for(int i = 0; i < numberofstar; ++i){
cout << "*";
}
cout <<'\n';
}
}
| true |
f4ab8e5868e92bed8fbed232e2a463f75031c176 | C++ | LauraDiosan-CS/lab04-aygean219 | /labul4/repo.cpp | UTF-8 | 799 | 2.78125 | 3 | [] | no_license | #include "Repo.h"
Repo::Repo() {
this->n = 0;
}
Repo::~Repo() {
this->n = 0;
}
void Repo::deleteElem(Produs s)
{
int i = findElem(s);
if (i != -1)
{
produse[i] = produse[n - 1];
n--;
}
}
int Repo::findElem(Produs s)
{
for (int i = 0; i < n; i++)
if (produse[i] == s) return i;
return -1;
}
void Repo::addProdus(Produs p) {
this->produse[this->n++] = p;
}
void Repo::updateElem(Produs s, char* n,int pret,int zi,int luna,int an)
{
int i = findElem(s);
produse[i].setNume(n);
produse[i].setPret(pret);
produse[i].setZi(zi);
produse[i].setLuna(luna);
produse[i].setAn(an);
}
Produs* Repo::getAll() {
return this->produse;
}
Produs Repo::getElem(int pos) {
return this->produse[pos];
}
int Repo::getSize() {
return this->n;
} | true |
a4ad2b53e019421db42c9059c95e47bc078ca183 | C++ | JustWhit3/SAFD-algorithm | /test/test_functions.cpp | UTF-8 | 8,935 | 2.53125 | 3 | [
"MIT"
] | permissive | //============================================
// Preprocessor directives
//============================================
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#define DOCTEST_CONFIG_SUPER_FAST_ASSERTS
//============================================
// Headers
//============================================
//My headers
#include "../include/functions.hpp"
#include "../include/utils.hpp"
//Extra headers
#include <doctest/doctest.h>
#include <arsenalgear/math.hpp>
//STD headers
#include <stdexcept>
#include <algorithm>
#include <cmath>
#include <complex>
//============================================
// "Leg_pol" function testing
//============================================
TEST_CASE( "Testing the Leg_pol function" ) // 100% working
{
CHECK_EQ( safd::Leg_pol( 2, 0.3 ), -0.365 );
CHECK_EQ( safd::Leg_pol( 0, 0.6 ), 1 );
CHECK_EQ( safd::Leg_pol( 1, 0.6 ), 0.6 );
CHECK_EQ( round( safd::Leg_pol( 6, 0.6 ) * 100.0 ) / 100.0, 0.17 );
CHECK_THROWS_AS( safd::Leg_pol( -2, 3 ), std::runtime_error );
}
//============================================
// "Leg_func" function testing
//============================================
TEST_CASE( "Testing the Leg_func function" ) // 100% working
{
SUBCASE( "Testing for b == 0" )
{
CHECK_EQ( round( safd::Leg_func( 0, 0, 0.3 ) * 100.0 ) / 100.0, 1 );
CHECK_EQ( round( safd::Leg_func( 0, 1, 0.3 ) * 100.0 ) / 100.0, 0.3 );
CHECK_EQ( round( safd::Leg_func( 0, 2, 0.3 ) * 100.0 ) / 100.0, -0.37 );
}
SUBCASE( "Testing for 1 <= b <= 3" )
{
CHECK_EQ( round( safd::Leg_func( 1, 1, 0.5 ) * 100.0 ) / 100.0, -0.87 );
CHECK_EQ( round( safd::Leg_func( 1, 2, -0.3 ) * 100.0 ) / 100.0, 0.86 );
CHECK_EQ( round( safd::Leg_func( 3, 4, 0.9 ) * 100.0 ) / 100.0, -7.83 - 0.01 );
CHECK_EQ( round( safd::Leg_func( 2, 2, 0.5 ) * 100.0 ) / 100.0, 2.25 );
}
SUBCASE( "Testing for b >= 4 and |b-a| <= 1" )
{
CHECK( agr::IsInBounds( safd::Leg_func( 4, 5, 0.5 ), 260.0, 270.0 ) );
CHECK( agr::IsInBounds( safd::Leg_func( 6, 6, 0.005 ), 10380.0, 10400.0 ) );
CHECK( agr::IsInBounds( safd::Leg_func( 7, 8, 0.5 ), -370300.0, -369800.0 ) );
CHECK( agr::IsInBounds( safd::Leg_func( 10, 11, 0.5 ), 1631080449.0, 1638080449.0 ) );
}
SUBCASE( "Testing for b >= 4 and |b-a| > 1" ) //Start loosing accuracy. Tests are not precise, but acceptable.
{
//CHECK_EQ( round( safd::Leg_func( 4, 6, 0.5 ) * 1.0 ) / 1.0, 465.1 );
//CHECK_EQ( round( safd::Leg_func( 6, 8, 0.5 ) * 1.0 ) / 1.0, 78388.9 );
//CHECK_EQ( round( safd::Leg_func( 7, 11, 0.5 ) * 1.0 ) / 1.0, 295075.9 );
}
SUBCASE( "Testing exceptions" )
{
CHECK_THROWS_AS( safd::Leg_func( 1, 2, -3 ), std::runtime_error );
CHECK_THROWS_AS( safd::Leg_func( 1, 2, 3 ), std::runtime_error );
CHECK_THROWS_AS( safd::Leg_func( 3, 2, 0.2 ), std::runtime_error );
CHECK_THROWS_AS( safd::Leg_func( -2, 1, 0.2 ), std::runtime_error );
CHECK_THROWS_AS( safd::Leg_func( -2, -3, 0.2 ), std::runtime_error );
}
}
//============================================
// "sph_arm" function testing
//============================================
TEST_CASE( "Testing the sph_arm function" ) // 100% working
{
SUBCASE( "Testing for m == 0 and l == 0" )
{
std::complex<double> c( 0.28, 0 );
CHECK_EQ( round( safd::sph_arm( 0, 0, M_PI, M_PI ).real() * 100.0 ) / 100.0, c.real() );
CHECK_EQ( round( safd::sph_arm( 0, 0, M_PI, M_PI ).imag() * 100.0 ) / 100.0, c.imag() );
CHECK_EQ( round( safd::sph_arm( 0, 0, 2*M_PI, M_PI ).real() * 100.0 ) / 100.0, c.real() );
CHECK_EQ( round( safd::sph_arm( 0, 0, 2*M_PI, M_PI ).imag() * 100.0 ) / 100.0, c.imag() );
}
SUBCASE( "Testing for m == 0, l == 1 and Theta = 180" )
{
std::complex<double> d( -0.49, 0 );
CHECK_EQ( round( safd::sph_arm( 0, 1, M_PI, M_PI ).real() * 100.0 ) / 100.0, d.real() );
CHECK_EQ( round( safd::sph_arm( 0, 1, M_PI, M_PI ).imag() * 100.0 ) / 100.0, d.imag() );
}
SUBCASE( "Testing for m == 0, l == 2 and Theta = 180" )
{
std::complex<double> e( 0.63, 0 );
CHECK_EQ( round( safd::sph_arm( 0, 2, M_PI, M_PI ).real() * 100.0 ) / 100.0, e.real() );
CHECK_EQ( round( safd::sph_arm( 0, 2, M_PI, M_PI ).imag() * 100.0 ) / 100.0, e.imag() );
}
SUBCASE( "Testing for m == 0, l == 2 and Theta = 30" )
{
std::complex<double> e_2( 0.39, 0 );
CHECK_EQ( round( safd::sph_arm( 0, 2, M_PI/6, M_PI ).real() * 100.0 ) / 100.0, e_2.real() );
CHECK_EQ( round( safd::sph_arm( 0, 2, M_PI/6, M_PI ).imag() * 100.0 ) / 100.0, e_2.imag() );
}
SUBCASE( "Testing for m == 1, l == 1, Theta = 30 and Phi = 60" )
{
std::complex<double> f( -0.09, -0.15 );
CHECK_EQ( round( safd::sph_arm( 1, 1, M_PI/6, M_PI/3 ).real() * 100.0 ) / 100.0, f.real() );
CHECK_EQ( round( safd::sph_arm( 1, 1, M_PI/6, M_PI/3 ).imag() * 100.0 ) / 100.0, f.imag() );
}
SUBCASE( "Testing for m == -1, l == 1, Theta = 30 and Phi = 60" )
{
std::complex<double> f_n( 0.09, -0.15 );
CHECK_EQ( round( safd::sph_arm( -1, 1, M_PI/6, M_PI/3 ).real() * 100.0 ) / 100.0, f_n.real() );
CHECK_EQ( round( safd::sph_arm( -1, 1, M_PI/6, M_PI/3 ).imag() * 100.0 ) / 100.0, f_n.imag() );
}
SUBCASE( "Testing for m == 2, l == 2, Theta = 30 and Phi = 60" )
{
std::complex<double> g( -0.05, 0.08 );
CHECK_EQ( round( safd::sph_arm( 2, 2, M_PI/6, M_PI/3 ).real() * 100.0 ) / 100.0, g.real() );
CHECK_EQ( round( safd::sph_arm( 2, 2, M_PI/6, M_PI/3 ).imag() * 100.0 ) / 100.0, g.imag() );
}
SUBCASE( "Testing for m == 3, l == 4, Theta = 30 and Phi = 60" )
{
std::complex<double> h( 0.14, 0 );
CHECK_EQ( round( safd::sph_arm( 3, 4, M_PI/6, M_PI/3 ).real() * 100.0 ) / 100.0, h.real() );
CHECK_EQ( round( safd::sph_arm( 3, 4, M_PI/6, M_PI/3 ).imag() * 100.0 ) / 100.0, h.imag() );
}
SUBCASE( "Testing for m == 5, l == 5, Theta = 30 and Phi = 60" )
{
std::complex<double> i( -0.01, 0.01 );
CHECK_EQ( round( safd::sph_arm( 5, 5, M_PI/6, M_PI/3 ).real() * 100.0 ) / 100.0, i.real() );
CHECK_EQ( round( safd::sph_arm( 5, 5, M_PI/6, M_PI/3 ).imag() * 100.0 ) / 100.0, i.imag() );
}
SUBCASE( "Testing for m == 4, l == 5, Theta = 30 and Phi = 60" )
{
std::complex<double> j( -0.04, -0.07 );
CHECK_EQ( round( safd::sph_arm( 4, 5, M_PI/6, M_PI/3 ).real() * 100.0 ) / 100.0, j.real() );
CHECK_EQ( round( safd::sph_arm( 4, 5, M_PI/6, M_PI/3 ).imag() * 100.0 ) / 100.0, j.imag() );
}
SUBCASE( "Testing exceptions" )
{
CHECK_THROWS_AS( safd::sph_arm( 7, 2, M_PI/6, M_PI/3), std::runtime_error );
CHECK_THROWS_AS( safd::sph_arm( 1, -1, M_PI/6, M_PI/3), std::runtime_error );
CHECK_THROWS_AS( safd::sph_arm( -6, 5, M_PI/6, M_PI/3), std::runtime_error );
}
}
//============================================
// "parsed_f" function testing
//============================================
TEST_CASE( "Testing the parsed_f function" ) // 100% working
{
CHECK_EQ( safd::parsed_f( "th + phi", 1, 2 ), 3 );
CHECK_EQ( safd::parsed_f( "cos( th ) - sin( phi )", M_PI, M_PI/2 ), -2 );
CHECK_EQ( safd::parsed_f( "3*( cos( th ) - sin( phi ) )", M_PI, M_PI/2 ), -6 );
double p = safd::parsed_f( "3*( cos( th ) - sin( phi ) )", M_PI, M_PI/2 );
CHECK_EQ( p, -6 );
}
//============================================
// "f_theta_phi" function testing
//============================================
TEST_CASE( "Testing the f_theta_phi function" ) // 100% working
{
CHECK_EQ( round( safd::f_theta_phi_real( "cos( th ) - sin( phi )", 1, 1, M_PI/6, M_PI/4 ) * 10000.0 ) / 10000.0, -0.0097 );
CHECK_EQ( round( safd::f_theta_phi_imag( "cos( th ) - sin( phi )", 1, 1, M_PI/6, M_PI/4 ) * 10000.0 ) / 10000.0, 0.0097 );
CHECK_EQ( round( safd::f_theta_phi_real( "sin( th ) + cos( phi )", 1, 1, M_PI/6, M_PI/3 ) * 1000.0 ) / 1000.0, -0.043 );
CHECK_EQ( round( safd::f_theta_phi_imag( "sin( th ) + cos( phi )", 1, 1, M_PI/6, M_PI/3 ) * 1000.0 ) / 1000.0, 0.075 );
}
//============================================
// "f_m_l" function testing
//============================================
TEST_CASE( "Testing the f_m_l function" )
{
SUBCASE( "Testing for m = 0" )
{
CHECK_EQ( round( safd::f_m_l( "cos( th )", 0, 0 ).real() * 100.0 ) / 100.0, 0.0 );
CHECK_EQ( round( safd::f_m_l( "cos( th )", 0, 0 ).imag() * 100.0 ) / 100.0, 0.0 );
CHECK( agr::IsInBounds( safd::f_m_l( "cos( th )", 0, 1 ).real(), 2.04, 2.065 ) );
CHECK_EQ( round( safd::f_m_l( "cos( th )", 0, 1 ).imag() * 100.0 ) / 100.0, 0.0 );
CHECK( agr::IsInBounds( safd::f_m_l( "pow( cos( th ), 3 )", 0, 1 ).real(), 1.21, 1.24 ) );
CHECK_EQ( round( safd::f_m_l( "pow( cos( th ), 3 )", 0, 1 ).imag() * 100.0 ) / 100.0, 0.0 );
}
SUBCASE( "Testing for m > 0" )
{
//No calculators ara available on the web to test this case, but if all the previous tests worked,
//since this depends on the other one, this should work as well.
}
} | true |
f93980e537953e815ebcaed1d133d6a23303009a | C++ | qicosmos/fibio | /src/fiber/mutex.cpp | UTF-8 | 12,534 | 2.546875 | 3 | [
"BSD-2-Clause"
] | permissive | //
// mutex.cpp
// fibio
//
// Created by Chen Xu on 14-3-4.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#include <fibio/fibers/mutex.hpp>
#include "fiber_object.hpp"
namespace fibio { namespace fibers {
static const auto NOPERM=lock_error(boost::system::errc::operation_not_permitted);
static const auto DEADLOCK=lock_error(boost::system::errc::resource_deadlock_would_occur);
namespace detail {
inline detail::fiber_ptr_t cur_fiber() {
auto cf=current_fiber();
if (cf) {
return cf->shared_from_this();
}
return detail::fiber_ptr_t();
}
}
void mutex::lock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
BOOST_THROW_EXCEPTION(DEADLOCK);
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
return;
}
// This mutex is locked
// Add this fiber into waiting queue
suspended_.push_back(tf);
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->pause(); }
}
void mutex::unlock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_!=tf) {
// This fiber doesn't own the mutex
BOOST_THROW_EXCEPTION(NOPERM);
}
if (suspended_.empty()) {
// Nobody is waiting
owner_.reset();
return;
}
// Set new owner and remove it from suspended queue
std::swap(owner_, suspended_.front());
suspended_.pop_front();
owner_->resume();
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->yield(owner_); }
}
bool mutex::try_lock() {
auto tf=detail::cur_fiber();
if (!tf) return false;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
// This fiber already owns the mutex
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
}
// Return true if this fiber owns the mutex
return owner_==tf;
}
void recursive_mutex::lock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
++level_;
return;
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
assert(suspended_.empty());
assert(level_==0);
owner_=tf;
level_=1;
return;
}
// This mutex is locked
// Add this fiber into waiting queue
suspended_.push_back(tf);
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->pause(); }
}
void recursive_mutex::unlock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_!=tf) {
// This fiber doesn't own the mutex
BOOST_THROW_EXCEPTION(NOPERM);
}
--level_;
if (level_>0) {
// This fiber still owns the mutex
return;
}
if (suspended_.empty()) {
// Nobody is waiting
owner_.reset();
assert(level_==0);
return;
}
// Set new owner and remove it from suspended queue
std::swap(owner_, suspended_.front());
suspended_.pop_front();
level_=1;
owner_->resume();
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->yield(owner_); }
}
bool recursive_mutex::try_lock() {
auto tf=detail::cur_fiber();
if (!tf) return false;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
// This fiber already owns the mutex, increase recursive level
++level_;
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
assert(suspended_.empty());
assert(level_==0);
owner_=tf;
level_=1;
}
// Cannot acquire the lock now
return owner_==tf;
}
void timed_mutex::lock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
BOOST_THROW_EXCEPTION(DEADLOCK);
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
return;
}
// This mutex is locked
// Add this fiber into waiting queue without attached timer
suspended_.push_back({tf, 0});
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->pause(); }
}
bool timed_mutex::try_lock() {
auto tf=detail::cur_fiber();
if (!tf) return false;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
// This fiber already owns the mutex
return true;
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
return true;
}
// Cannot acquire the lock now
return false;
}
void timed_mutex::unlock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_!=tf) {
// This fiber doesn't own the mutex
BOOST_THROW_EXCEPTION(NOPERM);
}
if (suspended_.empty()) {
// Nobody is waiting
owner_.reset();
return;
}
// Set new owner and remove it from suspended queue
std::swap(owner_, suspended_.front().f_);
detail::timer_t *t=suspended_.front().t_;
suspended_.pop_front();
if (t) {
// Cancel attached timer, the timer handler will schedule new owner
t->cancel();
} else {
// No attached timer, directly schedule new owner
owner_->resume();
}
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->yield(owner_); }
}
void timed_mutex::timeout_handler(detail::fiber_ptr_t this_fiber,
boost::system::error_code ec)
{
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_!=this_fiber) {
// This fiber doesn't own the mutex
// Find and remove this fiber from waiting queue
auto i=std::find(suspended_.begin(),
suspended_.end(),
this_fiber);
if (i!=suspended_.end()) {
suspended_.erase(i);
}
} else {
// This fiber should not be in the suspended queue, do nothing
}
this_fiber->resume();
}
bool timed_mutex::try_lock_rel(detail::duration_t d) {
auto tf=detail::cur_fiber();
if (!tf) return false;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
BOOST_THROW_EXCEPTION(DEADLOCK);
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
return true;
}
// This mutex is locked
// Add this fiber into waiting queue
detail::timer_t t(tf->get_io_service());
t.expires_from_now(d);
t.async_wait(tf->get_fiber_strand().wrap(std::bind(&timed_mutex::timeout_handler,
this,
tf,
std::placeholders::_1)));
suspended_.push_back({tf, &t});
// This fiber will be resumed when timer triggered/canceled or other called unlock()
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->pause(); }
return owner_==tf;
}
void recursive_timed_mutex::lock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
++level_;
return;
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
level_=1;
return;
}
// This mutex is locked
// Add this fiber into waiting queue without attached timer
suspended_.push_back({tf, 0});
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->pause(); }
}
void recursive_timed_mutex::unlock() {
auto tf=detail::cur_fiber();
if (!tf) return;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_!=tf) {
// This fiber doesn't own the mutex
BOOST_THROW_EXCEPTION(NOPERM);
}
--level_;
if(level_>0) {
// This fiber still owns the mutex
return;
}
if (suspended_.empty()) {
// Nobody is waiting
owner_.reset();
level_=0;
return;
}
// Set new owner and remove it from suspended queue
std::swap(owner_, suspended_.front().f_);
detail::timer_t *t=suspended_.front().t_;
suspended_.pop_front();
level_=1;
if (t) {
// Cancel attached timer, the timer handler will schedule new owner
t->cancel();
} else {
// No attached timer, directly schedule new owner
owner_->resume();
}
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->yield(owner_); }
}
bool recursive_timed_mutex::try_lock() {
auto tf=detail::cur_fiber();
if (!tf) return false;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
// This fiber already owns the mutex, increase recursive level
++level_;
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
level_=1;
}
// Cannot acquire the lock now
return owner_==tf;
}
void recursive_timed_mutex::timeout_handler(detail::fiber_ptr_t this_fiber, boost::system::error_code ec) {
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_!=this_fiber) {
// This fiber doesn't own the mutex
// Find and remove this fiber from waiting queue
auto i=std::find(suspended_.begin(),
suspended_.end(),
this_fiber);
if (i!=suspended_.end()) {
suspended_.erase(i);
}
} else {
// This fiber should not be in the suspended queue, do nothing
}
this_fiber->resume();
}
bool recursive_timed_mutex::try_lock_rel(detail::duration_t d) {
auto tf=detail::cur_fiber();
if (!tf) return false;
std::lock_guard<detail::spinlock> lock(mtx_);
if (owner_==tf) {
++level_;
return true;
} else if(!owner_) {
// This mutex is not locked
// Acquire the mutex
owner_=tf;
level_=1;
return true;
}
// This mutex is locked
// Add this fiber into waiting queue
detail::timer_t t(tf->get_io_service());
t.expires_from_now(d);
t.async_wait(tf->get_fiber_strand().wrap(std::bind(&recursive_timed_mutex::timeout_handler,
this,
tf,
std::placeholders::_1)));
suspended_.push_back({tf, &t});
// This fiber will be resumed when timer triggered/canceled or other called unlock()
{ detail::relock_guard<detail::spinlock> relock(mtx_); tf->pause(); }
return owner_==tf;
}
}} // End of namespace fibio::fibers
| true |
4eba95f7d001d7a7221c30492c048b231f0135ad | C++ | KendrickAng/competitive-programming | /kattis/greedilyincreasing/greedilyincreasing.cpp | UTF-8 | 466 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int n; cin >> n;
int curr = -1;
vector<int> nums;
for (int i = 0; i < n; i++) {
int tmp; cin >> tmp;
if (curr == -1 || tmp > curr) {
nums.push_back(tmp);
curr = tmp;
}
}
cout << nums.size() << endl;
for (int i: nums) cout << i << " ";
cout << endl;
} | true |
ac5253122a3188ea97a9cf923b6ec1441eadcf37 | C++ | cuyi/cpplearn | /time/gnuTimes.cpp | GB18030 | 504 | 2.515625 | 3 | [] | no_license | #include <cstdio>
#include <unistd.h> // unistd.h C C++ ṩ POSIX ϵͳ API ķʹܵͷļ
#include <sys/times.h>
#include "timeConsumingFun.hpp"
int main(void)
{
clock_t tBeginTime = times(NULL);
timeingFunc();
clock_t tEndTime = times(NULL);
double milliseconds = (double)(tEndTime - tBeginTime) * 1000 / sysconf(_SC_CLK_TCK);
printf("[times] Cost Time = %fms\n", milliseconds);
return 0;
}
| true |
e5f1f3005a211b30ff917de385dcfd8111ccd966 | C++ | najosky/opendarkeden_server | /src/server/gameserver/ParkingCenter.h | UTF-8 | 3,302 | 2.625 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
// Filename : ParkingCenter.h
// Written By : Reiot
// Description :
//////////////////////////////////////////////////////////////////////////////
#ifndef __PARKING_CENTER_H__
#define __PARKING_CENTER_H__
#include "Types.h"
#include "Exception.h"
#include "Zone.h"
#include "item/Motorcycle.h"
#include "Mutex.h"
#include <map>
#include <list>
//////////////////////////////////////////////////////////////////////////////
// class MotorcycleBox
//////////////////////////////////////////////////////////////////////////////
class MotorcycleBox
{
public:
MotorcycleBox(Motorcycle* pMotorcycle, Zone* pZone, ZoneCoord_t X, ZoneCoord_t Y) throw();
virtual ~MotorcycleBox() throw();
public:
Motorcycle* getMotorcycle() throw() { return m_pMotorcycle; }
void setMotorcycle(Motorcycle* pMotorcycle) throw() { m_pMotorcycle = pMotorcycle; }
Zone* getZone() const throw() { return m_pZone; }
void setZone(Zone* pZone) throw() { m_pZone = pZone; }
ZoneCoord_t getX() const throw() { return m_X; }
void setX(ZoneCoord_t X) throw() { m_X = X; }
ZoneCoord_t getY() const throw() { return m_Y; }
void setY(ZoneCoord_t Y) throw() { m_Y = Y; }
ItemID_t getItemID() const throw() { return m_pMotorcycle->getItemID(); }
// �ٸ� zone��� �̵����� ��������
bool isTransport() const throw() { return m_bTransport; }
void setTransport(bool bTransport=true) { m_bTransport = bTransport; }
private:
// ��������Ŭ ��ü
Motorcycle* m_pMotorcycle;
// ���� ��������Ŭ�� �ִ� �ġ
Zone* m_pZone;
ZoneCoord_t m_X;
ZoneCoord_t m_Y;
// �ٸ� zone��� �̵� ��. by sigi. 2002.5.23
bool m_bTransport;
};
//////////////////////////////////////////////////////////////////////////////
// class ParkingCenter;
//////////////////////////////////////////////////////////////////////////////
class ParkingCenter
{
public:
ParkingCenter() throw();
virtual ~ParkingCenter() throw();
public:
void addMotorcycleBox(MotorcycleBox* pMotorcycleBox) throw(DuplicatedException, Error);
// ���⼭ keyID�� ������ TargetID�� ���Ѵ�. ���� Motorcycle�� ItemID�̱ �ϴ�.
void deleteMotorcycleBox(ItemID_t keyTargetID) throw(NoSuchElementException, Error);
// ���⼭ keyID�� ������ TargetID�� ���Ѵ�. ���� Motorcycle�� ItemID�̱ �ϴ�.
bool hasMotorcycleBox(ItemID_t keyTargetID) throw(NoSuchElementException, Error);
// ���⼭ keyID�� ������ TargetID�� ���Ѵ�. ���� Motorcycle�� ItemID�̱ �ϴ�.
MotorcycleBox* getMotorcycleBox(ItemID_t keyTargetID) const throw(NoSuchElementException, Error);
// �ַ� RemoveMotorcycles�� ó�����ش�. by sigi. 2003.2.26
void heartbeat() throw (Error);
private:
// ���⼭ ItemID_t�� ���������� ItemID�� ���Ѵ�.
map< ItemID_t, MotorcycleBox* > m_Motorcycles;
list< MotorcycleBox* > m_RemoveMotorcycles;
mutable Mutex m_Mutex;
mutable Mutex m_MutexRemove;
};
// global variable declaration
extern ParkingCenter* g_pParkingCenter;
#endif
| true |
5e003b07e6d45bf1b3622d0bcf7b86ac41b87ad6 | C++ | candidate2020/AccCppSolnMan | /Chap6/is_palindrome.cpp | UTF-8 | 138 | 2.65625 | 3 | [] | no_license |
#include<string>
#include<algorithm>
bool is_palindrome(const std::string& s){
return std::equal(s.begin(), s.end(), s.rbegin());
}
| true |
029c4ed77c5294a1c5ef96a0113f3e4aa2de06d0 | C++ | SlickHackz/famous-problems-cpp-solutions | /04 Heap/Source Files/MergeksortedArrays-useHeap.cpp | UTF-8 | 2,845 | 3.703125 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct node
{
int data;
int row;
int next;
};
class MinHeap
{
struct node *heaparr;
int heapsize;
int cursize;
public :
MinHeap(int n);
int getParent(int i);
int getLeft(int i);
int getRight(int i);
void insertKey(struct node a);
struct node getMin();
void Heapify(int i);
struct node replaceMin(struct node a);
};
MinHeap::MinHeap(int n)
{
heaparr = new struct node[n];
heapsize = n;
cursize = 0;
}
int MinHeap::getParent(int i)
{
return (i-1)/2;
}
int MinHeap::getLeft(int i)
{
return 2*i+1;
}
int MinHeap::getRight(int i)
{
return 2*i+2;
}
void MinHeap::insertKey(struct node temp)
{
if(cursize==heapsize)
{
cout<<"\n Heap is full! \n";
return;
}
heaparr[cursize] = temp;
cursize++;
Heapify(0);
return;
}
struct node MinHeap::getMin()
{
struct node temp;
temp.data = -1;
temp.row = -1;
temp.next = -1;
if(cursize==0)
return temp;
return heaparr[0];
}
struct node MinHeap::replaceMin(struct node x)
{
struct node root = heaparr[0];
heaparr[0] = x;
Heapify(0);
return root;
}
void Swap(struct node *a,struct node *b)
{
if(a!=b)
{
struct node temp = *a;
*a = *b;
*b = temp;
}
}
void MinHeap::Heapify(int i)
{
int small = i;
int left = getLeft(i);
int right = getRight(i);
if(left < cursize && heaparr[left].data < heaparr[small].data)
small = left;
if (right < cursize && heaparr[right].data < heaparr[small].data)
small = right;
if(small!=i)
{
Swap(&heaparr[small],&heaparr[i]);
Heapify(small);
}
}
int main()
{
int arr[][4] = { {1,3,5,7},
{2,4,6,8},
{0,9,10,11} };
int R=sizeof(arr)/sizeof(arr[0]);
int C=sizeof(arr[0])/sizeof(arr[0][0]);
//cout<<"Rows : "<<R<<" Cols : "<<C<<endl;
MinHeap heap(R);
for(int i=0 ; i<=R-1 ; i++)
{
struct node temp = {arr[i][0],i,1};
heap.insertKey(temp);
}
for(int i=0 ; i<=R*C-1 ; i++)
{
// 1. Get the min node and print it
struct node cur = heap.getMin();
cout<<cur.data<<" ";
struct node nextnode;
// 2. Create a temporary node which is the next node to be inserted into the heap
if(cur.next <= C-1)
nextnode.data = arr[cur.row][cur.next];
else
nextnode.data = 99999;
nextnode.row = cur.row;
nextnode.next = cur.next+1;
// 3. Replace the top node with the temp node created in step 2! Dont forget to Heapify()!
heap.replaceMin(nextnode);
}
cin.get();
return 0;
}
| true |
79ac4af75ca815f5cdb07f385c3d7f079fa8496a | C++ | myjc/TinySTL | /HashTable.h | UTF-8 | 4,837 | 3 | 3 | [] | no_license | #ifndef TINYSTL_HASH_TABLE_H
#define TINYSTL_HASH_TABLE_H
#include "Iterator.h"
#include "Allocator.h"
#include "Vector.h"
#include "List.h"
namespace TinySTL
{
//hashtable元素节点
template<typename T>
struct HashTableNode
{
T data_;
HashTableNode* nextNode_;
HashTableNode():nextNode_(nullptr){}
};
//HashTable 前置声明
template<typename Value,typename Key,typename HashFunc,
typename Extractkey,typename EqualKey,typename Alloc = alloc>
class HashTable;
//迭代器
template<typename Value,typename Key,typename HashFunc,
typename Extractkey,typename EqualKey,typename Alloc>
class HashTableIterator
{
public:
typedef forward_iterator_tag iterator_category;
typedef Value value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef HashTableNode<Value> Node;
typedef HashTable<Value,Key,HashFunc,Extractkey,EqualKey,Alloc> Table;
typedef ListIterator<Value> local_iterator;
public:
local_iterator cur_;
Table* table_;
size_type bk_index_;
public:
HashTableIterator(local_iterator iter,Table* table,size_type index):
cur_(iter),table_(table),bk_index_(index){}
HashTableIterator() = default;
~HashTableIterator() = default;
reference operator*(){ return *cur_;}
pointer operator->(){return &(operator*());}
HashTableIterator& operator++();
HashTableIterator operator++(int);
bool operator==(const HashTableIterator& iter){return cur_ = iter.cur_;}
bool operator!= (const HashTableIterator& iter){return cur_ != iter.cur_;}
};
template<typename Value,typename Key,typename HashFunc,
typename Extractkey,typename EqualKey,typename Alloc>
class HashTable
{
public:
typedef size_t size_type;
typedef Value value_type;
typedef Key key_type;
typedef HashTableIterator<Value,Key,HashFunc,Extractkey,EqualKey,Alloc> iterator;
typedef typename iterator::difference_type difference_type;
typedef typename iterator::pointer pointer;
typedef typename iterator::reference reference;
typedef typename List<Value>::iterator local_iterator;
typedef HashFunc hasher;
typedef EqualKey key_equal;
private:
hasher hasher_;
Extractkey extractkey_;
key_equal equaler_;
Vector<List<Value>> buckets_;
size_type num_elements_;
float max_load_factor_;
public:
HashTable():max_load_factor_(1.0){}
HashTable(size_type n,const HashFunc& hashfunc,const EqualKey& eql)
{
initialize_buckets(n);
}
~HashTable(){ clear();}
public:
size_type buckets_count(){ return buckets_.size();}
size_type buckets_size(size_type index){ return buckets_[index].size();}
iterator begin();
iterator end();
local_iterator begin(size_type n);
local_iterator end(size_type n);
size_type count(const key_type&);
iterator find(const key_type&);
size_type size()const{ return num_elements_;}
bool empty()const{ return num_elements_ == 0;}
float load_factor(){ return static_cast<float>(num_elements_) / buckets_.size();}
size_type max_load_factor() { return max_load_factor_;}
void max_load_factor(float factor){ max_load_factor_ = factor;}
Pair<iterator,bool> insert_unique(const value_type&);
iterator insert_equal(const value_type&);
void clear();
void swap(HashTable& ht)
{
buckets_.swap(ht.buckets_);
TinySTL::swap(num_elements_,ht.num_elements_);
TinySTL::swap(max_load_factor_,ht.max_load_factor_);
}
private:
static const int stl_num_prime_ = 28;
constexpr static const unsigned int primes_list[stl_num_prime_] =
{
53,97,193,389,769,1543,3079,6151,12289,24593,49157,98317,196613,393241,786433,1572869,
3145739,6291469,1258917,25165843,50331653,100663919,201326611,402653189,805306457,
1610612741,3221225473,4294967291
};
unsigned long next_prime(unsigned long n)
{
const unsigned long* first = primes_list;
const unsigned long* last = primes_list + stl_num_prime_;
const unsigned long* pos = TinySTL::lower_bound(first,last,n);
return pos == last ? *(last - 1) : *pos;
}
size_type max_buckets_count(){ return primes_list[stl_num_prime_ - 1];}
void rehash(size_type num);
void initialize_buckets(size_type n)
{
const size_type size = next_prime(n);
buckets_.reserve(n);
buckets_.insert(buckets_.end(),size,List<Value>());
}
size_type buckets_index(const value_type& val,size_type n);
size_type buckets_index(const value_type& val);
size_type buckets_index_key(const key_type& val,size_type n);
size_type buckets_index_key(const key_type& val);
};
}
#endif // TINYSTL_HASH_TABLE_H
| true |
29f78dec6727562a69e9fbb3fb31a77009f8cc4e | C++ | SRombauts/SimplexNoiseCImg | /color.h | UTF-8 | 605 | 3.359375 | 3 | [] | no_license |
#include <cstdint>
class color3f
{
public:
color3f();
color3f(uint8_t _r, uint8_t _g, uint8_t _b);
public:
float r;
float g;
float b;
};
inline float lerp(float x, float y, float a)
{
return (1 - a) * x + a * y;
}
inline float lerp(float x, float y,
float ax, float ay, float a)
{
return (ay - a)/(ay - ax) * x
+ (a - ax)/(ay - ax) * y;
}
color3f lerp(color3f x, color3f y, float a);
color3f lerp(color3f x, color3f y,
float ax, float ay, float a);
/**
* @param[in] noise [-1; 1]
*
* @return color
*/
color3f ramp(float noise);
| true |
aa7bb1a4789430b5b33055d6e3abd750f41bf387 | C++ | Kurorororo/pplanner | /src/multithread_search/lock_free_closed_list.h | UTF-8 | 4,433 | 2.875 | 3 | [] | no_license | #ifndef LOCK_FREE_CLOSED_LIST_H_
#define LOCK_FREE_CLOSED_LIST_H_
#include <atomic>
#include <fstream>
#include <unordered_set>
#include <utility>
#include <vector>
#include "sas_plus.h"
#include "search_graph/state_packer.h"
#include "search_node.h"
namespace pplanner {
struct SearchNodeWithNext : public SearchNode {
std::shared_ptr<SearchNodeWithNext> next;
};
template <typename T = SearchNodeWithNext>
class LockFreeClosedList {
public:
LockFreeClosedList(int exponent = 26)
: mask_((1u << exponent) - 1), closed_(1 << exponent) {
Init();
}
bool IsClosed(uint32_t hash,
const std::vector<uint32_t>& packed_state) const {
return Find(hash, packed_state) != nullptr;
}
bool Close(std::shared_ptr<T> node);
std::shared_ptr<T> Find(uint32_t hash,
const std::vector<uint32_t>& packed_state) const;
std::pair<std::shared_ptr<T>, std::shared_ptr<T> > Find(
std::size_t head_index, const std::vector<uint32_t>& packed_state) const;
void Dump(std::shared_ptr<const SASPlus> problem,
std::shared_ptr<const StatePacker> packer) const;
private:
void Init();
uint32_t mask_;
std::vector<std::shared_ptr<T> > closed_;
};
/***
* Michael, M., 2002.
* High Performance Dynamic Lock-Free Hash Tables and List-Based Sets
* In state space search, there is no need for deletion of nodes in closed
* lists, so we did not implement marking and deletion.
* In addition, it is dirty that each mark uses the lowest bit of the pointer.
*/
template <typename T>
void LockFreeClosedList<T>::Init() {
for (int i = 0, n = closed_.size(); i < n; ++i) closed_[i] = nullptr;
}
template <typename T>
bool LockFreeClosedList<T>::Close(std::shared_ptr<T> node) {
std::size_t i = node->hash & mask_;
while (true) {
auto p = Find(i, node->packed_state);
auto cur = p.first;
auto prev = p.second;
if (cur != nullptr && cur->packed_state == node->packed_state) return false;
node->next = cur;
if (prev == nullptr) {
if (std::atomic_compare_exchange_weak(&closed_[i], &cur, node))
return true;
} else if (std::atomic_compare_exchange_weak(&prev->next, &cur, node)) {
return true;
}
}
}
template <typename T>
std::shared_ptr<T> LockFreeClosedList<T>::Find(
uint32_t hash, const std::vector<uint32_t>& packed_state) const {
std::size_t i = hash & mask_;
auto p = Find(i, packed_state);
if (p.first == nullptr) return nullptr;
return packed_state == p.first->packed_state ? p.first : nullptr;
}
template <typename T>
std::pair<std::shared_ptr<T>, std::shared_ptr<T> > LockFreeClosedList<T>::Find(
std::size_t head_index, const std::vector<uint32_t>& packed_state) const {
while (true) {
std::shared_ptr<T> prev = closed_[head_index];
if (prev == nullptr) return std::make_pair(nullptr, nullptr);
auto cur = prev->next;
if (closed_[head_index] != prev) continue;
if (prev->packed_state >= packed_state)
return std::make_pair(prev, nullptr);
while (true) {
if (cur == nullptr) return std::make_pair(nullptr, prev);
auto next = cur->next;
if (prev->next != cur) break;
if (cur->packed_state >= packed_state) return std::make_pair(cur, prev);
prev = cur;
cur = next;
}
}
}
template <typename T>
void LockFreeClosedList<T>::Dump(
std::shared_ptr<const SASPlus> problem,
std::shared_ptr<const StatePacker> packer) const {
std::ofstream expanded_nodes;
expanded_nodes.open("expanded_nodes.csv", std::ios::out);
expanded_nodes << "node_id,parent_node_id,h,action,timestamp";
for (int i = 0; i < problem->n_variables(); ++i) expanded_nodes << ",v" << i;
expanded_nodes << std::endl;
std::vector<int> state(problem->n_variables());
for (auto list : closed_) {
std::shared_ptr<T> node = list;
while (node != nullptr) {
int node_id = node->id;
int parent_id = node->parent == nullptr ? -1 : node->parent->id;
int h = node->h;
expanded_nodes << node_id << "," << parent_id << "," << h << ","
<< node->action << "," << node_id;
packer->Unpack(node->packed_state.data(), state);
for (int j = 0; j < problem->n_variables(); ++j)
expanded_nodes << "," << state[j];
expanded_nodes << std::endl;
node = node->next;
}
}
}
} // namespace pplanner
#endif // LOCK_FREE_CLOSED_LIST_H_
| true |
17ce33949aad319bfcef360ffae7288d1babfb6b | C++ | riverlight/lport | /libport/testport/testport.cpp | UTF-8 | 1,407 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "port.h"
#define THRERA_NUM 10
#define THREAD_RUN_TIME 1000
#define THREAD_SLEEP_TIME 10
static void* thread_process(void *arg);
HMutex mutex = NULL;
int main(int argc, char *argv[])
{
int counter = 0;
HThread hThread[THRERA_NUM];
int id[THRERA_NUM];
memset(hThread, 0, THRERA_NUM*sizeof(HThread));
memset(id, 0, THRERA_NUM*sizeof(int));
if (NULL != (mutex = mutex_create()))
{
printf("Create mutex successfully\r\n\r\n");
}
else
{
printf("Could not create mutex\r\n\r\n");
return -1;
}
for (counter=0; counter<THRERA_NUM; counter++)
{
id[counter] = counter+1;
if (NULL == (hThread[counter] = thread_create(thread_process, id+counter)))
{
printf("Could not create %d thread\r\n\r\n", counter);
}
else
{
printf("Create %d thread successfully\r\n\r\n", counter);
}
}
for (counter=0; counter<THRERA_NUM; counter++)
{
if (NULL != hThread[counter])
{
thread_destroy(hThread[counter]);
printf("Destroy %d thread\r\n\r\n", counter);
}
}
mutex_destroy(mutex);
#ifdef WIN32
system("pause");
#endif
return 0;
}
static void* thread_process(void *arg)
{
int threadId = *((int*)arg);
for (int i=1; i<THREAD_RUN_TIME; i++)
{
mutex_lock(mutex);
printf("The %d thread have run %d times\r\n", threadId, i);
mutex_unlock(mutex);
port_sleep(THREAD_SLEEP_TIME);
}
return NULL;
}
| true |
9906e0acd631a639f1c99bd350aef91f3b6ac02c | C++ | llwwjjj/Lwj_stl | /sequence containers/Lwj_heap.h | UTF-8 | 7,855 | 3.03125 | 3 | [] | no_license | //
// Lwj_heap.h
// S
//
// Created by 练文健 on 2018/5/30.
// Copyright © 2018年 练文健. All rights reserved.
//
#ifndef Lwj_heap_h
#define Lwj_heap_h
namespace Lwj_stl{
//-----------------------------------------------push_heap-------------------------------------------------------------
//先对vector进行push_back后使用push_heap进行调度
template <class RandomAccessIterator>
inline void push_heap(RandomAccessIterator first,RandomAccessIterator last){
__push_heap_aux(first,last,distance_type(first),value_type(first));
}
template<class RandomAccessIterator,class Distance,class T>
inline void __push_heap_aux(RandomAccessIterator first,RandomAccessIterator last,Distance*,T*){
__push_heap(first,Distance((last-first)-1),Distance(0),T(*(last-1)));
}
template<class RandomAccessIterator,class Distance,class T>
void __push_heap(RandomAccessIterator first,Distance holeIndex,Distance topIndex,T value){
Distance parent=(holeIndex-1)/2;//找到父节点
while(holeIndex > topIndex && *(first+parent)<value){
//当尚未达到顶端,且父节点小于新值时,交换
*(first+holeIndex)=*(first+parent);//父值给洞值
holeIndex=parent;//洞号调整
parent=(holeIndex-1)/2;//调整父号
}
*(first+holeIndex)=value;//新值给洞值
}
template <class RandomAccessIterator, class Distance, class T, class Compare>
void __push_heap(RandomAccessIterator first, Distance holeIndex,
Distance topIndex, T value, Compare comp) {
Distance parent = (holeIndex - 1) / 2;
while (holeIndex > topIndex && comp(*(first + parent), value)) {
*(first + holeIndex) = *(first + parent);
holeIndex = parent;
parent = (holeIndex - 1) / 2;
}
*(first + holeIndex) = value;
}
template <class RandomAccessIterator, class Compare, class Distance, class T>
inline void __push_heap_aux(RandomAccessIterator first,
RandomAccessIterator last, Compare comp,
Distance*, T*) {
__push_heap(first, Distance((last - first) - 1), Distance(0),
T(*(last - 1)), comp);
}
template <class RandomAccessIterator, class Compare>
inline void push_heap(RandomAccessIterator first, RandomAccessIterator last,
Compare comp) {
__push_heap_aux(first, last, comp, distance_type(first), value_type(first));
}
//--------------------------------------------------adjust_heap---------------------------------------------------------
template<class RandomAccessIterator,class Distance,class T>
void __adjust_heap(RandomAccessIterator first,Distance holeIndex,Distance len,T value){
Distance topIndex=holeIndex;
Distance secondChild=2*(holeIndex+1);
while(secondChild<len){
//比较两节点大小
if(*(first+secondChild) < *(first+secondChild-1))
secondChild--;
//令较大值为洞值,再令洞号下移至较大字节点处
*(first+holeIndex) = *(first+secondChild);
holeIndex=secondChild;
secondChild=2*(holeIndex+1);//字节点中的右节点
}
if (secondChild == len) { // 沒有右子節點,只有左子節點
// Percolate down:令左子值為洞值,再令洞號下移至左子節點處。
*(first + holeIndex) = *(first + (secondChild - 1));
holeIndex = secondChild - 1;
}
__push_heap(first, holeIndex, topIndex, value);//可能此时尚未满足次序特性,需要执行一次push_heap操作
}
template <class RandomAccessIterator, class Distance, class T, class Compare>
void __adjust_heap(RandomAccessIterator first, Distance holeIndex,
Distance len, T value, Compare comp) {
Distance topIndex = holeIndex;
Distance secondChild = 2 * holeIndex + 2;
while (secondChild < len) {
if (comp(*(first + secondChild), *(first + (secondChild - 1))))
secondChild--;
*(first + holeIndex) = *(first + secondChild);
holeIndex = secondChild;
secondChild = 2 * (secondChild + 1);
}
if (secondChild == len) {
*(first + holeIndex) = *(first + (secondChild - 1));
holeIndex = secondChild - 1;
}
__push_heap(first, holeIndex, topIndex, value, comp);
}
//--------------------------------------------------pop_heap------------------------------------------------------------
//首先设定欲调整值为尾值,然后将首值调整置尾节点,然后重整
template <class RandomAccessIterator>
inline void pop_heap(RandomAccessIterator first,RandomAccessIterator last){
__pop_heap_aux(first,last,value_type(first));
}
template<class RandomAccessIterator,class T>
inline void __pop_heap_aux(RandomAccessIterator first,RandomAccessIterator last,T*){
__pop_heap(first,last-1,last-1,T(*(last-1)),distance_type(first));
}
template<class RandomAccessIterator,class Distance,class T>
inline void __pop_heap(RandomAccessIterator first,RandomAccessIterator last,RandomAccessIterator result,T value,Distance holeIndex){
*result=*first;//设定尾值为首值,又pop_back()取出尾值
__adjust_heap(first,Distance(0),Distance(last-first),value);//重新调整
}
template <class RandomAccessIterator, class T, class Compare, class Distance>
inline void __pop_heap(RandomAccessIterator first, RandomAccessIterator last,
RandomAccessIterator result, T value, Compare comp,
Distance*) {
*result = *first;
__adjust_heap(first, Distance(0), Distance(last - first), value, comp);
}
template <class RandomAccessIterator, class T, class Compare>
inline void __pop_heap_aux(RandomAccessIterator first,
RandomAccessIterator last, T*, Compare comp) {
__pop_heap(first, last - 1, last - 1, T(*(last - 1)), comp,
distance_type(first));
}
template <class RandomAccessIterator, class Compare>
inline void pop_heap(RandomAccessIterator first, RandomAccessIterator last,
Compare comp) {
__pop_heap_aux(first, last, value_type(first), comp);
}
//--------------------------------------------------------------------------------------------------------------------------
template<class RandomAccessIterator>
void sort_heap(RandomAccessIterator first,RandomAccessIterator last){
//每执行一次pop_heap就把当前范围内最大值放尾端,且每次把范围减一
while(last-first>1)
pop_heap(first,last--);
}
template <class RandomAccessIterator, class Compare>
inline void make_heap(RandomAccessIterator first, RandomAccessIterator last,
Compare comp) {
__make_heap(first, last, comp, value_type(first), distance_type(first));
}
//将一段现有的数据转化为一个heap
template<class RandomAccessIterator,class T,class Distance>
void __make_heap(RandomAccessIterator first,RandomAccessIterator last,T*,Distance*){
if(last-first<2) return;//如果长度为0或1,不必重新排列
Distance len =last-first;
Distance parent=(len-2)/2;
while(true){
__adjust_heap(first,parent,len,T(*(first+parent)));
if(parent==0)
return;
parent--;
}
}
}
#endif /* Myheap_h */
| true |
b1c309d081f83cae378717f1582347e0bc645d85 | C++ | kartikf1/cpp-advance | /input/methods.cpp | UTF-8 | 414 | 3.234375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
class MyClass
{ // The class
public: // Access specifier
void myMethod()
{ // Method/function
cout << "Hello World!";
cout << "hello universe\n";
}
};
int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
system("pause");
return 0;
}
// Added comment
// This is second comment | true |
44eb463194f70d8eea27194be0ace1a0e2fc5b23 | C++ | linvon/QQ | /server/main.cpp | UTF-8 | 560 | 2.625 | 3 | [] | no_license | #include "widget.h"
#include <QtGui/QApplication>
#include <QtCore/QTextCodec>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//确保只运行一次
QSystemSemaphore sema("ServerKey",1,QSystemSemaphore::Open);
//在临界区操作共享内存
sema.acquire();
QSharedMemory mem("ServerObject");
// 如果全局对象已存在则退出
if (!mem.create(1))
{
QMessageBox::warning(NULL, "error","A server has already been running.");
sema.release();
return 0;
}
sema.release();
Widget w;
w.show();
return a.exec();
}
| true |
022ba9ff65f15bc09c21499c1d76664ee640109f | C++ | TsvetinaRasheva/Tasks-_C- | /Tasks_28.10/Zadacha_3.cpp | UTF-8 | 480 | 3.484375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int number;
cout << "Number : ";
cin >> number;
int fib_first, fib_second;
fib_first = 0;
fib_second = 1;
cout << "Fibonachi numbers : " << 0 << " " << 1 << " " << 1;
int next_fib_num = fib_first + fib_second;
while (next_fib_num <= number)
{
fib_first = fib_second;
fib_second = next_fib_num;
next_fib_num = fib_first + fib_second;
cout << " " << next_fib_num;
}
return 0;
}
| true |