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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c3681bdeb49bc477548fdcaf9569a7bcc3c64825 | C++ | InfiniBrains/mobagen | /examples/maze/World.h | UTF-8 | 1,805 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef MOBAGEN_WORLD_H
#define MOBAGEN_WORLD_H
#include "math/ColorT.h"
#include "scene/GameObject.h"
#include "MazeGeneratorBase.h"
#include "Node.h"
#include "math/Point2D.h"
#include <vector>
class World : GameObject {
private:
int sideSize;
std::vector<MazeGeneratorBase*> generators;
int generatorId = 0;
bool isSimulating = false;
float timeBetweenAITicks = 0.0;
float timeForNextTick = 0;
int64_t moveDuration = 0;
int64_t totalTime = 0;
// .=
// |
// even indexes are top elements;
// odd indexes are left elements;
std::vector<bool> data;
// the boxes colors
std::vector<Color32> colors;
// convert a point into the index of the left vertex of the node
inline int Point2DtoIndex(const Point2D& point) {
// todo: test. unstable interface
auto sizeOver2 = sideSize / 2;
return (point.y + sizeOver2) * (sideSize + 1) * 2 + (point.x + sizeOver2) * 2;
}
public:
~World();
explicit World(Engine* pEngine, int size);
Node GetNode(const Point2D& point);
bool GetNorth(const Point2D& point);
bool GetEast(const Point2D& point);
bool GetSouth(const Point2D& point);
bool GetWest(const Point2D& point);
void SetNode(const Point2D& point, const Node& node);
void SetNorth(const Point2D& point, const bool& state);
void SetEast(const Point2D& point, const bool& state);
void SetSouth(const Point2D& point, const bool& state);
void SetWest(const Point2D& point, const bool& state);
void Start() override;
void OnGui(ImGuiContext* context) override;
void OnDraw(SDL_Renderer* renderer) override;
void Update(float deltaTime) override;
void Clear();
void SetNodeColor(const Point2D& node, const Color32& color);
Color32 GetNodeColor(const Point2D& node);
int GetSize() const;
private:
void step();
};
#endif
| true |
f65eaf5238fe852aa184397b0a95b87866f78fac | C++ | Anubhav12345678/competitive-programming | /eggdropingproblemusingdp.cpp | UTF-8 | 3,004 | 3.53125 | 4 | [] | no_license | // A Dynamic Programming based C++ Program for the Egg Dropping Puzzle
# include <stdio.h>
# include <limits.h>
//Since we need to minimize the number of trials in worst case, we take the maximum of two cases. We consider the max of above two cases for every floor and choose the floor which yields minimum number of trials.
/*
k ==> Number of floors
n ==> Number of Eggs
eggDrop(n, k) ==> Minimum number of trials needed to find the critical
floor in worst case.
eggDrop(n, k) = 1 + min{max(eggDrop(n - 1, x - 1), eggDrop(n, k - x)):
x in {1, 2, ..., k}}
*/
// this gives gauaranteed the highest floor from which the egg wint break on dropping
// A utility function to get maximum of two integers
int max(int a, int b) { return (a > b)? a: b; }
/* Function to get minimum number of trials needed in worst
case with n eggs and k floors */
int eggDrop(int n, int k)
{
/* A 2D table where entery eggFloor[i][j] will represent minimum
number of trials needed for i eggs and j floors. */
int eggFloor[n+1][k+1];
int res;
int i, j, x;
// We need one trial for one floor and0 trials for 0 floors
for (i = 1; i <= n; i++)
{
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
// We always need j trials for one egg and j floors.
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
// Fill rest of the entries in table using optimal substructure
// property
for (i = 2; i <= n; i++)
{
for (j = 2; j <= k; j++)
{
eggFloor[i][j] = INT_MAX;
for (x = 1; x <= j; x++)
{
res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n][k];
}
/* Driver program to test to pront printDups*/
int main()
{
int n = 2, k = 36;
printf ("nMinimum number of trials in worst case with %d eggs and "
"%d floors is %d \n", n, k, eggDrop(n, k));
return 0;
}
//the above is in o(n^2)
//below is in O(nlogk)
// C++ program to find minimum
// number of trials in worst case.
#include <bits/stdc++.h>
using namespace std;
// Find sum of binomial coefficients xCi
// (where i varies from 1 to n). If the sum
// becomes more than K
int binomialCoeff(int x, int n, int k)
{
int sum = 0, term = 1;
for (int i = 1; i <= n && sum < k; ++i) {
term *= x - i + 1;
term /= i;
sum += term;
}
return sum;
}
// Do binary search to find minimum
// number of trials in worst case.
int minTrials(int n, int k)
{
// Initialize low and high as 1st
// and last floors
int low = 1, high = k;
// Do binary search, for every mid,
// find sum of binomial coefficients and
// check if the sum is greater than k or not.
while (low < high) {
int mid = (low + high) / 2;
if (binomialCoeff(mid, n, k) < k)
low = mid + 1;
else
high = mid;
}
return low;
}
/* Drier program to test above function*/
int main()
{
cout << minTrials(2, 10);
return 0;
}
| true |
992f0084e42e0b55166f613209d053ab29557b59 | C++ | Himanshu-Negi8/Data-Structure-and-Algorithms | /Leetcode/group_anagrams_49.cpp | UTF-8 | 348 | 2.703125 | 3 | [] | no_license | class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>>v;
unordered_map<string,vector<string>> mp;
for(string x:strs){
auto word =x;
sort(x.begin(),x.end());
mp[x].push_back(word);
}
for( auto a : mp){
v.push_back(a.second);
}
return v;
}
};
| true |
96717250d63f07761f5378403ae8df8a0a907e9b | C++ | jebasingh/Problem-Solving | /05_05/05_05_string_parenthesis_count.cpp | UTF-8 | 971 | 3.578125 | 4 | [] | no_license | #include<iostream>
#include<stack>
#include<string>
using namespace std;
int getNoOfBalancedParenthesis(string str) {
stack<char> s;
int i = 0;
int counter = 0;
int innerLevelCounterTotal = 0;
while(i < str.length()) {
if( str[i] == '(') {
s.push('(');
i++;
}
else if ( str[i] == ')') {
int innerLevelCounter = -1;
counter++;
while(!s.empty() && i < str.length()) {
if(str[i] == ')') {
s.pop();
innerLevelCounter++;
i++;
}
else {
i++;
break;
}
}
innerLevelCounterTotal += innerLevelCounter;
}
}
int totalCount = (counter * (counter + 1) ) /2;
totalCount += innerLevelCounterTotal;
return totalCount;
}
int main() {
string str;
cout<<"Enter the string : ";
cin>>str;
// str = "(((((((())))))))";
int count = getNoOfBalancedParenthesis(str);
cout<< "\nNo of Count : " << count << "\n";
return 0;
} | true |
579bad345ccdb2fa68bfea1a4744a2b07f0ed885 | C++ | k0adarsh/LeetCode-Solutions | /Medium/Spiral Matrix.cpp | UTF-8 | 1,149 | 2.890625 | 3 | [] | no_license | class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& mat) {
vector<int> ans;
int n = mat.size();
if(n == 0)
return ans;
int m = mat[0].size(),i,j;
int low = 0, high = n - 1, lft = 0, rgt = m-1,dir = 0;
while(low <= high && lft <= rgt)
{
if(dir == 0)
{
for(i=lft;i<=rgt;i++)
ans.push_back(mat[low][i]);
dir = 1;
low += 1;
}
else if(dir == 1)
{
for(i=low;i<=high;i++)
ans.push_back(mat[i][rgt]);
dir = 2;
rgt -= 1;
}
else if(dir == 2)
{
for(i=rgt;i>=lft;i--)
ans.push_back(mat[high][i]);
dir = 3;
high -= 1;
}
else if(dir == 3)
{
for(i=high;i>=low;i--)
ans.push_back(mat[i][lft]);
dir = 0;
lft += 1;
}
}
return ans;
}
};
| true |
e6dd5af169ea7ed8a1dcee35e81a862bafd1756a | C++ | rcirca/irose | /src/client/GameData/Event/CTEventServerList.h | UTF-8 | 878 | 2.546875 | 3 | [] | no_license | #ifndef _CTEventServerList_
#define _CTEventServerList_
#include "ctevent.h"
struct CHANNELSERVER_INFO{
DWORD m_worldserver_id;
BYTE m_channel_id;
std::string m_channel_name;
short m_user_percent;
};
struct WORLDSERVER_INFO{
DWORD m_world_id;
std::string m_world_name;
std::list< CHANNELSERVER_INFO > m_channel_list;
};
class CTEventServerList : public CTEvent
{
public:
CTEventServerList(void);
virtual ~CTEventServerList(void);
enum{
EID_NONE,
EID_CLEAR_WORLDSERVER_LIST,
EID_CLEAR_CHANNELSERVER_LIST,
EID_ADD_WORLDSERVER,
EID_ADD_CHANNELSERVER,
};
void SetWorldServerInfo( WORLDSERVER_INFO& info );
void SetChannelServerInfo( CHANNELSERVER_INFO& info );
WORLDSERVER_INFO& GetWorldServerInfo();
CHANNELSERVER_INFO& GetChannelServerInfo();
private:
WORLDSERVER_INFO m_worldserver;
CHANNELSERVER_INFO m_channelserver;
};
#endif | true |
9dad058d6b7c6e424327da11010e2f5a9df9fcf5 | C++ | dqmcdonald/GardenLabESP8266 | /GardenLabESP8266.ino | UTF-8 | 4,067 | 2.96875 | 3 | [] | no_license | /*GardenLab ESP8266 Wemos D1 Mini
Responsible for receiving data over serial from the Arduino and pass it on to the
Raspberry Pi Server.
The Arduino controls the power for this board so to save battery it's only turned on when
the Arduino is ready to send data
Quentin McDonald
May 2017
*/
//This example will set up a static IP - in this case 192.168.1.99
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <EEPROM.h>
/* Pin definitions: */
#define RX D1
#define TX D2
SoftwareSerial softSerial = SoftwareSerial(RX, TX);
String data_string = "";
String last_data_string="";
String esid;
long rssi;
long wifi_strength;
char buff[128];
WiFiServer server(80);
IPAddress ip(192, 168, 1, 99); // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // set gateway to match your network
int num_bytes = 0; // Number of bytes to read
int bytes_read = 0; // Number currently read
void setup() {
Serial.begin(9600);
delay(10);
softSerial.begin(9600);
softSerial.flush();
// Start the server
server.begin();
Serial.println("Server started");
pinMode(BUILTIN_LED, OUTPUT);
digitalWrite(BUILTIN_LED,LOW);
setupWifi();
digitalWrite(BUILTIN_LED,HIGH);
pinMode(2, OUTPUT);
}
void loop() {
if ( softSerial.available()) {
if ( num_bytes == 0 ) {
num_bytes = (int)softSerial.read();
Serial.print("Num bytes to read from Arduino =");
Serial.println(num_bytes);
digitalWrite(BUILTIN_LED,LOW);
} else {
char c = softSerial.read();
data_string += c;
bytes_read++;
// If we have read the whole string post it to server
if ( num_bytes == bytes_read ) {
digitalWrite(BUILTIN_LED,HIGH);
delay(500);
digitalWrite(BUILTIN_LED,LOW);
post_data(data_string);
last_data_string = data_string;
data_string = "";
num_bytes = 0;
bytes_read = 0;
}
}
}
}
void setupWifi() {
EEPROM.begin(512);
// read eeprom for ssid and pass
Serial.println("Reading EEPROM ssid");
for (int i = 0; i < 32; ++i)
{
esid += char(EEPROM.read(i));
}
Serial.print("SSID: ");
Serial.println(esid);
Serial.println("Reading EEPROM pass");
String epass = "";
for (int i = 32; i < 96; ++i)
{
epass += char(EEPROM.read(i));
}
Serial.print("PASS: ");
Serial.println(epass);
Serial.print(F("Setting static ip to : "));
Serial.println(ip);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(esid);
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network
WiFi.config(ip, gateway, subnet);
WiFi.begin(esid.c_str(), epass.c_str());
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.print("Use this URL : ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void post_data(const String& dstring) {
Serial.println("Posting data string:");
Serial.println(data_string);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const char* host = "192.168.1.13";
const int httpPort = 8080;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// // We now create a URI for the request
String url = "/input/";
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Accept: */*\r\n" +
"Content-Length: " + dstring.length() + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n\r\n");
client.println(dstring);
delay(10);
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
| true |
6a57cd2384974d2f54a72881a238f53f71091d95 | C++ | TrumpZuo/PAT_exam_B | /1045_wrong.cpp | GB18030 | 1,183 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{ int n;cin>>n;int a[n]={0},Fin[10000]={0},ans=0;
for(int i=0;i<n;i++)
{cin>>a[i];}
for(int i=0;i<n;i++)
{ bool MainNum=true;
if(i==0)
{for(int j=1;j<n;j++)
{
if(a[j]<a[i])
{ MainNum=false;break;}
}
}
else if(i==n-1)
{
for(int j=0;j<n-1;j++)
{if(a[j]>a[i])
{ MainNum=false; break;}
}
}
else
{int j=i-1,k=i+1;
while(j>=0)
{ if(a[j]>a[i])
{ MainNum=false;break;}
j--;
}
if(MainNum==true)
{ while(k<n)
{if(a[k]<a[i]){ MainNum=false;break;}k++;
}
}
}
if(MainNum==true)
{ ans++;Fin[ans]=a[i];}
}
cout<<ans<<endl;
for(int i=1;i<=ans;i++)
{if(i!=ans)cout<<Fin[i]<<" ";
else cout<<Fin[i];}
cout<<endl;
// printf("\n"); һԵûͨ
//гʱ
} | true |
c96fcf1e4a3c099980102f9718ad7ced7664e2c4 | C++ | yustikasaridirgahayu/remedialUTS | /nomor8.cpp | UTF-8 | 552 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int angka_yang_dicari = 30;
int array[] = {55,53,52,51,30,24,21,15,10,5};
int min = 0;
int max =(sizeof(array)/sizeof(*array)-1);
int nilai_perkiraan;
while (min<=max)
{
nilai_perkiraan =(int)(((max+min)/2));
if(angka_yang_dicari==array[nilai_perkiraan]);
{
cout << "Angka yang dicari berada pada index "<<nilai_perkiraan<<endl;
break;
} if (array[nilai_perkiraan] < angka_yang_dicari){
min = nilai_perkiraan + 1;
} else {
max = nilai_perkiraan - 1;
}
cout << nilai_perkiraan <<endl;
}
return 0;
}
| true |
da2a624ac07be1b0f566aeb98d127440f6f9c4f6 | C++ | GraemeKnowles/School | /CSC 180/Hiya/Position.cpp | UTF-8 | 715 | 3.34375 | 3 | [] | no_license | #include "Position.h"
#include <algorithm>
#include <string>
#include "GameBoard.h"
std::string Position::intToAlpha[7] = { "A", "B", "C", "D", "E", "F", "G" };
Position::Position(std::string pos)
{
std::transform(pos.begin(), pos.end(), pos.begin(), ::tolower);
x = pos[0] - 'a';
y = pos[1] - '0' - 1;
}
bool Position::isValid(std::string x)
{
if (x.size() < 2) {
return false;
}
int col = tolower(x[0]) - 'a';
int row = x[1] - '0' - 1;
if (col < 0 || row < 0 || col >= GameBoard::BOARD_WIDTH || row >= GameBoard::BOARD_HEIGHT)
{
return false;
}
return true;
}
Position Position::getMirrorPosition() const
{
return Position(GameBoard::BOARD_WIDTH - x - 1, GameBoard::BOARD_HEIGHT - y - 1);
} | true |
ea1f1cace09157e3d93b8c17190ee0dd99cfea95 | C++ | Osprey-DPD/osprey-dpd | /src/StressGridCell.h | UTF-8 | 2,474 | 2.5625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | // StressGridCell.h: interface for the CStressGridCell class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_STRESSGRIDCELL_H__4698109D_4D07_4860_8FED_E6AB37ECC3DF__INCLUDED_)
#define AFX_STRESSGRIDCELL_H__4698109D_4D07_4860_8FED_E6AB37ECC3DF__INCLUDED_
// Forward declarations
// Include file to allow calculation of stress tensor in curvilinear coordinates
#include "SimMiscellaneousFlags.h"
#include "AbstractCell.h"
class CStressGridCell : public CAbstractCell
{
// ****************************************
// Construction/Destruction: base class has protected constructor
public:
CStressGridCell();
CStressGridCell(long index, long coords[3], double dx, double dy, double dz);
// Copy constructor
CStressGridCell(const CStressGridCell& oldCell);
virtual ~CStressGridCell();
// ****************************************
// Global functions, static member functions and variables
public:
// ****************************************
// PVFs that must be overridden by all derived classes
public:
// ****************************************
// Public access functions
public:
// Functions to access the local stress tensor
inline double GetStress11() const {return m_aStressSphere[0];}
inline double GetStress22() const {return m_aStressSphere[4];}
inline double GetStress33() const {return m_aStressSphere[8];}
inline double GetStressComponent(long i) const {return m_aStressSphere[i];}
// Function to write out the components of the stress tensor
void WriteStressTensor() const;
// Function to zero all components of the stress tensor
void Clear();
// Function to add a stress to the local stress tensor
void AddStress(double stress[9]);
// Function to transform the local tensor into spherical polar coordinates
void TransformStressToSphCoords(double origin[3]);
// Function to transform the local tensor into cylindrical polar coordinates
void TransformStressToCylCoords(double origin[3]);
// ****************************************
// Protected local functions
protected:
// ****************************************
// Implementation
// ****************************************
// Private functions
private:
// ****************************************
// Data members
private:
double m_aStressSphere[9]; // Stress tensor within current cell
};
#endif // !defined(AFX_STRESSGRIDCELL_H__4698109D_4D07_4860_8FED_E6AB37ECC3DF__INCLUDED_)
| true |
7e69de160a8b20c22599853fc8d2e008f9ea3a6b | C++ | gomster96/Byungwoong_Algorithm | /lecture/DP_7.cpp | UTF-8 | 1,979 | 2.921875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define instructor
#ifdef mine
struct blo{
int area, height, weight;
blo(int a = 0, int b = 0, int c = 0){
area = a;
height = b;
weight = c;
}
bool myCheck(const blo& bb) const{
if(area < bb.area && weight < bb.weight) return true;
else return false;
}
};
int main(){
ios_base::sync_with_stdio(false);
freopen("input.txt","rt",stdin);
int n ;
cin >> n;
int a, b, c;
vector<blo> arr(n+1);
vector<int> dt(n+1);
for(int i=1; i<=n; i++){
cin >> a >> b >> c;
arr[i] = blo(a,b,c);
}
int res = 0;
for(int i=1; i<=n; i++){
int max = arr[i].height;
for(int j=i-1; j>=1; j--){
if(max < (dt[j] + arr[i].height)&& arr[i].myCheck(arr[j])){
max = dt[j] + arr[i].height;
//cout<<"max: " << max << " i: " << i << " j: " << j << endl;
}
}
dt[i] = max;
if(dt[i] > res) res = dt[i];
}
cout<<res<<endl;
return 0;
}
#endif
#ifdef instructor
struct Brick{
int s, h, w;
Brick(int a, int b, int c){
s = a, h = b, w = c;
}
bool operator<(const Brick &b) const{
return s>b.s;
}
};
int main(){
ios_base::sync_with_stdio(false);
freopen("input.txt","rt",stdin);
int n, a, b, c, max_h = 0, res = 0;
cin >> n;
vector<Brick> Bricks;
vector<int> dy(n, 0);
for(int i=0; i<n; i++){
cin>>a>>b>>c;
Bricks.push_back(Brick(a, b, c));
}
sort(Bricks.begin(), Bricks.end());
dy[0] = Bricks[0].h;
res = dy[0];
for(int i=1; i<n; i++){
max_h = 0;
for(int j=i-1; j>=0; j--){
if(Bricks[j].w > Bricks[i].w && dy[j] > max_h){
max_h = dy[j];
}
}
dy[i] = max_h + Bricks[i].h;
res = max(res, dy[i]);
}
cout << res << endl;
return 0;
}
#endif | true |
7c7a4e826db1b902487951aca2823b4602c00389 | C++ | OhmR/C0_Compile | /compile_1/Parser.h | GB18030 | 2,461 | 2.640625 | 3 | [] | no_license | #ifndef _PARSER_H_
#define _PARSER_H_
#include "Error.h"
#include "lexical.h"
#include "SymbolSet.h"
#include "MiddleCode.h"
using namespace std;
class Parser
{
public:
Parser(string name);
~Parser();
void program(); //
SymbolSet return_symbolset() { return set; }
vector<Quaternary> return_middleCode(){ return Code.getcode(); }
int err_flag;
private:
string operande; //ʽĴ纯洢
int flag_AddSub; //洢ڼ12
int flag_MultDiv; //洢ڳ12
int temp_count = 0;
int label = 0; //ѭתʹãʹǣ
string op1, op2;
int relatesign;
MiddleCode Code;
info ifo;
SymbolSet set;
string name; //¼
string filename;
lexical *lex;
Error err;
string WriteConst;
int sign;
int num; //洢ֵ
char charvalue; //洢charֵ
void reset_temp() { temp_count = 0; }
void JumpToChar(char ch);
int addOperator(); //ӷ
int multOperator(); //˷
int relateOperator(); //ϵ
// void isNum(); //
void isChar(); //ַ
void constDec(); //˵
void constDef(); //
int unsignInt(); //
void Int(); //
int identity(); //ʶ
void statementHead(); //ͷ
void varDec(); //˵
void varDef(); //
int Type(); //ͱʶ
void reFuncDef(); //зغ
void noFuncDef(); //غ
void compoundStatement(); //
void parametersTable(); //
void mainFunc(); //
void expr(); //ʽ
void term(); //
void factor(); //
void statement(); //
void assignStatement(); //ֵ
void ifStatement(); //
string condition(); //
void cycleStatement(); //ѭ
void stepSize(); //
void reFuncCall(); //зֵ
void noFuncCall(); //ֵ
void valueParTable(string funcname); //ֵ
void statementColumn(); //
void write(); //д
void read(); //
void Return(); //
int isNum(string name); //жnameǷΪ
int transNum(string name); //stringתΪint
void comparePara(string funcname, int num, string oper);
};
#endif | true |
a273b3501f389915112946bcd18c09a06cdac180 | C++ | joelpinheiro/audio-video-codification | /Trabalho_1/BitStream/BitStream.h | UTF-8 | 945 | 2.765625 | 3 | [] | no_license | #ifndef BITSTREAM_H
#define BITSTREAM_H
#include <iostream>
#include <fstream>
class BitStream
{
public:
BitStream(std::string, unsigned int);
void openFileToWrite(int);
void openFileToRead();
void closeFileRead();
void closeFileWrite();
unsigned int getSize();
std::string getFileName();
void readBit(int);
void writeBit(int, int);
int getBitToText(unsigned int, unsigned int);
char getBitToBin(unsigned int);
char* getBufferContents();
void setBufferContents(char*);
void setBufferSize(unsigned int);
unsigned int getBufferSize();
unsigned int getOptimalBufferSize();
#define CREATE_AND_REPLACE 0
#define REPLACE_ONLY 1
protected:
private:
void allocBuffer();
std::streampos beginStream, endStream;
std::ifstream fileHandleRead;
std::ofstream fileHandleWrite;
std::string fileName;
char* memBlock;
unsigned int bufferSize;
};
#endif // BITSTREAM_H
| true |
f96e36feb2b79dd7904e4c451e228a469c1e9208 | C++ | tips367/Algorithms | /SearchingAndSorting/FindMinimumLengthUnsortedSubarraySortingWhichMakesCompleteArraySorted/FindMinimumLengthUnsortedSubarraySortingWhichMakesCompleteArraySorted.cpp | UTF-8 | 2,876 | 4.25 | 4 | [] | no_license | /* Given an unsorted array arr[0..n - 1] of size n, find the minimum length subarray arr[start..end],
such that sorting this subarray makes the whole array sorted.
Examples:
1) If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], program should be able to find
that the subarray lies between the indexes 3 and 8.
2) If the input array is[0, 1, 15, 25, 6, 7, 30, 40, 50], program should be able to find that the
subarray lies between the indexes 2 and 5.
*/
#include <iostream>
void printUnsortedSubarrayIndexes(int arr[], int n)
{
int start = 0, end = n - 1, max, min;
// 1) Find the candidate unsorted subarray
// 1(a) Scan from left to right and find the first element which is greater than the next element.
// Let start be the index of such an element. In the above example 1, start is 3 (index of 30).
for (start = 0; start < n - 1; start++)
{
if (arr[start] > arr[start + 1])
break;
}
if (start == (n - 1))
{
std::cout << "The complete array is sorted." << std::endl;
return;
}
// 1(b) Scan from right to left and find the first element(first in right to left order) which is smaller
// than the next element(next in right to left order).Let end be the index of such an element.
// In the above example 1, end is 7 (index of 31).
for (end = n - 1; end > 0; end--)
{
if (arr[end] < arr[end - 1])
break;
}
// 2) Check whether sorting the candidate unsorted subarray makes the complete array sorted or not.
// If not, then include more elements in the subarray.
// 2(a) Find the minimum and maximum values in arr[start..end]. Let minimum and maximum values be min and max.
// min and max for [30, 25, 40, 32, 31] are 25 and 40 respectively.
max = arr[start];
min = arr[start];
for (int i = start + 1; i <= end; i++)
{
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
// 2(b) Find the first element (if there is any) in arr[0..start-1] which is greater than min,
// change start to index of this element. There is no such element in above example 1.
for (int i = 0; i < start; i++)
{
if (arr[i] > min)
{
start = i;
break;
}
}
// 2(c) Find the last element (if there is any) in arr[end+1..n-1] which is smaller than max,
// change end to index of this element. In the above example 1, end is changed to 8 (index of 35)
for (int i = n - 1; i >= end + 1; i--)
{
if (arr[i] < max)
{
end = i;
break;
}
}
// 3) Print start and end
std::cout << "The minimum length unsorted subarray sorting " <<
"which makes complete array sorted lies between indexes " << start << " and " << end;
return;
}
// Driver code
int main()
{
//int arr[] = { 10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60 };
int arr[] = { 0, 1, 15, 25, 6, 7, 30, 40, 50 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
printUnsortedSubarrayIndexes(arr, arr_size);
return 0;
} | true |
be3341028809f91b1184ac6117c70b1a994996da | C++ | Dhruvik-Chevli/Code | /CodingNinjas/Graphs/sparsh.cpp | UTF-8 | 3,393 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<string>
#include<unordered_set>
#include<stack>
#include<queue>
#include<unordered_map>
using namespace std;
typedef long long int ll;
#define EPS 1e-9
// #define pb push_back
#define FOR(i, a, b) for(ll i = a; i < b; i++)
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
void DSUinit(vector<ll>&a,vector<ll>&size,ll n)
{
FOR(i,0,n)
{
a[i]=i;
size[i]=1;
}
return;
}
ll root(vector<ll>&a,ll i)
{
return (i==a[i])?i:a[i]=root(a,a[i]);
}
bool DSUfind(vector<ll>a,ll x,ll y)
{
if(root(a,x)==root(a,y))
{
return true;
}
return false;
}
void DSUunion(vector<ll>&a,vector<ll>&size, ll x,ll y)
{
x=root(a,x);
y=root(a,y);
if(x==y)
{
return;
}
if(size[x]<size[y]) swap(x,y);
a[y]=x;
size[x]+=size[y];
}
void dfs(vector<vector<ll> >&graph,vector<bool>&visited,ll start)
{
visited[start]=true;
FOR(i,0,graph[start].size())
{
if(!(visited[graph[start][i]]))
{
dfs(graph,visited,graph[start][i]);
}
}
return;
}
bool isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0) return false;
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
ll power(ll x,ll y,ll p)
{
ll ans=1;
x = x%p;
if(x==0) return 0;
while(y)
{
if(y&1) ans=(ans*x)%p;
y>>=1;
x=(x*x)%p;
}
return ans;
}
void getAllPaths(int curh, int cury,int h, int y,vector<string>&ans,string s)
{
if(curh==h and cury==y)
{
ans.push_back(s);
return;
}
if(curh>h or cury>y)
{
return;
}
if(curh<h)
{
string s1=s+'H';
getAllPaths(curh+1,cury,h,y,ans,s1);
}
if(cury<y)
{
string s1=s+'V';
getAllPaths(curh,cury+1,h,y,ans,s1);
}
}
vector<string> getPaths(int x,int y)
{
vector<string>ans;
string cur="";
getAllPaths(0,0,x,y,ans,cur);
sort(ans.begin(),ans.end());
return ans;
}
vector<string>getSafePaths(vector<string> journeys)
{
vector<string>ans;
vector<vector<vector<string> > >poss(10,vector<vector<string> >(10,vector<string>()));
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
vector<string> ans1=getPaths(i+1,j+1);
poss[i][j].push_back(ans1);
}
}
for(int i=0;i<journeys.size();i++)
{
int j=0;
int k=0;
while(journeys[i][j]!=' ')
{
j++;
}
k=j+1;
while(journeys[i][k]!=' ')
{
k++;
}
int x=stoi(journeys[i].substr(0,j));
int y=stoi(journeys[i].substr(j+1,k-j));
int z=stoi(journeys[i].substr(k+1));
ans.push_back(poss[i-1][j-1][k]);
}
return ans;
}
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
vector<string>journeys;
cin.ignore();
FOR(i,0,n)
{
string s;
getline(cin,s);
journeys.push_back(s);
}
FOR(i,0,n)
{
cout<<journeys[i]<<"\n";
}
vector<string>ans=getSafePaths(journeys);
FOR(i,0,ans.size())
{
cout<<ans[i]<<"\n";
}
return 0;
} | true |
8329f62b2e204e967aa1de80aa0d767e1ca8252d | C++ | bonnie519/SUDA | /closure-property_set-function_dependence/Depen.h | UTF-8 | 496 | 3.546875 | 4 | [] | no_license | #include<string>
using namespace std;
class Depen
{
private:
string left;
string right;
public:
Depen();
Depen(string& a,string& b);
//Depen operator=(Depen&);
void Display();
string DisL();
string DisR();
};
Depen::Depen()
{
left="";
right="";
}
Depen::Depen(string& a,string& b)
{
left=a;
right=b;
}
void Depen::Display()
{
cout<<left<<"->"<<right<<endl;
}
string Depen::DisL()
{
return left;
}
string Depen::DisR()
{
return right;
} | true |
76dc3dc6449ad298d5f5414c2c23c42133a9f47d | C++ | krittindev/OCOM64 | /CAMP1/4-14-WED_algorithm/SubArray/SubArray.cpp | UTF-8 | 458 | 2.59375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
float num[n], sum = 0, focusSum;
for(int i = 0; i < n; i++){
cin >> num[i];
sum += num[i];
}
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
focusSum = 0;
for(int k = i; k <= j; k++)
focusSum += num[k];
if(focusSum/(1-i+j) > ( (n-1+i-j)? (sum - focusSum)/(n-1+i-j): 0))
cout << i+1 << ' ' << j+1 << '\n';
}
}
return 0;
}
| true |
64bb996f43ba8836c5c3d02d48014582bcd9ce0d | C++ | midaslmg94/CodingTest | /Simulation/17779_게리맨더링 2.cpp | UHC | 3,990 | 3.125 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<algorithm>
#include<vector>
#define MAX 21
using namespace std;
struct INFO {
int sector;
int people;
};
INFO map[MAX][MAX];
int n;
int cnt[5]; // ű α
int calculate() { // ű α ̸
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
int idx = map[i][j].sector;
cnt[idx - 1] += map[i][j].people; // ̷ ִϱ ¾
}
}
sort(cnt, cnt + 5);
return cnt[4] - cnt[0];
}
void bfs(int x, int y, int d1, int d2) {
//ʱȭ
memset(cnt, 0, sizeof(cnt));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
map[i][j].sector = 0;
}
}
// 5 ű 輱 ä
int up_x = x; int up_y = y; // 5 ű : 1
if (up_x - 1 >= 1) {
map[up_x - 1][up_y].sector = 1;
}
while (up_x <= x + d1 && up_y >= y - d1) {
map[up_x][up_y].sector = 5;
up_x++; up_y--;
}
int left_x = x + d1; int left_y = y - d1; // 5 ű : 3
if (left_y - 1 >= 1) {
map[left_x][left_y].sector = 3;
}
while (left_x <= x + d1 + d2 && left_y <= y - d1 + d2) {
map[left_x][left_y].sector = 5;
left_x++; left_y++;
}
int down_x = x + d1 + d2; int down_y = y - d1 + d2; // Ʒ 5 ű : 4
if (down_x + 1 <= n) {
map[down_x][down_y].sector = 4;
}
while (down_x >= x + d2 && down_y <= y + d2) {
map[down_x][down_y].sector = 5;
down_x--; down_y++;
}
int right_x = x + d2; int right_y = y + d2; // 5 ű : 2
if (right_y + 1 <= n) {
map[right_x][right_y].sector = 2;
}
while (right_x >= x && right_y >= y) {
map[right_x][right_y].sector = 5;
right_x--; right_y--;
}
int x1 = x;
int x2 = x;
int x3 = x;
int x4 = x;
int y1 = y;
int y2 = y;
int y3 = y;
int y4 = y;
// 1 ű ä
for (int i = 1; i < x1 + d1; i++) {
for (int j = 1; j <= y1; j++) {
if (map[i][j].sector != 0) {
y1--;
continue;
}
map[i][j].sector = 1;
//cnt[0] += map[i][j].people; // ̷ ߴ Ʋ
}
}
// 2 ű ä
for (int i = 1; i <= x2 + d2; i++) {
for (int j = y2 + 1; j <= n; j++) {
if (map[i][j].sector != 0) {
y2++;
continue;
}
map[i][j].sector = 2;
//cnt[1] += map[i][j].people;
}
}
// 3 ű ä
for (int i = n; i >= x3 + d1; i--) {
for (int j = 1; j < y3 - d1 + d2; j++) {
if (map[i][j].sector != 0) {
y3--;
continue;
}
map[i][j].sector = 3;
//cnt[2] += map[i][j].people;
}
}
// 4 ű ä
for (int i = n; i > x4 + d2; i--) {
for (int j = y4 - d1 + d2; j <= n; j++) {
if (map[i][j].sector != 0) {
y4++;
continue;
}
map[i][j].sector = 4;
//cnt[3] += map[i][j].people;
}
}
// 5 ű ä
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (map[i][j].sector == 0 || map[i][j].sector == 5) {
map[i][j].sector = 5;
//cnt[4] += map[i][j].people;
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
freopen("input.txt", "r", stdin);
cin >> n;
int tmp;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> map[i][j].people;
map[i][j].sector = 0;
}
}
/*bfs(3, 5, 2, 1);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << map[i][j].sector << ' ';
}
cout << endl;
}
cout << endl << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << map[i][j].people << ' ';
}
cout << endl;
}*/
int res = 0;
int ans = 987654321;
res = calculate();
for (int x = 1; x <= n; x++) {
for (int y = 1; y <= n; y++) {
for (int d1 = 1; d1 <= n; d1++) {
for (int d2 = 1; d2 <= n; d2++) {
if (1 <= y - d1 && y + d2 <= n && x + d1 + d2 <= n) {
bfs(x, y, d1, d2);
res = calculate();
ans = min(ans, res);
}
}
}
}
}
cout << ans;
} | true |
511b0587398dba0d8f024392bfe1be70a4675de7 | C++ | ash20012003/DynamicProgrammingPractice | /Fibonacci.cpp | UTF-8 | 297 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int term[1000];
int fib(int n)
{
if (n <= 1)
return n;
if (term[n] != 0)
return term[n];
else {
term[n] = fib(n - 1) + fib(n - 2);
return term[n];
}
}
int main(){
cout << fib(5);
} | true |
f5b047993885e11e5404ba61d9f3ad9e34601801 | C++ | m80126colin/Judge | /before2020/TIOJ/TIOJ 1667(Easy, Inversion-pair, Straight-forward).cpp | UTF-8 | 394 | 2.609375 | 3 | [] | no_license | /**
* @judge TIOJ
* @id 1667
* @tag Easy, Inversion pair, Straight forward
*/
#include <stdio.h>
#include <iostream>
using namespace std;
int n, t, a[101];
int main()
{
int i, j;
while (scanf("%d", &n) != EOF)
{
for (i = t = 0; i < n; i++)
{
scanf("%d", &a[i]);
for (j = 0; j < i; j++)
{
if (a[j] > a[i]) t++;
}
}
printf("%d\n", t);
}
} | true |
b1d152dff23dc9c1c30eb24b03921598e7761d50 | C++ | WhiZTiM/coliru | /Archive2/14/19cf014e7bcb76/main.cpp | UTF-8 | 631 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <typeinfo>
#include <cxxabi.h>
template<std::size_t n> struct exact_width
{ using uint_type = void; };
template<> struct exact_width<8>
{ using uint_type = unsigned long long; };
template<> struct exact_width<4>
{ using uint_type = unsigned int; };
template<> struct exact_width<2>
{ using uint_type = unsigned short; };
template<> struct exact_width<1>
{ using uint_type = unsigned char; };
template<std::size_t n>
using fw_uint = typename exact_width<n>::uint_type;
int main()
{
int s = 0;
fw_uint<2> x;
std::cout << abi::__cxa_demangle(typeid(x).name(), nullptr, nullptr, &s);
}
| true |
79639c7e6255d9e5baeda19e39a03a3b5a9786f7 | C++ | magahet/arduino-projects | /led_sign/led_sign.ino | UTF-8 | 787 | 2.90625 | 3 | [] | no_license | #include <FastLED.h>
#define LED_PIN 2
#define NUM_LEDS 150
CRGB leds[NUM_LEDS];
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
}
void loop() {
//digitalWrite(LED_BUILTIN, LOW); // Turn the LED on by making the voltage LOW
//delay(1000); // Wait for a second
//digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
//delay(2000); // Wait for two seconds
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] = CRGB ( 0, 0, 255);
FastLED.show();
delay(20);
}
for (int i = NUM_LEDS - 1; i >= 0; i--) {
leds[i] = CRGB ( 255, 0, 0);
FastLED.show();
delay(20);
}
}
| true |
0620ed005694c981dd5956c3eba562aeb8e2c5eb | C++ | ceefour/glut101 | /glut113/glut113.cpp | UTF-8 | 8,552 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | #include "stdafx.h"
#include <windows.h>
#include <math.h> // Math Library Header File
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "../glut/glut.h"
#include "../glut/glaux.h"
const float piover180 = 0.0174532925f;
float heading;
float xpos;
float zpos;
GLfloat yrot; // Y Rotation
GLfloat walkbias = 0;
GLfloat walkbiasangle = 0;
GLfloat lookupdown = 0.0f;
GLfloat z = 0.0f; // Depth Into The Screen
GLuint filter; // Which Filter To Use
GLuint texture[3]; // Storage For 3 Textures
typedef struct tagVERTEX
{
float x, y, z;
float u, v;
} VERTEX;
typedef struct tagTRIANGLE
{
VERTEX vertex[3];
} TRIANGLE;
typedef struct tagSECTOR
{
int numtriangles;
TRIANGLE* triangle;
} SECTOR;
SECTOR sector1; // Our Model Goes Here:
void readstr(FILE *f, char *string)
{
do
{
fgets(string, 255, f);
} while ((string[0] == '/') || (string[0] == '\n'));
return;
}
void SetupWorld()
{
float x, y, z, u, v;
int numtriangles;
FILE *filein;
char oneline[255];
filein = fopen("world.txt", "rt"); // File To Load World Data From
readstr(filein, oneline);
sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles);
sector1.triangle = new TRIANGLE[numtriangles];
sector1.numtriangles = numtriangles;
for (int loop = 0; loop < numtriangles; loop++)
{
for (int vert = 0; vert < 3; vert++)
{
readstr(filein, oneline);
sscanf(oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v);
sector1.triangle[loop].vertex[vert].x = x;
sector1.triangle[loop].vertex[vert].y = y;
sector1.triangle[loop].vertex[vert].z = z;
sector1.triangle[loop].vertex[vert].u = u;
sector1.triangle[loop].vertex[vert].v = v;
}
}
fclose(filein);
return;
}
AUX_RGBImageRec *LoadBMP(char *Filename) // Loads A Bitmap Image
{
FILE *File = NULL; // File Handle
if (!Filename) // Make Sure A Filename Was Given
{
return NULL; // If Not Return NULL
}
File = fopen(Filename, "r"); // Check To See If The File Exists
if (File) // Does The File Exist ?
{
fclose(File); // Close The Handle
return auxDIBImageLoadA(Filename); // Load The Bitmap And Return A Pointer
}
return NULL; // If Load Failed Return NULL
}
int LoadGLTextures() // Load Bitmaps And Convert To Textures
{
int Status = FALSE; // Status Indicator
AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture
memset(TextureImage, 0, sizeof(void *) * 1); // Set The Pointer To NULL
// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
if (TextureImage[0] = LoadBMP("crate.bmp"))
{
Status = TRUE; // Set The Status To TRUE
glGenTextures(3, &texture[0]); // Create Three Textures
// Create Nearest Filtered Texture
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX,
TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
// Create Linear Filtered Texture
glBindTexture(GL_TEXTURE_2D, texture[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX,
TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
// Create MipMapped Texture
glBindTexture(GL_TEXTURE_2D, texture[2]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[0]->sizeX,
TextureImage[0]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
}
if (TextureImage[0]) // If Texture Exists
{
if (TextureImage[0]->data) // If Texture Image Exists
{
free(TextureImage[0]->data); // Free The Texture Image Memory
}
free(TextureImage[0]); // Free The Image Structure
}
return Status; // Return The Status
}
void resize(int width, int height) // Resize And Initialize The GL Window
{
if (height == 0)
// Prevent A Divide By Zero By
{
height = 1;
// Making Height Equal One
}
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}
void init() // All Setup For OpenGL Goes Here
{
if (!LoadGLTextures()) // Jump To Texture Loading Routine
{
return; // If Texture Didn't Load Return FALSE
}
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Set The Blending Function For Translucency
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This Will Clear The Background Color To Black
glClearDepth(1.0);
// Enables Clearing Of The Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
SetupWorld();
return; // Initialization Went OK
}
void myTimeOut(int id)
{
// called if timer event
// ...advance the state of animation incrementally...
//rot+=1;
glutPostRedisplay(); // request redisplay
glutTimerFunc(100, myTimeOut, 0); // request next timer event
}
void myKeyboard(unsigned char key, int x, int y)
{
}
void mySpecialKeyboard(int key, int x, int y)
{
if (key == GLUT_KEY_UP)
{
xpos -= (float)sin(heading*piover180) * 0.05f;
zpos -= (float)cos(heading*piover180) * 0.05f;
if (walkbiasangle >= 359.0f)
{
walkbiasangle = 0.0f;
}
else
{
walkbiasangle += 10;
}
walkbias = (float)sin(walkbiasangle * piover180) / 20.0f;
}
else if (key == GLUT_KEY_DOWN)
{
xpos += (float)sin(heading*piover180) * 0.05f;
zpos += (float)cos(heading*piover180) * 0.05f;
if (walkbiasangle <= 1.0f)
{
walkbiasangle = 359.0f;
}
else
{
walkbiasangle -= 10;
}
walkbias = (float)sin(walkbiasangle * piover180) / 20.0f;
}
else if (key == GLUT_KEY_RIGHT)
{
heading -= 1.0f;
yrot = heading;
}
else if (key == GLUT_KEY_LEFT)
{
heading += 1.0f;
yrot = heading;
}
else if (key == GLUT_KEY_PAGE_UP)
{
z -= 0.02f;
lookupdown -= 1.0f;
}
else if (key == GLUT_KEY_PAGE_DOWN)
{
z += 0.02f;
lookupdown += 1.0f;
}
}
void mydisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The View
GLfloat x_m, y_m, z_m, u_m, v_m;
GLfloat xtrans = -xpos;
GLfloat ztrans = -zpos;
GLfloat ytrans = -walkbias - 0.25f;
GLfloat sceneroty = 360.0f - yrot;
int numtriangles;
glRotatef(lookupdown, 1.0f, 0, 0);
glRotatef(sceneroty, 0, 1.0f, 0);
glTranslatef(xtrans, ytrans, ztrans);
glBindTexture(GL_TEXTURE_2D, texture[filter]);
numtriangles = sector1.numtriangles;
// Process Each Triangle
for (int loop_m = 0; loop_m < numtriangles; loop_m++)
{
glBegin(GL_TRIANGLES);
glNormal3f(0.0f, 0.0f, 1.0f);
x_m = sector1.triangle[loop_m].vertex[0].x;
y_m = sector1.triangle[loop_m].vertex[0].y;
z_m = sector1.triangle[loop_m].vertex[0].z;
u_m = sector1.triangle[loop_m].vertex[0].u;
v_m = sector1.triangle[loop_m].vertex[0].v;
glTexCoord2f(u_m, v_m); glVertex3f(x_m, y_m, z_m);
x_m = sector1.triangle[loop_m].vertex[1].x;
y_m = sector1.triangle[loop_m].vertex[1].y;
z_m = sector1.triangle[loop_m].vertex[1].z;
u_m = sector1.triangle[loop_m].vertex[1].u;
v_m = sector1.triangle[loop_m].vertex[1].v;
glTexCoord2f(u_m, v_m); glVertex3f(x_m, y_m, z_m);
x_m = sector1.triangle[loop_m].vertex[2].x;
y_m = sector1.triangle[loop_m].vertex[2].y;
z_m = sector1.triangle[loop_m].vertex[2].z;
u_m = sector1.triangle[loop_m].vertex[2].u;
v_m = sector1.triangle[loop_m].vertex[2].v;
glTexCoord2f(u_m, v_m); glVertex3f(x_m, y_m, z_m);
glEnd();
}
glFlush();
glutSwapBuffers();
}
int _tmain(int argc, _TCHAR* argv[])
{
glutInit(&argc, (char**)argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("simple");
// callbacks
glutDisplayFunc(mydisplay);
glutKeyboardFunc(myKeyboard);
glutSpecialFunc(mySpecialKeyboard);
glutTimerFunc(100, myTimeOut, 0);
glutReshapeFunc(resize);
init();
glutMainLoop();
return 0;
}
| true |
790ad9c9ff8b0fb90b5f456b90d6cce54a7317ab | C++ | hooddanielc/cgalexp | /examples/triangulation_color.cc | UTF-8 | 950 | 2.765625 | 3 | [] | no_license | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_3.h>
#include <CGAL/Triangulation_vertex_base_with_info_3.h>
#include <CGAL/IO/Color.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Triangulation_vertex_base_with_info_3<CGAL::Color, K> Vb;
typedef CGAL::Triangulation_data_structure_3<Vb> Tds;
typedef CGAL::Delaunay_triangulation_3<K, Tds> Delaunay;
typedef Delaunay::Point Point;
int main()
{
Delaunay T;
T.insert(Point(0,0,0));
T.insert(Point(1,0,0));
T.insert(Point(0,1,0));
T.insert(Point(0,0,1));
T.insert(Point(2,2,2));
T.insert(Point(-1,0,1));
// Set the color of finite vertices of degree 6 to red.
Delaunay::Finite_vertices_iterator vit;
for (vit = T.finite_vertices_begin(); vit != T.finite_vertices_end(); ++vit)
if (T.degree(vit) == 6)
vit->info() = CGAL::RED;
return 0;
} | true |
08498e1fb110f01c9be88239e5689add666a476a | C++ | zackgomez/geosmash | /src/FrameManager.h | UTF-8 | 1,408 | 2.703125 | 3 | [] | no_license | #pragma once
#include <map>
#include "Engine.h"
#include "Logger.h"
#include "kiss-skeleton.h"
struct anim_frame
{
std::string id;
GLuint mask_tex;
float w, h; // game units
float x, y; // Center inside texture, [-0.5, 0.5]
};
class FrameManager
{
public:
static FrameManager* get();
void renderFrame(const glm::mat4 &transform, const glm::vec4 &color,
const std::string &name) const;
// Renders a default pose of the passed in fighter
void renderFighter(const glm::mat4 &transform, const glm::vec4 &color,
const std::string &fighterName) const;
void loadFrameFile(const std::string &filename);
void loadPoseFile(const std::string &filename);
// Returns a keyframe ready for passing to a skeleton for the given pose
Keyframe getPose(const std::string &poseName) const;
// Removes all currently loaded frames
void clear();
private:
FrameManager();
FrameManager(const FrameManager &);
~FrameManager();
LoggerPtr logger_;
std::map<std::string, const anim_frame*> frames_;
std::map<std::string, Keyframe> poses_;
void addFrame(const anim_frame *frame);
GLuint createMaskTexture(GLubyte *data, int w, int h);
anim_frame *loadAnimFrame(std::istream &stream);
static Keyframe loadPose(std::istream &is, std::string &posename);
static BoneFrame readBoneFrame(std::istream &is);
};
| true |
36891856f0419e4a2133314440e7618180d675f5 | C++ | moyprg/moyprg_cmasmas | /busqsecuencial.cpp | WINDOWS-1250 | 509 | 3.0625 | 3 | [] | no_license | //Udemy Progamacin ATS
//Ejemplo Busqueda secuencial
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
char a[]={'a','e','i','o','u'}, dato;
int i;
char band='F';
dato='e';
//busqueda secuencial
i=0;
while((band=='F')&&(i<5)){
if(a[i]==dato){
band='V';
}
i++;
}
if(band=='F'){
cout<<"El numero a buscar no se encuentra en el arreglo"<<endl;
}else if(band=='V'){
cout<<"EL numero fue encintrado en la posicion: "<<i-1<<"."<<endl;
}
getch();
return 0;
}
| true |
f65fbc049462d71829ab291c93661d83e66b2b3c | C++ | xex238/Programming_2018 | /4 semester/Discrete_math/course_work/class_1.h | UTF-8 | 1,233 | 3.0625 | 3 | [] | no_license | #ifndef CLASS_1_H
#define CLASS_1_H
#include <iostream>
#include <QMainWindow>
class class_1
{
public:
class_1() = default;
~class_1() = default;
int* a; // Здесь лежит загаданное компьютером число
int* b; // Число, которое ввёл пользователь
int size{ 0 }; // Длина числа
int metadata_a[10]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Сведения о загаданном числе (количество цифр в числе)
int metadata_b[10]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Сведения о числе, который ввёл пользователь
int bulls{ 0 }; // Количество быков
int cows{ 0 }; // Количество коров
void Do_size_a_and_b(int x);
void Filling_with_reiteration(); // Создаём случайное число с повторяющимимся цифрами
void Filling_metadata(); // Заполняем массив о количестве повторяющихся цифр в числе
QString Result(int x); // Проверяем поступающее число на количество быков и коров
};
#endif // CLASS_1_H
| true |
579a9b958c4acced261f01dc650a9efb44ae8f04 | C++ | Dipankar2020-ai/Coding-ninjas-Ds-with-c- | /Linkedlist2 assignment/reverse k nodes.cpp | UTF-8 | 3,317 | 3.265625 | 3 | [] | no_license |
#include <iostream>
using namespace std;
class node
{
public:
int data;
node* next;
node(int data)
{
this->data=data;
next=NULL;
}
};
node* create(node* head)
{
int data;
cin>>data;
while(data!=-1)
{
node* newnode=new node(data);
if(head==NULL)
{
head=newnode;
}
else
{
node* temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
}
cin>>data;
}
return head;
}
void print(node* head)
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
}
int length(node* head)
{
int count=0;
while(head!=NULL)
{
head=head->next;
count++;
}
return count;
}
int findnoderecursive(node* head,int ele,int len)
{
if(len==0)
{
return -1;
}
if(head->data==ele)
{
return 1;
}
findnoderecursive(head->next,ele,len-1);
}
node* oddaftereven(node* head)
{
node* oddH=NULL;
node* oddT=NULL;
node* evenH=NULL;
node*evenT=NULL;
while(head!=NULL)
{
if(head->data%2!=0)
{
if(oddH==NULL)
{
oddH=head;
oddT=head;
}
else
{
oddT->next=head;
oddT=oddT->next;
}
}
else
{
if(evenH==NULL)
{
evenH=head;
evenT=head;
}
else
{
evenT->next=head;
evenT=evenT->next;
}
}
head=head->next;
}
if(oddT==NULL)
{
return evenH;
}
if(evenH==NULL)
{
return oddH;
}
oddT->next=evenH;
return oddH;
}
node* skipMdeleteN(node *head, int M, int N) {
node* temp=head;
while(temp!=NULL)
{
for(int i=0;i<M-1;i++)
{
if(temp!=NULL)
{
temp=temp->next;
}
else
{
break;
}
}
node* p=temp;
if(temp==NULL)
{
return head;
}
for(int j=0;j<N;j++)
{
if(temp!=NULL && temp->next!=NULL && p->next!=NULL)
{
p=temp->next;
temp->next=p->next;
delete(p);
}
}
temp=temp->next;
}
return head;
}
node* reversek(node* &head,int k)
{
node* prev=NULL;
node* curr=head;
node* nextptr;
int count=0;
while(nextptr!=NULL && count<k)
{
nextptr=curr->next;
curr->next=prev;
prev=curr;
curr=nextptr;
count++;
}
if(nextptr!=NULL)
{
head->next=reversek(nextptr,k);
}
return prev;
}
int main()
{
node* head=create(head);
print(head);
cout<<endl;
//int M,N;
//cin>>M>>N;
//head=skipMdeleteN(head,M,N);
int k;
cin>>k;
head=reversek(head,k);
print(head);
return 0;
} | true |
65e5bf9a606f9aebd0a323be08e31af9ac4a0513 | C++ | se1603/Moon | /MoonServer/managerbroker.cpp | UTF-8 | 2,699 | 2.8125 | 3 | [] | no_license | #include "managerbroker.h"
ManagerBroker* ManagerBroker::m_instance = new ManagerBroker();
ManagerBroker::ManagerBroker()
{
}
ManagerBroker::~ManagerBroker()
{
delete m_instance;
}
void ManagerBroker::initManagers()
{
MYSQL *mysql;
mysql = new MYSQL;
MYSQL_RES *result;
MYSQL_ROW row;
mysql_init(mysql);
if(!mysql_real_connect(mysql,"localhost","root","root","Moon",0,NULL,0)){
std::cout << "Manager:Connect MYSQL failed." << std::endl;
}else{
std::cout << "Manager:Connect MYSQL succeed." << std::endl;
}
std::string sql = "select * from Manager;";
if(mysql_query(mysql,sql.data())){
std::cout << "查询失败(Manager)" << std::endl;
}
else
{
result = mysql_use_result(mysql);
while(1)
{
row = mysql_fetch_row(result);
if(row == nullptr){
break;
}else{
std::string name;
for(unsigned int i=0;i<mysql_num_fields(result);++i){
Manager *m = new Manager(std::string(row[0]),atoi(row[1]));
m_managers[row[0]] = m;
}
}
}
}
}
bool ManagerBroker::login(std::string number, std::string password)
{
if(m_managers.find(number) != m_managers.end())
{
MYSQL *mysql;
mysql = new MYSQL;
MYSQL_RES *result;
MYSQL_ROW row;
mysql_init(mysql);
if(!mysql_real_connect(mysql,"localhost","root","root","Moon",0,NULL,0)){
std::cout << "Manager Connect MYSQL failed." << std::endl;
}else{
std::cout << "Manager Connect MYSQL succeed." << std::endl;
}
std::string sql = "select * from Manager where number = '"+ number
+ "' and password = '"+ password +"';";
std::cout << sql << std::endl;
if(mysql_query(mysql,sql.data())){
std::cout << "查询失败(Manager login)" << std::endl;
return false;
}
else
{
result = mysql_use_result(mysql);
while(1)
{
row = mysql_fetch_row(result);
if(row == nullptr){
return false;
}else{
for(unsigned int i=0;i<mysql_num_fields(result);++i){
m_logined.push_back(m_managers[number]);
}
return true;
}
}
}
if(mysql != nullptr)
mysql_close(mysql);
}
return false;
}
int ManagerBroker::managerIdentity(std::string number)
{
return m_managers[number]->identity();
}
| true |
6b2f4e339e7338a27f0f37ce8a7e0c07024227b1 | C++ | Jekmant/sampvoice | /server/Stream.h | UTF-8 | 1,402 | 2.515625 | 3 | [
"MIT"
] | permissive | /*
This is a SampVoice project file
Developer: CyberMor <cyber.mor.2020@gmail.ru>
See more here https://github.com/CyberMor/sampvoice
Copyright (c) Daniel (CyberMor) 2020 All rights reserved
*/
#pragma once
#include <array>
#include <atomic>
#include <cstdint>
#include <vector>
#include <ysf/structs.h>
#include "ControlPacket.h"
#include "VoicePacket.h"
class Stream {
protected:
int attachedSpeakersCount = 0;
int attachedListenersCount = 0;
std::array<std::atomic_bool, MAX_PLAYERS> attachedSpeakers = {};
std::array<std::atomic_bool, MAX_PLAYERS> attachedListeners = {};
ControlPacketContainerPtr packetCreateStream = nullptr;
ControlPacketContainerPtr packetDeleteStream = nullptr;
protected:
Stream();
public:
Stream(const Stream& object) = delete;
Stream(Stream&& object) = delete;
Stream& operator=(const Stream& object) = delete;
Stream& operator=(Stream&& object) = delete;
void PushVoicePacket(VoicePacket& packet);
virtual bool AttachListener(const uint16_t playerId);
bool HasListener(const uint16_t playerId);
virtual bool DetachListener(const uint16_t playerId);
virtual void DetachAllListeners(std::vector<uint16_t>& detachedListeners);
bool AttachSpeaker(const uint16_t playerId);
bool HasSpeaker(const uint16_t playerId);
bool DetachSpeaker(const uint16_t playerId);
void DetachAllSpeakers(std::vector<uint16_t>& detachedSpeakers);
virtual ~Stream();
};
| true |
d73b25b34a5a3aa51afac14dae83008d40a7c4b8 | C++ | Dnelre-Slin/Cplusplus_school_assignments | /NetworkTest/NetworkTest/Main.cpp | UTF-8 | 2,186 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
int main(int argc, char *argv[])
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
exit(1);
}
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr, "usage: showip hostname\n");
return 1;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}
printf("IP addresses for %s:\n\n", argv[1]);
for (p = res; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// get the pointer to the address itself,
// different fields in IPv4 and IPv6:
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
}
else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res); // free the linked list
WSACleanup();
return 0;
}
//int main()
//{
// WSADATA wsaData;
//
// //sockaddr_in sa = getaddrinfo();
//
// if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
// {
// fprintf(stderr, "WSAStartup failed.\n");
// exit(1);
// }
//
// //sockaddr_in sa;
// //sockaddr_in6 sa6;
//
// //sa.sin_addr. = INADDR_ANY;
// //sa6.sin6_addr = in6addr_any;
//
// int status;
// struct addrinfo hints;
// struct addrinfo *servinfo;
//
// memset(&hints, 0, sizeof(hints));
// hints.ai_family = AF_UNSPEC;
// hints.ai_socktype = SOCK_STREAM;
// hints.ai_flags = AI_PASSIVE;
//
// if ((status = getaddrinfo(NULL, "3490", &hints, &servinfo)))
// {
// fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
// exit(1);
// }
//
// freeaddrinfo(servinfo);
//
// system("PAUSE");
// return 0;
//} | true |
c62686cd470d76cd253f7682771a5719a4944c2a | C++ | luciandinu93/CPlusPlusLearning | /Chapter2/Lab2-13.cpp | UTF-8 | 321 | 3.171875 | 3 | [] | no_license | /* Factorial iterative
*/
#include <iostream>
using namespace std;
int main(void)
{
int n, i;
unsigned long long int result;
cout << "Enter n:";
cin >> n;
result = 1;
for (i = 1; i <= n; i++)
{
result *= i;
}
cout << n << "! = " << result << endl;
return 0;
}
| true |
bd6d73f39d62c082f036633c2b62a2c6ba08cb80 | C++ | xwlee9/cpp | /study/cpp_5stl.cpp | UTF-8 | 5,836 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
// #pragma warning(disable:xxxx) //去掉代号为xxxx的warning
// stl standard template library
// //========================================算法(最后)
void fun(char c)
{
cout << c;
}
void FunForeach() // 遍历函数
{
string str("hiefaecgra");
for_each(str.begin(),str.end(),fun); // 头文件<algorithm>
// sort(str.begin(),str.end()); // 排序 默认从小到大
sort(str.begin(),str.end(),greater<char>()); //从大到小排序 头文件<functional>
cout << endl;
for_each(str.begin(),str.end(),fun);
cout << endl;
}
int main()
{
string str; // 无参数构建函数
const char* str1 = str.c_str();
string str2(5, 'x'); // length 个 ch
cout << str2.c_str() << endl;
string str3("abcde"); // 字符串初始化
cout << str3.c_str() << endl; // abcde
string str4("abcdef", 3); // 参数2 length
cout << str4.c_str() << endl; // abc
string str5 ("abcdefg", 3, 3); //参数2 index 参数3 length
cout << str5.c_str() << endl; // def
string str6 (str5);
cout << str6.c_str() << endl; // def 拷贝构造
cout << str6;
string str7("nice");
cout << str7 << endl;
// cin >> str7;
// cout << str7;
// // ========================输出全部
cout << str7 <<endl;
cout << str7.c_str() << endl;
// // ========================输出单个字符
cout << str7[1] << endl;
cout << str7.at(1) << endl;
// // ========================修改
str7[1] = 'a';
cout << str7 << endl;
str7.at(0) = 'f';
cout << str7 << endl;
str7.insert(2, str2); // 第二个位置插入str2
cout << str7 << endl;
str7.insert(2, str3, 0, 2); // 第二个位置插入str3 中的index 为0的开始插入两个值
cout << str7 << endl;
str7.insert(0, "mmm");
str7.insert(0, 3, 'n');
cout << str7 << endl; //nnnmmmfaabxxxxxce
str2 += str3;
str2 += "zzz";
cout << str2 <<endl; //xxxxxabcdezzz
str2.append("111");
cout << str2 << endl; //xxxxxabcdezzz111
str2.append("222", 2);
str2.append(2, 'm');
cout << str2 << endl; //xxxxxabcdezzz11122mm
str7 = "xxx";
str2 = str7;
cout << str2 << " " << str7 << endl; //xxx xxx
// cin >> str;
// cout << str << endl;
str2.assign("abcdefg", 3); //赋值
cout << str2 <<endl;
str7.erase(1,2); // 从1开始 删除2个
cout << str7 <<endl; // x
str2.erase(0,str2.length());
// ============================================操作函数
// //比较 < -n = 0 > n
string str8("abdahservewpi");
string str9("abdd");
cout << (str8 > str9) <<endl; // 0
cout << str8.compare(str9) << endl; // -3
cout << str8.compare(1,2,str9) << endl; //1 bd abdd (index length)
// //拷贝 拷贝自己num个字符到str中 返回值为字符串的个数
char arrStr[6] = {0};
str8.copy(arrStr,3,1); //bda (number,index)
cout << arrStr <<endl;
// //查找 指定位置查找 str9 字符 字符串
cout << str8.find("bd",1) << endl; // 1 返回index
// //返回字串 (index, num )
cout << str8.substr(1,5) <<endl; //bdahs
// //交换 swap
str8.swap(str9);
cout << str8 << " " << str9 << endl; //abdd abdahservewpi
// //运算符重载
cout << (str8 + str9) << endl; //abddabdahservewpi
// ============================================迭代器
// //str9 abdahservewpi
string::iterator ite; // 指向string的指针 本质相当于char*
// char *cp = str9.c_str;
ite = str9.begin(); // 指向字符串的第一个元素
for (size_t i = 0; i < str9.size(); i++)
{
cout << ite[i] << " "; //a b d a h s e r v e w p i
cout << *ite << " ";
ite++;
}
// ite = str9.begin();
// for (ite; ite != str9.end(); ite++)
// {
// cout << *ite <<" "; //a b d a h s e r v e w p i
// }
// // 迭代器修改值
ite = str9.begin();
for (ite; ite != str9.end(); ite++)
{
*ite = 'a';
cout << *ite <<" "; //a a a a a a a a a a a a a
}
ite = str9.begin();
ite[2] = 'd';
cout << str9 << endl; //aadaaaaaaaaaa
// // 迭代器失效 当空间大小改变时 迭代器指向的原空间释放 数组申请新的连续的新空间 迭代器失效 要重新赋值begin()
ite = str9.begin();
str9.append(10,'b');
cout << str9 <<endl; //aadaaaaaaaaaabbbbbbbbbb
ite[1] = 'c';
cout << str9 <<endl; //aadaaaaaaaaaabbbbbbbbbb 不变
// // 当不从新申请新空间时 没有问题
string str10(7,'a');
ite = str10.begin();
str10.append(5,'b');
ite[3] = 'c';
cout << str10 <<endl; //aaacaaabbbbb
// // append (begin ,end)
string str11("xbuvw");
str11.append(str10.begin(), str10.begin()+5);
cout << str11 <<endl; //xbuvwaaaca
// // erase 一个或一段 (index) (begin,end)
str11.erase(str11.begin()+1); //删除index=1的元素
cout << str11 <<endl; //xuvwaaaca
// // insert 插入 (iterator,num, string)(iterator,str.begin(),str.end())
str11.insert(str11.begin()+1, 3, 'y');
cout << str11 << endl; //xyyyuvwaaaca
string str12("nice");
str11.insert(str11.begin()+1,str12.begin(), str12.end());
cout << str11 << endl; // xniceyyyuvwaaaca
// ============================================算法
FunForeach();
// print
// hiefaecgra
// aaceefghir
// 从大到小排序:
// rihgfeecaa
return 0;
}
| true |
364177309ef26139d37f10988cc3266d78058413 | C++ | cbtek/KanSolo | /common/database/src/types/Int16Type.cpp | UTF-8 | 502 | 2.546875 | 3 | [
"MIT"
] | permissive | //#-------------------------------------------------
//#
//# File Int16Type.cpp created by shadowefusion on 01-11-2014 at 2:34:0
//#
//#-------------------------------------------------
#include "Int16Type.h"
namespace cbtek {
namespace common {
namespace database {
namespace types{
Int16Type::Int16Type(const std::int16_t &value)
{
m_value=value;
}
std::int16_t Int16Type::getValue() const
{
return m_value;
}
Type Int16Type::getType() const
{
return Type::UINT16;
}
}}}}//namespace
| true |
8897359c80301127e1041a4cf3a49e2f04302c4d | C++ | hesu/projecteuler | /1_100/euler32/main.cpp | UTF-8 | 1,642 | 3.453125 | 3 | [] | no_license | /*
Problem 32 - Pandigital products
*/
// 987 = 654 * 321 (x)
// 가능한 건 다음경우뿐..
// 4n = 3n * 2n, 2n * 2n, 4n * 1n
#include <iostream>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;
void permutation( std::vector<int>nums, std::vector<int> now)
{
if (nums.size() == 0) {
/*
for(int i=0; i<now.size(); i++)
{
cout << now[i] << "-";
}
cout << endl;
*/
// case 1) 4n = 3n * 2n ?
int n1 = now[0] * 1000 + now[1] * 100 + now[2] * 10 + now[3] * 1;
int n2 = now[4] * 100 + now[5] * 10 + now[6] * 1;
int n3 = now[7] * 10 + now[8] * 1;
if( n1 == n2*n3) { cout << "pandigital n1=" << n1 << " ,n2=" << n2 << " ,n3=" << n3 << endl; }
// case 2) 4n = 4n * 1n ?
n2 = now[4] * 1000 + now[5] * 100 + now[6] * 10 + now[7] * 1;
n3 = now[8] * 1;
if( n1 == n2*n3) { cout << "pandigital n1=" << n1 << " ,n2=" << n2 << " ,n3=" << n3 << endl; }
return;
}
for(int i=0; i<nums.size(); i++)
{
std::vector<int> newone( now);
std::vector<int> newnums( nums);
int val = newnums[i];
newone.push_back( val);
newnums.erase( newnums.begin() + i);
permutation( newnums, newone);
}
}
int main(int argc, char** argv)
{
clock_t begin = clock();
/* starting code */
std::vector<int> nums;
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
nums.push_back(4);
nums.push_back(5);
nums.push_back(6);
nums.push_back(7);
nums.push_back(8);
nums.push_back(9);
std::vector<int> now;
permutation( nums, now);
/* end of code */
clock_t end = clock();
std::cout << "elapsed time=" << double(end - begin) / CLOCKS_PER_SEC << std::endl;
return 0;
}
| true |
4ea550c94bf1f1fbd7a58f7d47822e94f03033bd | C++ | Rayleigh0328/OJ | /leetcode/117_3.cpp | UTF-8 | 1,061 | 3.578125 | 4 | [] | no_license | /*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() {}
Node(int _val, Node* _left, Node* _right, Node* _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public:
Node* connect(Node* root) {
if (root == NULL) return root;
Node* special = new Node(-1, NULL, NULL, NULL);
root->next = special;
Node* p1 = root;
Node* p2 = special;
while (p1 != NULL){
if (p1->left != NULL) {p2->next = p1->left; p2 = p2->next;}
if (p1->right != NULL) {p2->next = p1->right; p2 = p2->next;}
if (p1->next == special){
p1->next = NULL;
p1 = special->next;
special->next = NULL;
p2->next = special;
p2 = special;
}
else{
p1 = p1->next;
}
}
return root;
}
};
| true |
0a6439b2fe344eef673e55add934eae4d94e319a | C++ | on1659/STL | /STL/'16.04.29 - 연산자 오버로딩.cpp | UHC | 2,477 | 3.40625 | 3 | [] | no_license | #include "stdafx.h"
#include <Windows.h>
/*
ݺ -
ݺڰ ϱ ε Ŭ
*/
template <class c, class i>
void push(c& con, i iter)
{
con.push_back(iter);
}
inline void gotoxy(int x, int y, const char *msg, ...)
{
COORD pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
va_list arg;
va_start(arg, msg);
vprintf(msg, arg);
va_end(arg);
printf("\n");
}
void sgotoxy(int x, int y)
{
ostream_iterator<char> p(std::cout);
fflush(stdin);
for (int i = 0; i < y; ++i)p = '\n';
for (int i = 0; i < x; ++i)p = ' ';
}
template<class Iter, class Dest>
void cpy(Iter begin, Iter end, Dest des)
{
while (begin != end)
{
*des = *begin; //(d.operator*).operator = (int)
++des; // d.operator()++;
++begin;
//*des++ = *begin++;
}
}
template <class Type>
class My_back
{
protected:
Type *container; // pointer to container
typedef typename Type::value_type _Valty;
public:
explicit My_back(Type& _Cont) : container(_STD addressof(_Cont))
{
}
My_back& operator=(const _Valty& _Val)
{
container->push_back(_Val);
return (*this);
}
My_back& operator*(){ return (*this); }
My_back& operator++(){ return (*this); }
My_back operator++(int){ return (*this); }
};
template <class Type>
class Yoon_Back
{
Type& cont;
public:
Yoon_Back(Type& input) : cont(input) { };
Yoon_Back& operator*() { return *this; }
void operator++() { }
void operator=(int n) { cont.push_back(n); } // ִ´.
};
/*
̷ ȵȴ
ε
*/
int main()
{
ostream_iterator<char> p(std::cout);
p = 'a';
p = 'b';
p = 'c\n';
sgotoxy(3, 3);
cout << " ";
sgotoxy(2, 2);
cout << "2\n";
std::vector<int> v1{ 1,2,3,4,5 };
std::vector<int> v2{ 1,2,3,4,5 };
Yoon_Back <std::vector<int>> a(v2);
printf("[begin : %#x]\n", &v1.begin() );
printf("[rbegin : %#x]\n", &v1.rbegin() );
printf("[end : %#x]\n", &v1.end() );
printf("[rend : %#x]\n\n", &v1.rend() );
cout << "-----------------------------------\n";
int n = v1.size();
for(int i = 0; i < n; ++i )
{
printf("[%#x]\n", &v1[i]);
}
cout << "-----------------------------------\n";
cpy(v1.rbegin(), v1.rend(), a);
for (auto &p : v2) cout << p << " ";
std::cout << std::endl;
cout << "\n-------------------------------\n";
push(v1, 100);
for (auto &p : v1) cout << p << " ";
} | true |
dd45fa12e657a39eae688aa26f7881da806b2716 | C++ | MJJBennett/gamebot | /src/api/interaction.hpp | UTF-8 | 4,654 | 2.71875 | 3 | [] | no_license | #ifndef QB_INTERACTION_HPP
#define QB_INTERACTION_HPP
// In the future, we should probably avoid
// having this include brought in. (TODO)
#include <nlohmann/json.hpp>
#include "api.hpp"
#include "message.hpp"
#include "user.hpp"
#include "utils/debug.hpp"
#include "utils/json_utils.hpp"
#include "web/strings.hpp"
namespace qb::api
{
using json = nlohmann::json;
struct ApplicationCommandInteractionData
{
static ApplicationCommandInteractionData create(const nlohmann::json& src)
{
if (src.empty()) return {};
qb::log::point("Creating ApplicationCommandInteractionData from ", src.dump());
return ApplicationCommandInteractionData{src.value("id", ""), src.value("name", ""),
src.value("custom_id", ""),
src.value("component_type", -1)};
}
std::string to_string() const
{
return "ApplicationCommandInteractionData{" + id + ", " + name + ", " + custom_id + ", " +
std::to_string(component_type) + "}";
}
const std::string id;
const std::string name;
const std::string custom_id;
const int component_type;
};
struct InteractionResponse
{
InteractionResponse(int type = 4) : type(type)
{
}
nlohmann::json as_json()
{
nlohmann::json resp{{"type", type}};
if (content || flags)
{
resp["data"] = nlohmann::json::object();
}
if (content)
{
resp["data"]["content"] = *content;
}
if (flags)
{
resp["data"]["flags"] = flags;
}
return resp;
}
InteractionResponse& with_type(int val)
{
type = val;
return *this;
}
InteractionResponse& with_content(std::string val)
{
content = std::move(val);
return *this;
}
InteractionResponse& with_flags(int val)
{
flags |= val;
return *this;
}
int type = 4;
std::optional<std::string> content;
int flags = 0;
};
struct Interaction
{
Interaction() = default;
Interaction(const std::string& id,
const std::string& token,
const User& user,
const ApplicationCommandInteractionData& data,
const std::optional<api::Channel>& channel,
const std::optional<api::Message>& message)
: id(id), token(token), user(user), data(data), channel(channel), message(message)
{
}
std::string key() const
{
return (message ? (*message).id : "IDK_SLASH_COMMAND");
}
std::string to_string() const
{
return "nothing right now for this :)";
}
template <bool safe = false>
static Interaction create(const json& src)
{
// https://discord.com/developers/docs/interactions/slash-commands#interaction
if constexpr (safe)
{
if (src.find("channel_id") == src.end())
{
::qb::log::err("Interaction being constructed from incorrect tier ",
"of JSON data (or invalid data):\n", src.dump(2));
return Interaction{};
}
}
const auto ujson = src.contains("user") ? src["user"] : src["member"]["user"];
const auto djson = src.contains("data") ? src["data"] : nlohmann::json{};
using dtype = ApplicationCommandInteractionData;
qb::log::point("Creating an interaction.");
return api::Interaction(
src["id"], src["token"], api::User::create(ujson), dtype::create(djson),
(src.contains("channel_id") ? api::Channel(src["channel_id"], src["guild_id"])
: std::optional<api::Channel>{}),
(src.contains("message") ? api::Message::create(src["message"]) : std::optional<api::Message>{}));
}
static InteractionResponse response(int type = 4)
{
return InteractionResponse(type);
}
const std::string id;
const std::string token;
const User user{};
const ApplicationCommandInteractionData data{};
const std::optional<api::Channel> channel;
const std::optional<api::Message> message;
};
} // namespace qb::api
namespace qb
{
inline std::string interaction(const qb::api::Interaction& interaction)
{
return "/api/v8/interactions/" + interaction.id + "/" + interaction.token + "/callback";
}
namespace endpoints
{
inline std::string of(const qb::api::Interaction& i)
{
return ::qb::interaction(i);
}
} // namespace endpoints
} // namespace qb
#endif // QB_INTERACTION_HPP
| true |
a56bd978a2723ef7166569abec99b0fc51116889 | C++ | zhoushiwei/DemoOpenCV | /PlateSegment/fts_base_linesegment.h | UTF-8 | 995 | 2.546875 | 3 | [] | no_license | /*
* fts_base_linesegment.h
*
* Created on: May 7, 2014
* Author: sensen
*/
#ifndef FTS_BASE_LINESEGMENT_H_
#define FTS_BASE_LINESEGMENT_H_
#include "fts_base_externals.h"
#include "fts_base_util.h"
//using namespace cv;
class FTS_BASE_LineSegment
{
public:
Point p1, p2;
float slope;
float length;
float angle;
// FTS_BASE_LineSegment(Point point1, Point point2);
FTS_BASE_LineSegment();
FTS_BASE_LineSegment(int x1, int y1, int x2, int y2);
FTS_BASE_LineSegment(Point p1, Point p2);
void init(int x1, int y1, int x2, int y2);
bool isPointBelowLine(Point tp);
float getPointAt(float x) const;
Point closestPointOnSegmentTo(Point p);
Point intersection(FTS_BASE_LineSegment line);
FTS_BASE_LineSegment getParallelLine(float distance);
Point midpoint();
inline std::string str()
{
std::stringstream ss;
ss << "(" << p1.x << ", " << p1.y << ") : (" << p2.x << ", " << p2.y << ")";
return ss.str() ;
}
};
#endif /* FTS_BASE_LINESEGMENT_H_ */
| true |
91b3f2c1886eeb9360a62e762b461fdbbc0a0370 | C++ | MaoHJ-Official/os_experiment4_bankerAlgorithm- | /src/os_test4.cpp | UTF-8 | 6,855 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<vector>
#include<ctime>
#include<cstring>
#include<unistd.h>
#include<cstdlib>
#include<pthread.h>
#define RESTYPE 100 // 资源的种类数
#define NTHREAD 50 // 线程的数目
using namespace std;
pthread_mutex_t mutex; // 互斥信号量
pthread_cond_t cond; // 条件变量
class BankerAlgorithm { // 银行家算法
public:
int nthread; // 线程数
int restThread; // 剩余正在执行的线程数目
int nres; // 资源数
int vis[NTHREAD]; // 标示这个进程有没有访问过
int threadFinished[NTHREAD]; // 标示这个线程是否已经结束
vector<int> resMax[NTHREAD]; // 每个线程对各类资源的最大的需求量
vector<int> resAllocation[NTHREAD]; // 每个线程当前应经分配到各类资源的情况
vector<int> resNeed[NTHREAD]; // 每个线程还需要每类资源的情况
vector<int> resAvailable; // 各类资源的剩余可以利用的
private:
void toNeed() {
for (int i = 0; i < nthread; ++i)
for (int j = 0; j < nres; ++j)
resNeed[i].push_back(resMax[i][j]), resAllocation[i].push_back(0);
}
bool threadAafetyDetection(int idThread) {
// 线程安全检测
vector<int> tmpResAvailable(resAvailable);
vector<int> threadSafeSequence; // 线程安全序列
int cntThread = 0;
memset(vis, 0, sizeof(vis));
while (threadSafeSequence.size() < restThread) {
bool findRunThread = false;
for (int i = 0; i < nthread; ++i)
if (!vis[i] && !threadFinished[i]) {
int j;
for (j = 0; j < nres; ++j)
if (resNeed[i][j] > tmpResAvailable[j])
break;
if (j >= nres) {
// 各类所需要的资源的数目 小于或等于各类剩余资源的数目
// 该进程可以成功的运行完毕
findRunThread = true;
vis[i] = 1;
threadSafeSequence.push_back(i);
for (j = 0; j < nres; ++j)
tmpResAvailable[j] += resAllocation[i][j];
}
}
if (!findRunThread)
break; // 找不到下一个可以运行的线程,则退出
}
if (threadSafeSequence.size() == restThread) {
cout << "此时系统处于安全状态,存在线程安全序列如下:" << endl;
for (int i = 0; i < threadSafeSequence.size(); ++i)
cout << threadSafeSequence[i] << " ";
cout << endl;
return true;
} else {
cout << "此时系统处于不安全状态!!!资源无法分配!!!进程" << idThread << "将被阻塞!!!"
<< endl; // 等到下一次resAvailable更新的时候再将该进程唤醒
return false;
}
}
public:
BankerAlgorithm() {
}
void init() {
memset(threadFinished, 0, sizeof(threadFinished));
// 初始化线程的数目, 资源种类的数目以及每种资源的数目
cout << "请输入线程的数目和资源的种类数目:" << endl;
cin >> nthread >> nres;
restThread = nthread;
cout << "请输入每种资源的数目:" << endl;
for (int i = 0; i < nres; ++i) {
int k;
cin >> k;
resAvailable.push_back(k);
}
cout << "请输入每个线程对某类资源最大的需求:" << endl;
for (int i = 0; i < nthread; ++i) {
cout << "线程" << i << "需要的资源:" << endl;
for (int j = 0; j < nres; ++j) {
int k;
cin >> k;
resMax[i].push_back(k);
}
}
toNeed();
}
void returnRes(int idThread) {
for (int i = 0; i < nres; ++i)
resAvailable[i] += resAllocation[idThread][i], resAllocation[idThread][i] =
0;
}
int bankerAlgorithm(int idThread, vector<int> res) { //进程idThread对资源idRes的请求数量为k
for (int i = 0; i < res.size(); ++i) {
int idRes = i, k = res[i];
if (k <= resNeed[idThread][idRes]) {
if (k > resAvailable[idRes]) {
// 让进程阻塞
cout << "ERROR!!!线程" << idThread << "请求" << idRes
<< "类资源数目大于该类剩余资源的数目!" << endl << endl;
return 1;
}
} else { //让进程重新请求资源
cout << "ERROR!!!线程" << idThread << "请求" << idRes
<< "类资源数目大于所需要的该类资源的数目!" << endl << endl;
return 2;
}
}
for (int i = 0; i < res.size(); ++i) {
int idRes = i, k = res[i];
resAvailable[idRes] -= k;
resAllocation[idThread][idRes] += k;
resNeed[idThread][idRes] -= k;
}
//安全性算法的检测
if (!threadAafetyDetection(idThread)) { //不能分配资源, 要将idThread这个线程阻塞
for (int i = 0; i < res.size(); ++i) {
int idRes = i, k = res[i];
resAvailable[idRes] += k;
resAllocation[idThread][idRes] -= k;
resNeed[idThread][idRes] += k;
}
return 3;
}
cout << "线程" << idThread << "获得资源:";
for (int i = 0; i < res.size(); ++i)
cout << " " << i << "类:" << res[i];
cout << endl << endl;
return 0;
}
};
BankerAlgorithm ba;
void* thread_hjzgg(void *arg) {
long long idThread = (long long) arg; // 得到线程的标号
srand((int) time(0));
// 开始进行线程资源的请求
vector<int> res;
for (int i = 0; i < ba.nres; ++i) {
int k = ba.resNeed[idThread][i] == 0 ?
0 : rand() % ba.resNeed[idThread][i] + 1; // 线程对资源i申请的数目
res.push_back(k);
}
while (1) {
if (pthread_mutex_lock(&mutex) != 0) {
cout << "线程" << idThread << "加锁失败!!!" << endl;
pthread_exit(NULL);
}
bool isAllocationFinished = true; // 该线程是否已经将资源请求完毕
for (int i = 0; i < ba.nres; ++i)
if (ba.resNeed[idThread][i] != 0) {
isAllocationFinished = false;
break;
}
if (isAllocationFinished) {
cout << "线程" << idThread << "资源分配完毕!!!进程得到想要的全部资源后开始继续执行!" << endl;
cout << "................" << endl;
sleep(1);
cout << "线程" << idThread << "执行完毕!!!" << endl << endl;
--ba.restThread;
ba.threadFinished[idThread] = 1; // 线程结束
ba.returnRes(idThread);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
switch (ba.bankerAlgorithm(idThread, res)) {
case 3: // 系统会进入不安全状态,不能进行资源的分配,先进行阻塞
case 1: // 进程阻塞
pthread_cond_wait(&cond, &mutex);
break;
case 2: // 重新分配资源
case 0: // 资源分配成功, 接着在申请新的资源
res.clear();
for (int i = 0; i < ba.nres; ++i) {
int k = ba.resNeed[idThread][i] == 0 ?
0 : rand() % ba.resNeed[idThread][i] + 1; // 线程对资源i申请的数目
res.push_back(k);
}
break;
default:
break;
}
sleep(1);
pthread_mutex_unlock(&mutex);
}
}
int main() {
pthread_t tid[NTHREAD];
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
ba.init();
for (int i = 0; i < ba.nthread; ++i)
pthread_create(&tid[i], NULL, thread_hjzgg, (void*) i);
for (int i = 0; i < ba.nthread; ++i)
pthread_join(tid[i], NULL);
return 0;
}
| true |
bfd7b30e0fd0992c789c741c0d8891470b1fb100 | C++ | danieljsalazar2/15Examples | /linkList.cpp | UTF-8 | 8,259 | 3.453125 | 3 | [
"MIT"
] | permissive | //
// linkList.cpp
//
// Keith Mehl
// 04/28/03
// CSCI-15 Example program
// a simple singly-linked linked list with carriers
//
#include <iostream>
using namespace std;
// The user manages the data elements
// the list routines can only see (but not change) the keys
struct DATA
{
int key;
char data[31]; // or whatever fields you need...
};
// the linked list routines manage the list "carrier" elements
// they are never seen by the user
struct CARRIER
{
DATA *ptr;
CARRIER *next;
};
// the linked list class - a 'container class'
// it holds data objects used by the client
class LINKLIST
{
private:
CARRIER *head; // pointer to the first element in the list
static CARRIER *free; // static means one var shared by all objects
CARRIER *getListEl( void ); // get a carrier
void freeListEl( CARRIER *p ); // release a carrier
void PrintRevHelper( CARRIER *p ); // recursive print helper method
static int numLists; // how many lists share free list
bool traverseOK; // if traversing, did we change the list?
public:
const static int Forward; // shared const literals
const static int Reverse; // for list print direction
LINKLIST( void ) { numLists++; head = NULL; } // one more empty list
~LINKLIST( void ); // destructor
void AddEl( DATA *e ); // add sorted in ascending order
DATA *removeByKey( int key );
void PrintList( int direction );
int IsInList( int key);
int IsEmpty( void ) { return head == NULL; }
DATA *traverse( int first ); // iterator
};
// static class member initializers - executed at load time
CARRIER * LINKLIST::free = NULL;
const int LINKLIST::Forward = 1;
const int LINKLIST::Reverse = -1;
int LINKLIST::numLists = 0;
// get a carrier node - check free list first, else allocate
CARRIER *LINKLIST::getListEl( void )
{
CARRIER *p;
if( free != NULL ) {
p = free;
free = free->next;
} else {
p = new CARRIER;
}
p->ptr = NULL;
p->next = NULL;
return p;
}
// free element - just stash it on the free
// list to try to minimize heap fragmentation
void LINKLIST::freeListEl( CARRIER *p )
{
p->next = free;
p->ptr = NULL;
free = p;
return;
}
// destructor - free list elements and carriers
// and free list of carriers only if needed (last list destroyed)
LINKLIST::~LINKLIST( void )
{
cout << "In destructor, list count " << numLists << endl;
CARRIER *p = head, *q;
while( p != NULL ) {
q = p;
p = p->next;
delete q->ptr; // destruct data element
delete q; // and carrier element
}
numLists--; // one fewer list
if( numLists == 0 ) { // if last list, delete
p = free; // the free list of carriers
while( p != NULL ) {
q = p;
p = p->next;
delete q;
}
}
}
// recursive helper to print list in reverse sequence
void LINKLIST::PrintRevHelper( CARRIER *p )
{
if( p != NULL ) {
PrintRevHelper( p->next );
// in a "real" OO environment, we would use a "call-back"
// function into the client here to print the data...
cout << p->ptr->key << '\t' << p->ptr->data << endl;
}
return;
}
// user supplies data element *e to add to list by key
void LINKLIST::AddEl( DATA *e )
{
CARRIER *d = getListEl(), *p, *q;
d->ptr = e;
// "inchworm" down the list to find where to insert the element
// empty for() loop bode - do the work in the loop header
for( p = head, q = NULL;
p != NULL && p->ptr->key < d->ptr->key;
q = p, p = p->next );
if( q == NULL ) {
d->next = head;
head = d;
} else {
d->next = p;
q->next = d;
}
traverseOK = false; // cannot traverse any more
return;
}
// remove the first match to key (may have duplicates)
DATA *LINKLIST::removeByKey( int key )
{
CARRIER*p = head, *q = NULL;
DATA *d;
// equivalent while() loop to for() loop above
while( p != NULL && p->ptr->key != key ) {
q = p;
p = p->next;
}
if( p == NULL ) {
return NULL; // indicate key not found
}
else if( q == NULL ) {
head = head->next;
} else {
q->next = p->next;
}
d = p->ptr;
freeListEl( p ); // don't delete here, manage fragmentation on heap!
traverseOK = false; // cannot traverse any more
return d;
}
// forward can be iterative, reverse needs help (or use a stack)
void LINKLIST::PrintList( int direction )
{
CARRIER *p = head;
if( direction == 1 ) {
while( p != NULL ) {
// in a "real" OO environment, we would use a "call-back"
// function into the client here to print the data...
cout << p->ptr->key << '\t' << p->ptr->data << endl;
p = p->next;
}
} else {
PrintRevHelper( p );
}
return;
}
// return true if key is in list, else false
int LINKLIST::IsInList( int key )
{
CARRIER *p = head;
while( p != NULL && p->ptr->key < key ) {
p = p->next;
}
return p != NULL && p->ptr->key == key;
}
// iterator - each call after first=true advances pointer
// down the list returning the assuciated data pointer,
// until end of list when you get NULL back
// by agreement with the client, DATA cannot be changed
DATA * LINKLIST::traverse( int first )
{ // a static local variable has permanent duration
static CARRIER *p = NULL;
if( first ) {
p = head;
traverseOK = true; // new traversal is always O.K.
} else if( !traverseOK ) {
p = NULL; // can't keep traversing a modified list
} else if( p != NULL ) {
p = p->next;
}
if( p != NULL ) {
return p->ptr;
}
return NULL;
}
// a simple menu-driven client
int main()
{
int choice = 0, key;
DATA d, *e;
LINKLIST list;
while( choice != 8 ) {
cout << "\n\n1. add an element\n"
<< "2. see if an element exists\n"
<< "3. remove an element by key\n"
<< "4. print forward\n"
<< "5. print reverse\n"
<< "6. traverse (first)\n"
<< "7. traverse (next)\n"
<< "8. quit\n" << "\nEnter chioce : "
<< flush;
cin >> choice;
switch( choice )
{
case 1: cout << "Enter key and data (max 30 chars) : " << flush;
cin >> d.key >> d.data;
e = new DATA;
(*e) = d;
list.AddEl( e );
break;
case 2: cout << "Enter key : " << flush;
cin >> key;
if( list.IsInList( key ) ) {
cout << "Key " << key << " is in the list\n";
} else {
cout << "Nope, the key " << key << " isn't there\n";
}
break;
case 3: cout << "Enter key : " << flush;
cin >> key;
e = list.removeByKey( key );
if( e == NULL ) {
cout << "The key " << key << " wasn't there!\n";
} else {
cout << "Key " << key << " has data " << e->data << endl;
delete e;
}
break;
case 4: list.PrintList( LINKLIST::Forward );
break;
case 5: list.PrintList( LINKLIST::Reverse );
break;
case 6: e = list.traverse( true );
if( e == NULL ) {
cout << "There is no first key!\n";
} else {
cout << "Key " << e->key << " has data " << e->data << endl;
}
break;
case 7: e = list.traverse( false );
if( e == NULL ) {
cout << "There is no next key!\n";
} else {
cout << "Key " << e->key << " has data " << e->data << endl;
}
break;
case 8: cout << "Goodbye!" << endl;
break;
default: cout << "What???\n\n" << flush; // should not happen, but...
}
}
return 0;
}
| true |
e1035079fe7170c5e5aeae3403be4eff41b6adcd | C++ | JangHyeonJun/AlgorithmStudy | /Algorithms/programmers_42839.cpp | WINDOWS-1252 | 2,939 | 3.0625 | 3 | [] | no_license | //#include <string>
//#include <vector>
//#include <bitset>
//#include <set>
//
//using namespace std;
//
//const int MAX = 10000000;
//bitset<MAX> bs;
//set<int> primeNumbers;
//
//void InitBitsetByPrimeNumber()
//{
// bs[0] = bs[1] = true;
// for (int i = 2; i < MAX; i++)
// if (!bs[i])
// for (int j = i * 2; j < MAX; j += i)
// bs[j] = true;
//}
//
//void dfs(vector<bool> visits, string numbers, string currNum = "")
//{
// if (!currNum.empty())
// {
// int number = stoi(currNum);
// if (!bs[number])
// primeNumbers.insert(number);
// }
//
// for (int i=0; i<visits.size(); i++)
// if (!visits[i])
// {
// visits[i] = true;
// dfs(visits, numbers, currNum + numbers[i]);
// visits[i] = false;
// }
//}
//
//int solution(string numbers) {
// InitBitsetByPrimeNumber();
// vector<bool> visits(numbers.size());
// dfs(visits, numbers);
// int answer = primeNumbers.size();
// return answer;
//}
//
//int main()
//{
// string s = "123";
// solution(s);
// return 0;
//}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
////////// Ǯ
//////#include <string>
//////#include <vector>
//////#include <algorithm>
//////using namespace std;
//////const int max_num = 10000000;
//////bool dp[max_num];
//////
//////
//////int countPrimeNum(string numbers)
//////{
////// int count = 0;
////// const int max = atoi(numbers.c_str());
////// vector<bool> used;
//////
////// for (int i = 2; i <= max; i++)
////// {
////// if (dp[i])
////// {
////// bool counting = true;
////// used.clear();
////// used.assign(numbers.length(), false);
////// string s_i = to_string(i);
////// for (int j = 0; j < s_i.length(); j++)
////// {
////// bool findPrime = false;
////// for (int k = 0; k < used.size(); k++)
////// {
////// if (s_i[j] == numbers[k] && !used[k])
////// {
////// findPrime = true;
////// used[k] = true;
////// break;
////// }
//////
////// }
////// if (!findPrime)
////// {
////// counting = false;
////// break;
////// }
////// }
//////
////// if (counting)
////// count++;
////// }
////// }
//////
////// return count;
//////}
//////
//////void makePrime(int n)
//////{
////// dp[0] = false;
////// dp[1] = false;
////// for (int i = 2; i <= n; i++)
////// dp[i] = true;
//////
//////
////// for (int i = 2; i <= n; i++)
////// {
////// if (dp[i])
////// {
////// for (int j = i * 2; j <= n; j += i)
////// dp[j] = false;
////// }
////// }
//////}
//////
//////int solution(string numbers) {
////// sort(numbers.begin(), numbers.end(), greater<int>());
////// makePrime(atoi(numbers.c_str()));
//////
////// return countPrimeNum(numbers);
//////}
//////
////////int main()
////////{
//////// string s = "011";
//////// solution(s);
////////
//////// return 0;
////////} | true |
6bda13b9a05787cda9badea8f70f7ca9cf619f28 | C++ | cbiasco/raytracer | /Final/src/Parser.cpp | UTF-8 | 2,438 | 3.3125 | 3 | [] | no_license | //
// Parser.cpp
//
// Code by Caleb Biasco (biasc007) for Assignment-1 of CSCI5607
/*
* The Parser class is meant to streamline the file-reading process but
* still restrict the user from messing with the input stream.
* The user can get keywords and numbers from a specified file and
* check if an expected token was a number.
*/
#include "Parser.h"
using std::ifstream;
using std::string;
using std::stringstream;
Parser::Parser() {}
Parser::~Parser()
{
if (m_inputFile.is_open())
m_inputFile.close();
}
bool Parser::loadFile(string filename)
{
// Close the currently opened file.
if (m_inputFile.is_open())
m_inputFile.close();
// Try to open the requested file.
m_inputFile.open(filename);
if (m_inputFile.fail())
return false;
// Reset the EndOfFile flag.
m_eof = false;
return true;
}
bool Parser::endOfFile()
{
return m_eof;
}
void Parser::nextLine()
{
if (m_inputFile.is_open())
{
// Get the next line from the input file and put it in the string. If it's the
// end of the file, close the file, set the EndOfFile flag and leave.
if (!std::getline(m_inputFile, m_curLineStr))
{
m_inputFile.close();
m_eof = true;
return;
}
// Load the line into the stringstream.
m_curLineSS.clear();
m_curLineSS.str(m_curLineStr);
}
}
double Parser::getNum(bool &b)
{
// Grab the next line while there's nothing to read from the current one.
while (!m_curLineSS || m_curLineSS.peek() <= 0 || m_curLineSS.peek() == '#')
{
if (m_eof)
{
b = false;
return -1;
}
nextLine();
}
// Return the next token in the line.
double d;
m_curLineSS >> d;
b = b && !m_curLineSS.fail();
return d;
}
bool Parser::skipChar(char c)
{
char s;
m_curLineSS >> s;
if (c == s)
return true;
return false;
}
char Parser::peekChar()
{
return m_curLineSS.peek();
}
string Parser::getKeyword()
{
// Grab the next line while there's nothing to read from the current one.
while (!m_curLineSS || m_curLineSS.peek() <= 0 || m_curLineSS.peek() == '#')
{
if (m_eof)
return "";
nextLine();
}
// Return the next token in the line.
string str;
m_curLineSS >> str;
return str;
}
string Parser::swapFileName(string pathAndFile, string newFile)
{
int pathEnd = pathAndFile.length() - 1;
while (pathEnd > 0 && pathAndFile[pathEnd] != '\\' && pathAndFile[pathEnd] != '/')
pathEnd--;
if (pathEnd <= 0)
return newFile;
return pathAndFile.substr(0, pathEnd + 1) + newFile;
}
| true |
b18c6831ac8db8876eddc7aa069b597d0be19930 | C++ | jeanfilho/LandscapeRayTracer | /PointdataGenerator/main.cpp | UTF-8 | 5,054 | 3.15625 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <random>
#include <cmath>
#include <sstream>
#include <iomanip>
int GRID_SIZE = 256 + 1;
struct Point
{
Point()
{
x = 0;
y = 0;
z = 0;
}
Point(float a, float b, float c)
{
x = a;
y = b;
z = c;
}
float x;
float y;
float z;
};
std::vector<std::vector<Point>> diamondSquare(float startDeviation);
void diamondStep(int x, int y, int stepSize, float roughness, std::vector<std::vector<Point>> *grid);
void squareStep(int x, int y, int stepSize, float roughness, std::vector<std::vector<Point>> *grid);
void addNoise(std::vector<std::vector<Point>>* grid, float deviation);
void scaleData(std::vector<std::vector<Point>>* grid, float factor);
void savePointData(std::vector<std::vector<Point>>* grid, std::string filename);
/***********************************
MAIN LOOP
************************************/
void main(int argc, char** argv)
{
float noise = 0.5;
float roughness = 1;
float scaleFactor = 10;
std::string filename = "data";
if (argc > 1)
GRID_SIZE = atoi(argv[1]) + 1;
std::cout << "Generating points using Diamond-Square..." << std::endl;
std::vector<std::vector<Point>> points = diamondSquare(1);
//std::cout << "Adding noise..." << std::endl;
//addNoise(&points, noise);
std::cout << "Scaling points..." << std::endl;
scaleData(&points, scaleFactor);
std::cout << "Saving file..." << std::endl;
savePointData(&points, filename);
system("pause");
}
/***********************************
METHODS
************************************/
std::vector<std::vector<Point>> diamondSquare(float startDeviation)
{
std::default_random_engine gen(time(NULL));
std::uniform_real_distribution<float> dist(0, startDeviation);
std::vector<std::vector<Point>> result(GRID_SIZE);
//Initialize grid
std::cout << "Initializing grid..." << std::endl;
for (int i = 0; i < GRID_SIZE; i++)
{
result[i] = std::vector<Point>(GRID_SIZE);
for (int j = 0; j < GRID_SIZE; j++)
{
result[i][j] = Point((float)i, (float)j, 0);
}
}
//Set random values at the corners
result[0][0].z = dist(gen);
result[0][GRID_SIZE - 1].z = dist(gen);
result[GRID_SIZE - 1][0].z = dist(gen);
result[GRID_SIZE - 1][GRID_SIZE - 1].z = dist(gen);
//Diamond-Square Loop
std::cout << "Performing Diamond-Square Algorithm..." << std::endl;
dist = std::uniform_real_distribution<float>(0, 1);
int count = 1;
for (int i = GRID_SIZE; i > 1; i /= 2)
{
for (int x = i / 2; x < GRID_SIZE; x += i)
for(int y = i / 2; y < GRID_SIZE; y += i)
{
diamondStep(x, y, i/2, pow(dist(gen),count), &result);
squareStep(x, y - i / 2, i / 2, pow(dist(gen), count), &result);
squareStep(x - i / 2, y, i / 2, pow(dist(gen), count), &result);
squareStep(x + i / 2, y, i / 2, pow(dist(gen), count), &result);
squareStep(x, y + i / 2, i / 2, pow(dist(gen), count), &result);
}
++count;
}
return result;
}
void diamondStep(int x, int y, int stepSize, float r, std::vector<std::vector<Point>> *grid)
{
float tl, tr, bl, br;
br = (*grid)[x + stepSize][y + stepSize].z;
bl = (*grid)[x - stepSize][y + stepSize].z;
tr = (*grid)[x + stepSize][y - stepSize].z;
tl = (*grid)[x - stepSize][y - stepSize].z;
(*grid)[x][y].z =
((*grid)[x + stepSize][y + stepSize].z
+ (*grid)[x - stepSize][y + stepSize].z
+ (*grid)[x + stepSize][y - stepSize].z
+ (*grid)[x - stepSize][y - stepSize].z) / 4 + r;
}
void squareStep(int x, int y, int stepSize, float r, std::vector<std::vector<Point>> *grid)
{
float left = 0, right = 0, top = 0, bottom = 0;
int count = 0;
if (x > 0)
{
left = (*grid)[x - stepSize][y].z;
count++;
}
if (x < GRID_SIZE - 1)
{
right = (*grid)[x + stepSize][y].z;
count++;
}
if (y > 0)
{
top = (*grid)[x][y - stepSize].z;
count++;
}
if (y < GRID_SIZE - 1)
{
bottom = (*grid)[x][y + stepSize].z;
count++;
}
(*grid)[x][y].z = (left + right + top + bottom)/count + r;
}
void addNoise(std::vector<std::vector<Point>>* grid, float noise)
{
std::default_random_engine eng;
std::uniform_real_distribution<float> dist(-noise, noise);
for (int i = 0; i < GRID_SIZE; i++)
{
for (int j = 0; j < GRID_SIZE; j++)
{
(*grid)[i][j].z += dist(eng);
(*grid)[i][j].y += dist(eng);
(*grid)[i][j].x += dist(eng);
}
}
}
void scaleData(std::vector<std::vector<Point>>* grid, float factor)
{
for (int i = 0; i < GRID_SIZE; i++)
{
for (int j = 0; j < GRID_SIZE; j++)
{
(*grid)[i][j].z *= factor;
}
}
}
void savePointData(std::vector<std::vector<Point>>* grid, std::string filename)
{
std::ofstream output("../Data/" + filename);
for each (auto &row in (*grid))
{
for each(auto &point in row)
{
std::stringstream stream;
stream << std::fixed << std::setprecision(7) << point.x << " ";
stream << std::fixed << std::setprecision(7) << point.y << " ";
stream << std::fixed << std::setprecision(7) << point.z << std::endl;
output << stream.str();
}
}
output.close();
std::cout << "File saved in /Data/" << filename << std::endl;
}
| true |
9f616efe595ea16cb2d34e56e2d83f05f46e6e6c | C++ | DokyeongLee-3/MetalSlugAdjust | /MetalSlugAdjust/Include/UI/WidgetComponent.h | UTF-8 | 1,380 | 2.71875 | 3 | [] | no_license | #pragma once
#include "../Ref.h"
#include "UIWidget.h"
class CWidgetComponent :
public CRef
{
friend class CGameObject;
private:
CWidgetComponent();
CWidgetComponent(const CWidgetComponent& widget);
~CWidgetComponent();
private:
class CGameObject* m_Owner;
class CScene* m_Scene;
CSharedPtr<CUIWidget> m_Widget;
Vector2 m_Pos;
bool m_Visibility;
public:
Vector2 GetPos() const
{
return m_Pos;
}
void SetPos(const Vector2& Pos)
{
m_Pos = Pos;
}
void SetPos(float x, float y)
{
m_Pos = Vector2(x, y);
}
void SetOwner(class CGameObject* Owner)
{
m_Owner = Owner;
}
void SetScene(class CScene* Scene)
{
m_Scene = Scene;
}
void SetVisibility(bool Visiblity)
{
m_Visibility = Visiblity;
}
bool GetVisibility() const
{
return m_Visibility;
}
void SetWidget(CUIWidget* Widget)
{
m_Widget = Widget;
}
CUIWidget* GetWidget() const
{
return m_Widget;
}
public:
bool Init();
void Update(float DeltaTime);
void PostUpdate(float DeltaTime);
void Collision(float DeltaTime);
void Render(HDC hDC);
CWidgetComponent* Clone();
public:
template <typename T>
T* CreateWidget(const std::string& Name)
{
T* Widget = new T;
Widget->SetName(Name);
Widget->SetScene(m_Scene);
if (!Widget->Init())
{
SAFE_DELETE(Widget);
return nullptr;
}
m_Widget = Widget;
return Widget;
}
};
| true |
465eb27994440252dca0b5ca1158a2ac8da167b1 | C++ | KamskovEM/IiP_381808-1 | /pestrikov.id/Task4/Person.h | WINDOWS-1251 | 1,479 | 2.984375 | 3 | [] | no_license | #pragma once
#include <string>
#include "Date.h"
#include <fstream>
class Person
{
public:
Person(){}
Person(const std::string lastName, const std::string firstName, const std::string middleName);
Person(const std::string lastName, const std::string firstName, const std::string middleName, const std::string phoneNumber);
Person(const std::string lastName, const std::string firstName, const std::string middleName, const Date birthday);
Person(const std::string lastName, const std::string firstName, const std::string middleName, const bool isChosenOne);
Person(const std::string lastName, const std::string firstName, const std::string middleName, const std::string phoneNumber, const Date birthday);
Person(const std::string lastName, const std::string firstName, const std::string middleName, const std::string phoneNumber, const bool isChosenOne);
Person(const std::string lastName, const std::string firstName, const std::string middleName, const std::string phoneNumber, const Date birthday, const bool isChosenOne);
bool operator<(const Person& other);
std::string lastName = " ";
std::string firstName = " ";
std::string middleName = " ";
std::string phoneNumber = " ";
Date birthday = Date(1, 1, 1);
bool isChosenOne = false;
friend std::istream& operator>> (std::istream& in, Person& person);
friend std::ostream& operator<< (std::ostream& out, const Person& person);
};
| true |
e2a4231ed8ba90788bfad494375889ea45295302 | C++ | crstyhs/algoritmos-e-programacao | /lista 7/ex 2.cpp | UTF-8 | 531 | 2.5625 | 3 | [] | no_license | #include<stdio.h>
#include<locale.h>
#include<iostream>
int main(){
setlocale(LC_ALL, "Portuguese_Brazil");
int aluno,contador;
float nota[aluno];
do{
printf("informe a quantidade de alunos a sala possui: ");
setbuf(stdin,0);
scanf("%i",&aluno);
if(aluno<=0 or aluno>49) printf("quantidade informada de forma incorreta\n");}
while(aluno<=0 or aluno>49);
for(contador=0;contador<aluno;contador++){
printf("Digite a nota do aluno: ");
scanf("%f",¬a[contador]);}
system("pause");
return 0;
}
| true |
d33c374f5c2ef2976fd7b6daef8f28ed0fd6d46a | C++ | sahil788/OOP345 | /w6/Grades.h | UTF-8 | 1,376 | 3.609375 | 4 | [] | no_license | #pragma once
#include<iostream>
#include<string>
#include<fstream>
#include<functional>
using namespace std;
class Grades {
string *name=nullptr;
double *marks =nullptr;
string *letter=nullptr;
size_t count=0;
public:
Grades(char *filename) {
fstream file(filename);
if (file.is_open()) {
string line;
while (getline(file, line)) {
count++;
}
// sets the pointer to read file from starting
file.clear(); //clear end-of-file condition
file.seekg(0);
name = new string[count];
letter = new string[count];
marks= new double[count];
for (size_t i = 0; i < count; i++)
{
file >> name[i];
file >>marks[i] ;
}
std::cout << "file " << filename << " has " << count << " lines\n";
file.close();
}
else
{
throw std::string("Grade(\"") + filename + "\") - cannot open file \n ";
}
}
void displayGrades(std::ostream& os, std::function<std::string(double mark)> letter)const
{
for (size_t i = 0; i < count; i++)
{
os << name[i] << " "
<< marks[i] << " "
<< letter(marks[i])
<< "\n";
}
}
}; | true |
086d711ec5b18591d02a59657b24d6554fb8fdac | C++ | foolbread/leetcode | /112/112.cpp | UTF-8 | 813 | 3.359375 | 3 | [] | no_license | /**
* 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:
bool hasPathSum(TreeNode* root, int sum) {
if (root == NULL)
return false;
return cntPathSum(root,0,sum);
}
bool cntPathSum(TreeNode* node, int val, int sum) {
if (node->left == NULL && node->right == NULL)
return (val+node->val) == sum;
bool bleft = false;
bool bright = false;
if (node->left != NULL)
bleft = cntPathSum(node->left,val+node->val,sum);
if (node->right != NULL)
bright = cntPathSum(node->right,val+node->val,sum);
return (bleft||bright);
}
};
| true |
cbe9a34ebb38e75a91904853a00e27d02215a816 | C++ | naught101/ninjas2 | /plugins/Ninjas2/Widgets/RightClickMenu.hpp | UTF-8 | 2,118 | 2.625 | 3 | [] | no_license | #ifndef WOLF_RIGHT_CLICK_MENU_H
#define WOLF_RIGHT_CLICK_MENU_H
#include "Widget.hpp"
#include "Window.hpp"
#include "NanoVG.hpp"
#include "NanoLabel.hpp"
#include <vector>
START_NAMESPACE_DISTRHO
class RightClickMenuItem
{
public:
RightClickMenuItem(int id, const char *label, const char *comment = "", bool enabled = true) noexcept;
int getId();
bool getEnabled();
void setEnabled(bool enabled);
const char *getLabel();
const char *getComment();
bool hasComment();
void getSelected();
void setSelected();
bool isSection();
protected:
bool fIsSection;
private:
int fId;
bool fEnabled;
const char *fLabel;
const char *fComment;
bool fSelected;
Rectangle<float> fBounds;
};
class RightClickMenuSection : public RightClickMenuItem
{
public:
RightClickMenuSection(const char *label) noexcept;
};
class RightClickMenu : private Window,
public NanoWidget
{
public:
class Callback
{
public:
virtual ~Callback() {}
virtual void rightClickMenuItemSelected(RightClickMenuItem *rightClickMenuItem) = 0;
};
RightClickMenu(NanoWidget *parent) noexcept;
~RightClickMenu();
void show(int posX, int posY);
void close();
void addItem(int id, const char *label, const char *comment = "");
void addSection(const char *sectionName);
void setBorderColor(const Color color);
void setRegularFontSize(float fontSize);
void setSectionFontSize(float fontSize);
RightClickMenuItem *getItemById(int id);
void setCallback(Callback *callback) noexcept;
void setSectionEnabled(int index, bool enabled);
protected:
void onNanoDisplay() override;
void onFocusOut() override;
bool onMouse(const MouseEvent &ev) override;
void adaptSize();
Rectangle<float> getBoundsOfItem(const int index);
Rectangle<float> getBoundsOfItemComment(const int index);
private:
void findLongestItem();
std::vector<RightClickMenuItem> fItems;
NanoWidget *fParent;
float fFontSize;
float fSectionFontSize;
float fLongestWidth;
Color fBorderColor;
Margin fMargin;
Callback *fCallback;
};
#endif
END_NAMESPACE_DISTRHO
| true |
0b725f324591d9e58b7e5964d382b6188ee21c1e | C++ | JakubFr4czek/Rotate | /Rotate.cpp | UTF-8 | 1,533 | 3.34375 | 3 | [] | no_license | #include "Rotate.h"
template<typename T>
void transponse(std::vector<std::vector<T>>& arr){
for(auto i = 0; i < arr.size(); i++)
for(auto j = i; j < arr[i].size(); j++){
const int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
template<typename T>
void reverse(std::vector<std::vector<T>>& arr){
for(auto i = 0; i < arr.size(); i++)
for(auto j = 0; j < arr[i].size()/2; j++){
const int temp = arr[i][j];
arr[i][j] = arr[i][arr[i].size()-1-j];
arr[i][arr[i].size()-1-j] = temp;
}
}
template<typename T>
void clc::rotateLeft(std::vector<std::vector<T>>& arr){
reverse(arr);
transpone(arr);
}
template<typename T>
void clc::rotateLeft(std::vector<std::vector<T>>& arr, int times){
while(times>1){
transponse(arr);
times-=2;
}
if(times==1){
reverse(arr);
transponse(arr);
}
}
template<typename T>
void clc::rotateRight(std::vector<std::vector<T>>& arr){
transponse(arr);
reverse(arr);
}
template<typename T>
void clc::rotateRight(std::vector<std::vector<T>>& arr, int times){
while(times>1){
transponse(arr);
times-=2;
}
if(times==1){
transponse(arr);
reverse(arr);
}
}
template<typename T>
void clc::writeArray(std::vector<std::vector<T>>& arr){
for(auto n : arr){
for(auto m : n)
std::cout<<m<<" ";
std::cout<<"\n";
}
} | true |
abf6fd1565e65d0465b3a266123a9dd41a715ccf | C++ | c0dysharma/DSA-Practice | /Recursion/staircase.cpp | UTF-8 | 894 | 4.125 | 4 | [] | no_license | /*
Chapter Assignment
Problem Statement: Staircase
Problem Level: EASY
Problem Description:
A child is running up a staircase with N steps, and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs. You need to return number of possible ways W.
Input format :
Integer N
Output Format :
Integer W
Constraints :
1 <= N <= 30
Sample Input 1 :
4
Sample Output 1 :
7
Sample Input 2 :
5
Sample Output 2 :
13
*/
#include <iostream>
int waysToRun(int N){
// base case
if(N==1 || N==0)
return 1;
if(N<0)
return 0;
// recursive call and return| we have three ways 1 step at a time, 2 steps or 3 steps
return (waysToRun(N-1) + waysToRun(N-2) + waysToRun(N-3));
}
int main(void){
int N;
std::cin >> N;
std::cout << waysToRun(N) << std::endl;
return 0;
}
| true |
fbef3fea4ece1e2445d9452544b368b3bec56204 | C++ | STRICE3904/RandomNumber1 | /RandomNumber1/Source.cpp | UTF-8 | 278 | 2.828125 | 3 | [] | no_license | #include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand((unsigned)time(0));
int randomNumber;
for (int index = 0; index < 3; index++) {
randomNumber = (rand() % 10) + 1;
cout << randomNumber << endl;
}
} | true |
94b7c69528437504b378a942f59199127c75dc6b | C++ | kritsid/sorting | /quick_sort.cpp | UTF-8 | 823 | 3.625 | 4 | [] | no_license | #include<iostream>
using namespace std;
int partition(int arr[], int low, int high){
int pivot = arr[high] ;
int i=low-1;
int temp;
for(int j= low;j<high;j++){
if(arr[j]<pivot){
i++;
// swap[ arr[i] and arr[j]
temp = arr[i];
arr[i] = arr[j];
arr[j] =temp;
}
}
// swap arr[i+1] and arr[j] and return arr[i+1] as the new parition.
temp = arr[i+1];
arr[i+1]=arr[high];
arr[high] = temp;
cout<<arr[i+1]<<" ";
return i+1;
}
void quick_sort(int arr[], int low,int high){
if(low<high){
int p = partition(arr,low,high);
quick_sort(arr,low,p-1);
quick_sort(arr,p+1,high);
}
}
int main(){
int n=10
;int arr[]= {9,7,5,11,12,2,14,3,10,6};
cout<<"pivots are ";
quick_sort(arr,0,n-1);
cout<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}
| true |
501554366a4dc511c463db0a1c2d37711ee141bb | C++ | nmraz/winapitest | /apptest/src/base/expected.h | UTF-8 | 3,241 | 3.625 | 4 | [] | no_license | #pragma once
#include <exception>
#include <stdexcept>
#include <type_traits>
#include <variant>
namespace base {
class bad_expected_access : public std::logic_error {
public:
bad_expected_access();
};
namespace impl {
template<typename T>
class expected_base {
public:
static_assert(!std::is_same_v<T, std::exception_ptr>, "expected<std::exception_ptr> is not supported. Use expected<void> insted.");
static_assert(!std::is_same_v<T, std::monostate>, "expected<std::monostate> is not supported. Use expected<void> insted.");
void set_exception(std::exception_ptr exc);
template<typename Exc>
void set_exception(Exc&& exc);
void reset();
bool empty() const { return std::holds_alternative<std::monostate>(val_); }
bool has_value() const { return std::holds_alternative<T>(val_); }
bool has_exception() const { return std::holds_alternative<std::exception_ptr>(val_); }
std::exception_ptr get_exception() const {
const std::exception_ptr* ptr = std::get_if<std::exception_ptr>(&val_);
return ptr ? *ptr : nullptr;
}
protected:
[[noreturn]] void rethrow_exception() const {
if (auto exc = get_exception()) {
std::rethrow_exception(exc);
}
throw bad_expected_access();
}
std::variant<std::monostate, T, std::exception_ptr> val_;
};
template<typename T>
void expected_base<T>::set_exception(std::exception_ptr exc) {
val_ = std::move(exc);
}
template<typename T>
template<typename Exc>
void expected_base<T>::set_exception(Exc&& exc) {
set_exception(std::make_exception_ptr(std::forward<Exc>(exc)));
}
template<typename T>
void expected_base<T>::reset() {
val_ = std::monostate{};
}
} // namespace impl
template<typename T>
class expected : public impl::expected_base<T> {
public:
constexpr expected() = default;
template<typename U, typename = std::enable_if_t<!std::is_same_v<std::decay_t<U>, expected>>>
expected(U&& val);
template<typename U>
void set_value(U&& val);
T& get() &;
const T& get() const &;
T&& get() && ;
const T&& get() const &&;
};
template<typename T>
template<typename U, typename>
expected<T>::expected(U&& val) {
set_value(std::forward<U>(val));
}
template<typename T>
template<typename U>
void expected<T>::set_value(U&& val) {
this->val_ = static_cast<T>(std::forward<U>(val));
}
template<typename T>
T& expected<T>::get() & {
if (this->has_value()) {
return std::get<T>(this->val_);
}
this->rethrow_exception();
}
template<typename T>
const T& expected<T>::get() const & {
if (this->has_value()) {
return std::get<T>(this->val_);
}
this->rethrow_exception();
}
template<typename T>
T&& expected<T>::get() && {
if (this->has_value()) {
return std::get<T>(std::move(this->val_));
}
this->rethrow_exception();
}
template<typename T>
const T&& expected<T>::get() const && {
if (this->has_value()) {
return std::get<T>(std::move(this->val_));
}
this->rethrow_exception();
}
template<>
class expected<void> : public impl::expected_base<char> {
public:
void set_value() {
val_ = char{};
}
void get() const {
if (!has_value()) {
rethrow_exception();
}
}
};
template<typename T>
expected(T) -> expected<std::decay_t<T>>;
} // namespace base | true |
f5380797186e042c6288627639f2a216b216c5ff | C++ | georgeloyer/Dewpoint | /arduino_code/DewpointDetector/print2digits.ino | UTF-8 | 165 | 2.671875 | 3 | [] | no_license | void print2Digits(byte thisByte) {
if (thisByte < 0xF) {
if (DEBUG) {
Serial.print("0");
}
}
if (DEBUG) {
Serial.print(thisByte, HEX);
}
}
| true |
2b51d60653e4488bb3ac49ddcc84cf6e16f2b01c | C++ | IslamNwishy/BinaryTreesEx | /App.cpp | UTF-8 | 12,708 | 3.15625 | 3 | [] | no_license | #include"BinaryTree.h"
#include"BinaryTree.cpp"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
//Name: Islam Osama Nwishy
//ID#: 900170200
//Assignment 5
//Filename: App.cpp
//PS. I wasn't able to read the script from a .docx file so i changed it to .txt
//So the program will only work properly with files of extention .txt for input
//I tried to find a way online but i couldn't find a solution that wasn't confusing to me.
//Global fstreams
ifstream input;
ofstream output;
//Functions Prototyping
string UpperCase(string x);
void InputFile(BinaryTree<string, int> Tree[], string Script, int& wordcount);
bool ShouldRemove(char c);
string ReadyString();
void Start(BinaryTree<string, int> Tree[], int& wordcount, int State);
int PreRun(BinaryTree<string, int> Tree[], int& wordcount);
void InputOld(BinaryTree <string, int> Tree[]);
void CleanAndAdd(BinaryTree<string, int>Tree[], int& wordcount);
bool Add(BinaryTree<string, int>Tree[], int& wordcount);
string Save(BinaryTree<string, int> Tree[]);
void SearchAndRetrive(BinaryTree<string, int> Tree[]);
void GetWordsofFreq(BinaryTree<string, int>Tree[]);
void main() {
int WordCount = 0; //Holds the word Count Entered to the Tree
BinaryTree<string, int> Tree[26]; //A BinaryTree array of 26 elements (the number of english alphabets)
//I didn't make slots for the numbers and stored them with the letters
Start(Tree, WordCount, PreRun(Tree, WordCount));
//Saving the Data Before Closing the Program
if (WordCount > 0) { //If there is Data in the Tree
cout <<endl<< "If You Don't Want to Save Type 0 (You Will Lose Any Saved Data for the Next Run)";
string filename = Save(Tree); //Stores the file name of the save file chosen by the user
if (filename != "0") { //if the file is not called 0 then the data were saved
output.open("RunFile.txt"); //RunFile.txt is a file that stores some data about the last run
output << 1 << endl; //1 means some data is saved
output << filename << endl; //Save the file name to retrieve it on the next run
output << WordCount << endl; //Save the word count to retrieve it on the next run
output.close();
}
else { //If the user chooses not the save
output.open("RunFile.txt");
output << 0; //0 Means there is no data stored
output.close();
}
}
else { //If there is no data in the Tree
output.open("RunFile.txt");
output << 0; //0 Means there is no data stored
output.close();
}
}
//Checks the File RunFile.txt before starting the program to find a restore saved data if any
//Returns the state of the run, 0 means Initial Run, 1 Means Cumulative/Query Run
int PreRun(BinaryTree<string, int> Tree[], int& wordcount) {
input.open("RunFile.txt");
string in;
if (input.fail()) {
cout << "Couldn't find RunFile.txt" << endl;
return 0;
}
getline(input, in, '\n'); //Takes the state of the Last Run 0 = no data stored, 1 = some data stored
if (in == "1") {
string filename;
getline(input, filename, '\n'); //Take the save file destination
getline(input, in, '\n'); //Take the word count
wordcount = atoi(in.c_str()); //Update the program's word count
input.close();
input.open(filename); //Open the save file
if (input.fail()) {
return 0;
}
InputOld(Tree); //Input the saved data
return 1;
}
else {
input.close();
return 0;
}
}
//Inputs the Old data saved by the last run
void InputOld(BinaryTree <string, int> Tree[]) {
string Key, Data, dummy;
getline(input, dummy, '\n'); //dummy string to remove the headings
while (!input.eof()) {
getline(input, Key, ','); //take the key
getline(input, Data, '\n'); //take the data
Tree[Key[0] % 25].Insert(Key, atoi(Data.c_str())); //Input them to the Tree
}
input.close();
}
//Takes the whole text file and prepares it to be inputed to the Tree
//Returns the String ready to be inputed to the tree
string ReadyString() {
string word, all;
while (!input.eof())
{
getline(input, word, '\n'); //Take line by line
word.push_back(' '); //Add Space (instead of the end of line)
all.append(word); //Append the line to the string that will store the whole file
}
input.close();
replace_if(all.begin(), all.end(), ShouldRemove,' '); //Remove any non ascii characters as well as anything that is not
//alphanumeric or a space or an apostrophe
return all;
}
//Takes a string and inputs it to the Tree word by word
void InputFile(BinaryTree<string, int> Tree[], string Script, int& wordcount) {
int alpha = 0; string word, Key;
istringstream iss(Script); //input string stream (just makes it easier for me to process the string)
while (iss>>word) { //input the string word by word (every word is seperated by a space)
Key = UpperCase(word);
alpha = (int(Key[0])) % 25; //alpha is the index of the key in the array (based on the first letter)
//Every alphabet has a unique index but numbers overlap with them
if (!Tree[alpha].Insert(Key, 1)) //Insert each word with an occurance of 1
Tree[alpha].Update(Key, (Tree[alpha].Retrive(Key) + 1)); //if a word already exists update its data by 1
else
wordcount++; //increment wordcount with each unique word added
}
}
//Changes all characters of a string to uppercase (to remove case sensitivity)
string UpperCase(string x) {
transform(x.begin(), x.end(), x.begin(), ::toupper);
return x;
}
//Decides which characters are left in the text file (ascii, alphanumeric, spaces and or apostrophes)
bool ShouldRemove(char c) {
if (isascii(c))
if (isspace(c)|| isalnum(c)||c=='\'')
return false;
return true;
}
//Entry Point of the Program
//Takes the command from the user and calls the appropriate function to process it
void Start(BinaryTree<string, int> Tree[],int& wordcount, int state) {
int command = 0; //Holds the choice of the user for a process
string dummy, FileName;
cout << "Welcome To the Word Search";
//In case that this is the Initial Run
if (state == 0) {
while (command != 2) { //Exit Case for the intital Run State
cout << endl << endl << "There is No Saved Dictionary\n" << "So You Can:" << endl;
cout << "\t1- Input a new text file and create a Dictionary of it\n\t2- Exit the program\n\n";
cout << "Please Enter your Choice [1,2]" << endl;
cin >> command;
getline(cin, dummy); //Dummy to get rid of the (cin) leftovers
if (cin.fail()) { //Check if the input does not suite the type int
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
command = 0;
}
switch (command)
{
case 1:
if (Add(Tree, wordcount)) //Input a Text file to build a dictionary out of
command = 2; //If this process is successful exit the inital state
break;
case 2: //Exit Case for the program
return;
default:
cout << "Wrong Input! Please Try Again" << endl;
}
}
}
while (command != 8) { //Exit case
cout << endl << endl << "You Can:" << endl << endl;
cout << "\t1- Input a new text file and create a Dictionary of it (This Will Remove Any Exsisting Dictionary)\n\t2- Input a new text file and update the Dictionary";
cout << "\n\t3- Save the Dictionary to a File\n\t4- Find how many words are there in the Dictionary\n\t";
cout << "5- Search for the frequancy of a word\n\t6- Search for all words >= a given frequancy\n\t";
cout << "7- List all words and their frequancies\n\t8- Exit the program\n\n";
cout << "Please Enter your Choice [1,2,3,4,5,6,7,8]" << endl;
cin >> command;
getline(cin, dummy); //Dummy to get rid of the (cin) leftovers
if (cin.fail()) { //Check if the input does not suite the type int
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
command = 0;
}
switch (command) {
case 1:
CleanAndAdd(Tree, wordcount); //Delete the Previous Dictionary and start a new one from an given file
break;
case 2:
Add(Tree,wordcount); //Accumalate the data collected from a file to the existing Dictionary
break;
case 3:
Save(Tree); //Save the Tree to a File specified by the user
break;
case 4:
cout << endl << "There Are: " << wordcount << " Words in the Dictionary" << endl; //output word count
break;
case 5:
SearchAndRetrive(Tree); //Search and Retrieve a given word and its frequancy
break;
case 6:
GetWordsofFreq(Tree); //Search and Retrieve all words that are <= a given frequancy
break;
case 7:
cout << "Word\t\tFrequancy" << endl; //Output all the Dictionary to the screen
for (int i = 0; i < 26; i++)
Tree[i].Traverse();
break;
case 8: //Exit Case
break;
default:
cout << "Wrong Input! Please Try Again" << endl;
break;
}
}
}
//Deletes the Current Dictionary, if any, and Creates a new one using a given Text file
void CleanAndAdd(BinaryTree<string, int>Tree[], int&wordcount) {
string FileName;
cout << "Please Enter the New Text File Destination" << endl;
getline(cin, FileName);
input.open(FileName); //Take the file's name
if (input.fail()) { //Only Delete if you can open the file
input.close();
cout << "Error! Couldn't Open the File Please Try Again" << endl;
return;
}
cout << endl << "Deleting the Original Tree ..." << endl;
for (int i = 0; i < 26; i++) //Delete the old Dictionary
Tree[i].DeleteTree();
cout << "Done!" << endl << "Reading and Creating the new Dictionary ..." << endl;
wordcount = 0;
InputFile(Tree, ReadyString(),wordcount); //Input the new one
cout << "Done!" << endl;
}
//Adds a new Tree and Accumalates its data to the original dictionary, if any.
bool Add(BinaryTree<string,int>Tree[], int&wordcount) {
string FileName;
cout <<endl <<"Please Enter the New Text File Destination" << endl;
getline(cin, FileName); //Take the file's name
input.open(FileName);
if (input.fail()) {
input.close();
cout << "Error! Couldn't Open the File. Please Try Again" << endl;
return false;
}
cout << endl << "Reading the Text File and Adding it to the Dictionary ..." << endl;
InputFile(Tree, ReadyString(),wordcount); //Add the text to the Tree
cout << "Done!" << endl;
return true;
}
//Saves the Dictionary to a given file
//0 means you do not want to save
string Save(BinaryTree<string, int> Tree[]) {
string FileName;
cout <<endl <<"Please Enter a Save File Destination" << endl;
getline(cin, FileName); //Take the file's name
if (FileName == "0")
{
output.close();
cout << "Error! Couldn't Open the File. Please Try Again" << endl;
return FileName;
}
output.open(FileName);
if (output.fail()) {
output.close();
cout << "Error! Couldn't Open the File. Please Try Again" << endl;
return FileName;
}
cout << endl << "Outputing the Values to the file ..." << endl;
output << "Word,Frequancy";
for (int i = 0; i < 26; i++) //Save
Tree[i].Traverse(output); //Traverse to a file
cout << "Done!" << endl;
output.close();
return FileName;
}
//Searches and Retrives the frequancy of a given word
void SearchAndRetrive(BinaryTree<string, int> Tree[]) {
string word, dummy;
cout << endl << "Please Enter a Word to Search" << endl;
cin >> word; //Takes the word
getline(cin, dummy); //Dummy to get rid of the (cin) leftovers
int Freq = Tree[int(toupper(word[0])) % 25].Retrive(UpperCase(word)); //Retrives the word
if (Freq != NULL) //If you found it output the word and its frequancy
cout << endl << "The Frequancy for the word " << word << " is " << Freq << endl;
else
cout << "Could not find the word" << endl; //word does not exist
}
//Searches for Words >= a certain Frequancy
void GetWordsofFreq(BinaryTree<string, int>Tree[]) {
int freq = 0; string dummy;
cout << endl << "Please Enter a Frequancy" << endl;
cin >> freq; //Takes in the frequancy
getline(cin, dummy); //Dummy to get rid of the (cin) leftovers
if (cin.fail()) { //Check if the input does not suite the type int
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
freq = 0;
}
if (freq <= 0) { //if the inputed frequancy is less than or equal to 0 then no words exist
cout << "Can't find words with frequancy <= 0" << endl;
return;
}
cout << endl;
for (int i = 0; i < 26; i++) //Find and Output words under a certain frequancy in each alphabet
Tree[i].ReverseRetrive(freq);
} | true |
f8a318acd71d63726e36abc4172719b1fb67cda7 | C++ | helloworldzlg/cplusplus_learning | /测试C++ const对象.cpp | UTF-8 | 882 | 3.6875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class book
{
public:
book(){}
book(book &b);
book(char* a, double p = 5.0);
void setprice(double a);
double getprice()const;
void settitle(char* a);
char * gettitle()const;
void display()const;
private:
double price;
char * title;
};
book::book(book &b)
{
price = b.price;
title = b.title;
}
book::book(char* a, double p)
{
title = a;
price = p;
}
void book::display()const
{
cout<<"The price of "<<title<<" is $"<<price<<endl;
}
void book::setprice(double a)
{
price = a;
}
double book::getprice()const
{
return price;
}
void book::settitle(char* a)
{
title = a;
}
char * book::gettitle()const
{
return title;
}
int main()
{
const book Alice("Alice in Wonderland",29.9);
Alice.display();
//Alice.setprice(51.0);//compile error
return 0;
}
| true |
0a38a2c0b39a47963e70f172c31909328f331e57 | C++ | pacopedraza/cpp_study | /operations/sum_n_numbers.cpp | UTF-8 | 897 | 3.9375 | 4 | [] | no_license | /*
* This program should be able to perform the addition between "n" numbers
* Input: The quantity of numbers that the operation will perform.
* Output: The addition of the first "n" numbers
* Process: First we should know the quantity of the numbers to make addition, then
* we read inside the cycle each number and perform the addition
* */
#include<iostream>
#include<cstdlib>
int main()
{
short cont = 1, n;
float num, addition = 0; // the numbers can have point or not.
std::cout<<"\n\tENTER THE QUANTITY OF THE NUMBERS TO MAKE ADDITION: ";
std::cin>>n;
while( cont <= n )
{
system("cls || clear");
std::cout<<"\n\tENTER THE NUMBER: "<<cont<<':';
std::cin>>num;
addition += num;
cont++;
}
system("cls || clear");
std::cout<<"THE ADDITION OF: "<<n<<" NUMBERS IS: "<<addition<<"\n";
std::cout<<"\n\t";
std::cin.ignore().get();
}
| true |
a6d833b3d1de2359343c619e87feb613c80e48ec | C++ | BoHauHuang/Leetcode | /medium/120. Triangle/Triangle.cpp | UTF-8 | 867 | 2.515625 | 3 | [] | no_license | class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
int m = triangle[n-1].size();
int dp[n][m], ans = INT_MAX;
memset(dp, 0, sizeof(dp));
for(int i = 0 ; i < n ; i++){
m = triangle[i].size();
for(int j = 0 ; j < m ; j++){
if(i == 0) dp[i][j] = triangle[i][j];
else{
if(j > 0){
if(j != m-1) dp[i][j] = triangle[i][j] + min(dp[i-1][j], dp[i-1][j-1]);
else dp[i][j] = triangle[i][j] + dp[i-1][j-1];
}
else dp[i][j] = triangle[i][j] + dp[i-1][j];
}
}
}
for(int i = 0 ; i < m ; i++){
ans = min(dp[n-1][i], ans);
}
return ans;
}
};
| true |
217dfa49cb0ed7d3eb88f186c3fb8c90a22080f1 | C++ | KoplanyiDavid/Prog2 | /project/enemies.h | UTF-8 | 674 | 2.875 | 3 | [] | no_license | #pragma once
#include "weapons.h"
#include "player.h"
using namespace std;
class enemy {
protected:
string name;
int life;
unsigned dmg;
public:
enemy(string n, int l, unsigned d);
virtual void attack(player&) = 0;
const string getname() const;
int getlife() const;
void setlife(int const el);
unsigned getdamage() const;
};
class zombie :public enemy {
int zlife;
public:
zombie(string n, int l, unsigned d, int zl);
void attack(player& p);
int getzlife() const;
};
class human :public enemy {
weapon& hw;
public:
human(string n, int l, unsigned d, weapon& w);
void attack(player& p);
weapon& gethwpn() const;
};
| true |
cd994c45ebce602a31c2856857a287b8ac2d7e8d | C++ | timmyzeng/CandCpp | /Practice/delete_print_list.cpp | UTF-8 | 2,917 | 3.390625 | 3 | [] | no_license | /*************************************************************************
> File Name: delete_print_list.1.19.cpp
> Author: Timmy
> Created Time: Tue 30 Jan 2018 08:00:49 PM CST
************************************************************************/
#include <iostream>
#include <assert.h>
using namespace std;
//struct node{
//node( int n ){
//val = n;
//next = NULL;
//}
//int val;
//node* next;
//};
////1.删除一个无头节点单链表的非尾节点。
//void delete_list( node* pos ){
//assert(pos->next);
//node* tmp = pos->next;
//pos->next = pos->next->next;
//swap(tmp->val, pos->val);
//delete tmp;
//}
////从尾到头打印单链表。
//void print_reverse( node* head ){
//if( head == NULL )
//return;
//print_reverse( head->next );
//cout << head->val << " ";
//}
//void print( node* root ){
//while( root ){
//cout << root->val << "->";
//root = root->next;
//}
//cout << "NULL" << endl;
//}
//2.复杂单链表的复制,random指向任意一个节点或null,返回复制后的新链表。
#define datatype int
typedef struct complexnode{
complexnode(datatype val){
_data = val;
_next = NULL;
_random = NULL;
}
datatype _data;
complexnode* _next;
complexnode* _random;
}comnode;
comnode* copy_complex_list( comnode* head ){
comnode* cur = head;
comnode* next = cur->_next;
if( cur == NULL )
return NULL;
//将每一个节点复制到当前节点的后面,并链入链表
while( cur ){
comnode* tmp = new comnode(cur->_data);
cur->_next = tmp;
tmp->_next = next;
cur = next;
if( cur )
next = cur->_next;
}
cur = head;
next = cur->_next;
//给新链入的节点置random
while( cur ){
if( cur->_random )
next->_random = cur->_random->_next;
else
next->_random = NULL;
cur = next->_next;
if( cur )
next = cur->_next;
}
cur = head;
next = cur->_next;
comnode* result = next;
while( cur ){
cur->_next = next->_next;
cur = cur->_next;
if( cur ){
next->_next = cur->_next;
next = next->_next;
}
}
return result;
}
void print_random( comnode* head ){
comnode* cur = head;
cout << "list:";
while( cur ){
cout << cur->_data << "->";
cur = cur->_next;
}
cout << "NULL" << endl << "random:";
cur = head;
while( cur ){
if( cur->_random )
cout << cur->_random->_data << " ";
else
cout << "NULL" << " ";
cur = cur->_next;
}
cout << endl;
}
int main(){
comnode* head = new comnode(1);
comnode* n1 = new comnode(2);
comnode* n2 = new comnode(4);
comnode* n3 = new comnode(5);
comnode* n4 = new comnode(9);
head->_next = n1;
n1->_next = n2;
n2->_next = n3;
n3->_next = n4;
n4->_next = NULL;
head->_random = n2;
n1->_random = head;
n2->_random = n3;
n3->_random = NULL;
n4->_random = n4;
system( "clear" );
comnode* copy_list = copy_complex_list( head );
print_random(head);
cout << "copy_list:" << endl;
print_random(copy_list);
return 0;
}
| true |
d4ae0515438a8618d0f4b628dbab93203c7684b5 | C++ | toshirokubota/straight-polygon-grouping | /src/szlocalextrema.cpp | UTF-8 | 2,830 | 2.65625 | 3 | [] | no_license | #include <szParticle.h>
/*
*/
template<class Item>
void
LocalMaximum(vector<unsigned char>& M,
const vector<Item>& V,
const vector<unsigned char>& L, //ROI mask
const vector<int>& nbh,
bool strict,
int ndim,
const int* dims)
{
int nvoxels = numberOfElements(ndim,dims);
if(M.size()<nvoxels || V.size()<nvoxels || L.size()<nvoxels)
{
//mexPrintf("An input image does not contain enough data.\n");
return;
}
int i;
//construct a subscript representation of the neighborhood
//for efficient boundary check
vector<int> vcoords;
for(i=0; i<nbh.size(); ++i)
{
vector<int> vsub = Ind2SubCentered(nbh[i],ndim,dims);
vcoords.insert(vcoords.end(),vsub.begin(),vsub.end());
}
for(i=0; i<nvoxels; ++i)
{
unsigned char lb=L[i];
if(!lb)
{
SetData(M,i,(unsigned char) 0);
continue; //not inside ROI
}
bool bLM=true;
Item origV=V[i];
vector<int> vsub = Ind2Sub(i,ndim,dims);
for(int j=0; j<nbh.size(); ++j)
{
if(NeighborCheck(vsub.begin(),vcoords.begin()+j*ndim,ndim,dims))
{
int k=i+nbh[j];
if(L[k])
{
Item v2=V[k];
if(strict)
{// strictly maximum
if(v2>=origV)
{
bLM=false;
break;
}
}
else
{
if(v2>origV)
{
bLM=false;
break;
}
}
}
}
}
if(bLM)
{
SetData(M,i,(unsigned char) 1);
}
else
{
SetData(M,i,(unsigned char) 0);
}
}
}
/*
*/
template<class Item>
void
LocalMinimum(vector<unsigned char>& M,
const vector<Item>& V,
const vector<unsigned char>& L,
const vector<int>& nbh,
bool strict,
int ndim,
const int* dims)
{
int nvoxels = numberOfElements(ndim,dims);
if(M.size()<nvoxels || V.size()<nvoxels || L.size()<nvoxels)
{
//mexPrintf("An input image does not contain enough data.\n");
return;
}
int i;
//construct a subscript representation of the neighborhood
//for efficient boundary check
vector<int> vcoords;
for(i=0; i<nbh.size(); ++i)
{
vector<int> vsub = Ind2SubCentered(nbh[i],ndim,dims);
vcoords.insert(vcoords.end(),vsub.begin(),vsub.end());
}
for(i=0; i<nvoxels; ++i)
{
unsigned char lb=L[i];
if(!lb)
continue; //not inside ROI
bool bLM=true;
bool b0;
Item origV=V[i];
vector<int> vsub = Ind2Sub(i,ndim,dims);
for(int j=0; j<nbh.size(); ++j)
{
if(NeighborCheck(vsub.begin(),vcoords.begin()+j*ndim,ndim,dims))
{
int k=i+nbh[j];
if(L[k])
{
bool b;
Item v2=V[k];
if(strict) {// strictly maximum
if(v2<=origV)
{
bLM=false;
break;
}
}
else
{
if(v2<origV)
{
bLM=false;
break;
}
}
}
}
}
if(bLM)
{
SetData(M,i,(unsigned char) 1);
}
else
{
SetData(M,i,(unsigned char) 0);
}
}
}
| true |
c5e8505f471c928c764ab23cb123df5f7b9d9292 | C++ | ishaanshah/Competitive-Programming | /INOI/INOI1302.cpp | UTF-8 | 2,083 | 3.046875 | 3 | [] | no_license | /* Created by Ishaan Shah on 14-12-2017.
* Problem Name: INOI1302
* Problem Link: https://www.codechef.com/INOIPRAC/problems/INOI1302
*/
#include <bits/stdc++.h>
using namespace std;
class Graph {
int v;
list<int> *adj;
public:
explicit Graph(int v);
void add_edge(int u, int v);
int DFS(int start);
};
Graph::Graph(int v) {
this->v = v;
adj = new list<int>[v];
}
void Graph::add_edge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
int Graph::DFS(int start) {
bool visited[v];
for(int i = 0; i < v; i++) {
visited[i] = false;
}
int ans = 0;
stack<int> stk;
stk.push(start);
while(!stk.empty()) {
int u = stk.top();
stk.pop();
if(!visited[u]) {
ans++;
visited[u] = true;
}
for(auto &elem: adj[u]) {
if(!visited[elem]) {
stk.push(elem);
}
}
}
return ans;
}
int intersection(set<int> &id_1, set<int> &id_2);
int main() {
int n, k;
vector<set<int> > people;
cin >> n >> k;
for(int i = 0; i < n; i++) {
int a;
cin >> a;
set<int> id;
for(int j = 0; j < a; j++) {
int b;
cin >> b;
id.insert(b);
}
people.push_back(id);
}
Graph relations(n);
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
int temp = intersection(people[i], people[j]);
if(temp >= k) {
relations.add_edge(i, j);
}
}
}
cout << relations.DFS(0);
}
int intersection(set<int> &id_1, set<int> &id_2) {
int i = 0;
int j = 0;
int count = 0;
vector<int> arr_1(id_1.begin(), id_1.end());
vector<int> arr_2(id_2.begin(), id_2.end());
while(i < arr_1.size() && j < arr_2.size()) {
if(arr_1[i] < arr_2[j]) {
i++;
} else if(arr_1[i] > arr_2[j]) {
j++;
} else {
count++;
i++;
j++;
}
}
return count;
} | true |
b335f555423578432bb6406d33c66c67e5ae23d6 | C++ | rusmm85/Numerical-methods | /furie.cpp | UTF-8 | 1,148 | 2.859375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#define N 10
#define Pi 3.1415926535897932384626433832795
using namespace std;
double scalar (double *a, double *b)
{
int i;
double scal=0;
double h=1.0/N;
for(i=1;i<N;i++)
{
scal+=h*a[i]*b[i];
}
return scal;
}
void Phi (double *phi, int n)
{
int i;
double h=1.0/N;
for(i=1;i<N;i++)
{
phi[i]=sqrt(2.0)*sin(Pi*n*i*h);
}
return;
}
double CM (double *F, double *phi, int m)
{
double Cm, lambda, h=1.0/N;
Phi(phi,m);
lambda=(4/(h*h))*sin(Pi*m*h/2)*sin(Pi*m*h/2);
Cm=scalar(F,phi)/lambda;
return Cm;
}
int main()
{
int i, j;
double h=1.0/N, Cm;
double *phi;
double *Y;
double *Y1;
double *F;
phi= new double[N];
Y= new double[N+1];
Y1= new double[N];
F= new double[N];
for(i=1;i<N;i++)
{
Y1[i]=0;
Y[i]=rand()%10;
}
Y[0]=Y[N]=0;
for(i=1;i<N;i++)
{
F[i]=(-Y[i+1]+2*Y[i]-Y[i-1])/(h*h);
}
F[0]=0;
for(i=1;i<N;i++)
{
Cm = CM(F, phi, i);
//Y1[i]=0;
for(j=1;j<N;j++)
{
Y1[j]=Y1[j]+Cm*phi[j];
}
}
for(i=1;i<N;i++)
{
cout<<"i = "<<i<<" Y = "<<Y[i]<<" Y1= "<<Y1[i]<<endl;
}
return 1;
}
| true |
41f1f7631cfbfb9030e34cd6b4fb7622462e34be | C++ | radishkill/HttpProxy | /src/epollrepertory.cc | UTF-8 | 1,071 | 2.546875 | 3 | [] | no_license | //#include "epollrepertory.h"
//EpollRepertory::EpollRepertory()
//{
//// g_epollFd = epoll_create1(MAX_EVENTS);
// g_epollFd = epoll_create1(0);
//}
//void EpollRepertory::eventAdd(FdMsg &fdMsg) {
// //向管理器里面添加数据
// FdMsg *p = this->add(fdMsg);
// struct epoll_event epv = {0, {nullptr}};
// epv.data.ptr = p;
// epv.events = fdMsg.events;
// if (epoll_ctl(g_epollFd, EPOLL_CTL_ADD, fdMsg.fd, &epv) < 0) {
// std::cout << "add error" << std::endl;
// }
//}
//void EpollRepertory::eventDel(FdMsg &fdMsg) {
// this->drop(fdMsg);
// struct epoll_event epv = {0, {0}};
// epoll_ctl(g_epollFd, EPOLL_CTL_DEL, fdMsg.fd, &epv);
//}
//void EpollRepertory::eventDel(int fd) {
// FdMsg fdMsg;
// fdMsg.fd = fd;
// this->drop(fdMsg);
// struct epoll_event epv = {0, {0}};
// epoll_ctl(g_epollFd, EPOLL_CTL_DEL, fdMsg.fd, &epv);
//}
//void EpollRepertory::eventMod(int events, int fd) {
// events = events;
// fd = fd;
//}
//int EpollRepertory::getEpollFd()
//{
// return g_epollFd;
//}
| true |
e972339397a9d8b5fc111785fbc91b11d2c6803a | C++ | shesl-meow/PhysicsAnalysis | /直流双臂电桥/do.cpp | UTF-8 | 485 | 2.875 | 3 | [] | no_license | #include"../method.h"
void S(double *val, double *bia, int len=3){
double *S = new double[len];
double *Sbia = new double[len];
for(int i=0; i<len; i++){
S[i] = pi*val[i]*val[i]/4;
Sbia[i] = pi*val[i]*bia[i]/2;
}
printf("\nThe S of three: ");
for(int i=0; i<len; i++)
printf("\t%f",S[i]);
printf("\nBiase of S: ");
for(int i=0; i<len; i++)
printf("\t%f",Sbia[i]);
delete []S;
delete []Sbia;
}
int main(int argc,char**argv){
method(5,3,argv[1],&S);
return 0;
}
| true |
7be0730c66460a8881ba7227b91be1f8dc288fcf | C++ | nikonikolov/c_compiler | /src/DataStructures/VarExpr.cpp | UTF-8 | 847 | 2.640625 | 3 | [] | no_license | #include "VarExpr.h"
VarExpr::VarExpr(char* name_in) : BaseExpression(EXPR_tmp_var){
name = strdup(name_in);
}
VarExpr::VarExpr(char* name_in, const int& line_in, const string& src_file_in) :
BaseExpression(EXPR_tmp_var, line_in, src_file_in){
name = strdup(name_in);
}
VarExpr::~VarExpr(){}
const char* VarExpr::get_name() const{
return name;
}
void VarExpr::pretty_print(const int& indent){
string white_space;
white_space.resize(indent, ' ');
cout<<white_space<<name;
}
void VarExpr::renderasm(ASMhandle& context, ExprResult** dest /*=NULL*/){
if(dest==NULL) return;
Variable* result;
try{
result = context.get_var_location(name);
}
catch(const int& error){
generate_error("variable \""+string(name)+"\" not defined for the current scope");
}
*dest=result;
}
BaseExpression* VarExpr::simplify(){
throw 1;
}
| true |
8fce08ed7bda2b3d0eeafda3715b9aee5299e39c | C++ | hlatchague1/CSS343 | /Polymorphism/drama.h | UTF-8 | 482 | 2.890625 | 3 | [] | no_license | #pragma once
#include <string>
#include "movie.h"
using namespace std;
class Drama : public Movie {
public:
Drama(int stockAmount, string directorFirstName, string directorLastName,
string movieTitle, int releaseYear);
~Drama();
//sorted by Director, then Title
bool operator==(const Movie &otherMovie) const;
bool operator!=(const Movie &otherMovie) const;
bool operator<(const Movie &otherMovie) const;
bool operator>(const Movie &otherMovie) const;
}; | true |
5546350d85e554c94171e5374d8ffee85805da2c | C++ | aeremin/Codeforces | /alexey/Solvers/6xx/610/Solver610B.cpp | UTF-8 | 1,572 | 2.875 | 3 | [] | no_license | #include <Solvers/pch.h>
#include "algo/io/readvector.h"
#include "util/relax.h"
using namespace std;
// Solution for Codeforces problem http://codeforces.com/contest/610/problem/B
class Solver610B
{
public:
void run();
};
void Solver610B::run()
{
int64_t n;
cin >> n;
auto amounts = readVector<int64_t>(n);
auto minAmount = *min_element(begin(amounts), end(amounts));
int64_t maxAddition = 0;
int64_t addition = 0;
for ( int i = 0; i < 2 * n; ++i )
{
if ( amounts[i % n] > minAmount )
addition++;
else
{
relax_max(maxAddition, addition);
addition = 0;
}
}
relax_max( maxAddition, addition );
cout << n * minAmount + maxAddition;
}
class Solver610BTest : public ProblemTest {};
TEST_F(Solver610BTest, Example1)
{
string input = R"(5
2 4 2 3 3
)";
string output = R"(12
)";
setInput(input);
Solver610B().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver610BTest, Example2)
{
string input = R"(3
5 5 5
)";
string output = R"(15
)";
setInput(input);
Solver610B().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver610BTest, Example3)
{
string input = R"(6
10 10 10 1 10 10
)";
string output = R"(11
)";
setInput(input);
Solver610B().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F( Solver610BTest, Example4 )
{
string input = R"(3
1 2 1
)";
string output = R"(4)";
setInput( input );
Solver610B().run();
EXPECT_EQ( output, getOutput() );
}
| true |
3c2a32a21d1bcd699e0152225b1e2933bcc59d2b | C++ | adityaramesh/ctop | /include/ctop/cpuid.hpp | UTF-8 | 2,289 | 3.015625 | 3 | [] | no_license | /*
** File Name: system.hpp
** Author: Aditya Ramesh
** Date: 07/29/2014
** Contact: _@adityaramesh.com
*/
#ifndef Z008D83F8_D0FA_4815_96DE_FD47C220EB95
#define Z008D83F8_D0FA_4815_96DE_FD47C220EB95
#if PLATFORM_COMPILER == PLATFORM_COMPILER_GCC || \
PLATFORM_COMPILER == PLATFORM_COMPILER_CLANG || \
PLATFORM_COMPILER == PLATFORM_COMPILER_ICC
#include <cpuid.h>
#else
#error "Unsupported compiler."
#endif
#include <cstdint>
#include <tuple>
#include <boost/optional.hpp>
namespace ctop {
/*
** Returns the index corresponding to the largest supported CPUID leaf.
*/
boost::optional<uint32_t>
max_cpuid_leaf()
{
auto r = __get_cpuid_max(0, nullptr);
if (r == 0) {
return boost::none;
}
return r;
}
/*
** Returns a four-tuple containing the contents of EAX, EBX, ECX, and EDX after
** executing the CPUID instruction with the given leaf index.
**
** IMPORTANT NOTE: The use of the "volatile" keyword is **crucial** here,
** because the compiler treats the ASM instrinsic as a constant function, even
** if fences are placed around the calling site. This means that the compiler
** can hoist `cpuid` outside of a loop in which the thread is scheduled to a new
** processor at each iteration.
*/
auto cpuid(uint32_t leaf) ->
std::tuple<uint32_t, uint32_t, uint32_t, uint32_t>
{
uint32_t r1, r2, r3, r4;
asm volatile("cpuid"
: "=a" (r1), "=b" (r2), "=c" (r3), "=d" (r4)
: "a" (leaf)
);
return std::make_tuple(r1, r2, r3, r4);
}
/*
** This function does the same thing as the unary `cpuid` function, but it also
** loads the given value into ECX before executing CPUID. This is useful for the
** CPUID leaves that take two arguments as input.
**
** IMPORTANT NOTE: The use of the "volatile" keyword is **crucial** here,
** because the compiler treats the ASM instrinsic as a constant function, even
** if fences are placed around the calling site. This means that the compiler
** can hoist `cpuid` outside of a loop in which the thread is scheduled to a new
** processor at each iteration.
*/
auto cpuid(uint32_t leaf, uint32_t arg) ->
std::tuple<uint32_t, uint32_t, uint32_t, uint32_t>
{
uint32_t r1, r2, r3, r4;
asm volatile("cpuid"
: "=a" (r1), "=b" (r2), "=c" (r3), "=d" (r4)
: "a" (leaf), "c" (arg)
);
return std::make_tuple(r1, r2, r3, r4);
}
}
#endif
| true |
ec0f29d456f5fb908ba340b44a23cae5ce67c1a2 | C++ | marvinfy/Trainings | /qt/cursoQt/08_loop_paralelizado/writefile.cpp | ISO-8859-1 | 2,542 | 2.6875 | 3 | [] | no_license | #include "writefile.h"
#include <QThread>
#include <QtConcurrentRun>
#include <QDebug>
#include <QCoreApplication>
WriteFile::WriteFile(QObject *parent) :
QObject(parent)
{
}
void WriteFile::generateData(int rowCount)
{
m_rowCount = rowCount;
m_data.resize(rowCount);
qDebug() << rowCount << m_data.size();
for (int n=0; n<rowCount; ++n)
{
// povoar o vetor
QPair<QString , double > pair;
pair.first = QString("%1").arg(n+1);
pair.second = qrand() * 1.33 +1;
m_data[n] = pair;
}
}
bool WriteFile::writeTxt()
{
int cpus = QThread::idealThreadCount();
if ( cpus == 0)
cpus = 1;
int begin = 0;
int count = m_rowCount / cpus;
QVector <QFuture<bool> > futures;
futures.resize(cpus);
m_txtFiles.resize(cpus);
for ( int c=1; c<=cpus; ++c)
{
int end = c==cpus? m_rowCount-1 : begin+count-1 ;
m_txtFiles[c-1] = new QFile("cobranca.txt");
if ( !m_txtFiles[c-1]->open(QIODevice::WriteOnly | QIODevice::Truncate))
{
qDebug() << "falha ao abrir arquivo\n";
return false;
}
futures[c-1]=QtConcurrent::run(
this, &WriteFile::writeLoop, c-1, begin, end);
begin = end + 1;
}
for ( int c=0; c<cpus; ++c)
futures[c].waitForFinished();
for ( int c=0; c<cpus; ++c)
m_txtFiles[c]->close();
qDeleteAll(m_txtFiles);
qDebug() << "threads encerraram\n";
return true;
}
bool WriteFile::writeLoop(int index, int begin, int end)
{
enum { nameLen=40, valueLen = 12, terminatorLen = 2,
recordLen = nameLen+valueLen+terminatorLen};
const char * terminator = "\r\n";
int offset = begin * recordLen;
m_txtFiles[index]->seek(offset);
qDebug() << "thread: " << QThread::currentThreadId() <<
"begin: " << begin << "end: " << end
<< "offset: " << offset;
for ( ; begin <= end; ++begin)
{
m_txtFiles[index]->write(QString("%1").arg(
m_data[begin].first, // string
-nameLen, // tamanho, alinhado esquerda
'*' // preenchedor direita
).toAscii()
);
m_txtFiles[index]->write(QString("%1").arg(
m_data[begin].second, // double
valueLen, // tamanho alinhado direita
'f', // formato: fixed
//(o default 'g' que pode ser notao exponencial)
2, // preciso.
'0' // preenchedor esquerda
).toAscii()
);
m_txtFiles[index]->write(terminator);
}
// emit threadFinished();
return true;
}
| true |
622ebfff8e69c68d05a8cd2b45d2b9eb76b81ad0 | C++ | gmisail/MikroVM | /vm.h | UTF-8 | 2,137 | 3.234375 | 3 | [
"MIT"
] | permissive | #ifndef VM
#define VM
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <stack>
#include "function.h"
#include "opcodes.h"
#include "frame.h"
#include "constants.h"
class Mikro
{
public:
Mikro(const std::vector<int>& program) : ic(0), sp(-1), program(program), running(true)
{
for(int i = 0; i < MIKRO_MEMORY; i++)
{
stack[i] = 0;
globals[i] = 0;
}
frame = new Frame();
}
~Mikro()
{
for(std::map<int, Function*>::iterator itr = functions.begin(); itr != functions.end(); itr++)
{
delete itr->second;
}
delete frame;
}
bool run();
void push(double value)
{
stack[++sp] = value;
}
double pop()
{
if(sp < 0)
{
std::cout << "ERROR! Cannot access value outside of stack memory" << std::endl;
running = false;
}
return stack[sp--];
}
void jump(int address)
{
if(address > 0 && address < program.size()) ic = address;
}
void print()
{
std::cout << "------------------------------------" << std::endl;
std::cout << "Stack Pointer: " << sp << std::endl;
std::cout << "Instruction Pointer: " << ic << std::endl;
std::cout << "Stack: [ ";
for(int i = 0; i < MIKRO_MEMORY; i++)
{
std::cout << stack[i] << " ";
}
std::cout << "]" << std::endl;
std::cout << "------------------------------------" << std::endl;
}
private:
std::vector<int> program;
double stack[MIKRO_MEMORY];
double globals[MIKRO_MEMORY];
std::map<int, Function*> functions;
std::stack<int> call_stack;
Frame* frame;
int ic;
int sp;
bool running;
void eval();
const int current();
bool next();
};
#endif
| true |
34f9187591640005002da20f8918cfa0146d3349 | C++ | danwang112233/result | /10-10-12/fixloop.cpp | UTF-8 | 2,055 | 2.640625 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <math.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main(int argc,char **argv)
{
clock_t t1, t2;
t1 = clock();
if(argc != 3)
{
cout << "Usage: ./fixloop ne_min delta.\n" << "ne_min is the min number(<0) your loop used in infile of lammps\n" << "delta is the number multipled the min and the max number to get the final loop of electric strength." << endl;
}
else
{
int ne_min = atoi(argv[1]);
//int ne_max = atoi(argv[2]);
double delta = atof(argv[2]);
const char *filename = "loop.in";
int ne_max = -(ne_min);
ofstream fout(filename, ios::out|ios::trunc);
for(int i = ne_min; i < ne_max +1; ++i)
{
double exf = double(i) * delta;
double ex = exf / sqrt(3.0);
double ey = exf / sqrt(3.0);
double ez = exf / sqrt(3.0);
fout << "reset_timestep 0" << endl;
fout << "fix ef all efield " << ex << " " << ey << " " << ez << endl;
fout << "print \" electric field strength = " << exf << " .\"" << endl;
fout << "fix_modify ef energy yes " << endl;
fout << "min_style fire" << endl;
fout << "minimize 0.0 1e-07 30000 100000" << endl;
fout << "min_style quickmin" << endl;
fout << "minimize 0.0 1e-07 30000 100000" << endl;
fout << "unfix ef" << endl;
}
for(int i = ne_max - 1; i > ne_min -1; --i)
{
double exf = double(i) * delta;
double ex = exf / sqrt(3.0);
double ey = exf / sqrt(3.0);
double ez = exf / sqrt(3.0);
fout << "reset_timestep 0" << endl;
fout << "fix ef all efield " << ex << " " << ey << " " << ez << endl;
fout << "print \" electric field strength = " << exf << " .\"" << endl;
fout << "fix_modify ef energy yes " << endl;
fout << "min_style fire" << endl;
fout << "minimize 0.0 1e-07 30000 100000" << endl;
fout << "min_style quickmin" << endl;
fout << "minimize 0.0 1e-07 30000 100000" << endl;
fout << "unfix ef" << endl;
}
fout.close();
return 0;
}
}
| true |
006a4ff000c6d98a6fb12cd0e3023fd52cf90889 | C++ | CharacteristicPolynomial/EECS591ChatService | /replicaTools.h | UTF-8 | 9,219 | 2.75 | 3 | [] | no_license | #pragma once
#include "message.h"
#include "phone.h"
#include "replica.h"
#include <unordered_map>
#include <unordered_set>
using namespace std;
class RequestList {
// organize list of requests
public:
void print() {
// print log contents to cout
cout << endl << "Learn Log Updated" << endl;
int k = 0;
for(auto entry : slots) {
cout << "Slot " << k++ << " : ";
if (entry.second == true) {
Request r = entry.first;
cout << "Request(view=" << r.view
<< ", pos="<< r.position
<< ", seq="<< r.seq
<< ", clientIP="<< getIP(r.clientAddr)
<< ", clientPort="<< getPort(r.clientAddr)
<< ", content=";
cout.write(r.text, r.textLen);
cout << ")" << endl;
} else {
cout << "(Empty slot)" << endl;
}
}
}
void save(string filename) {
// save format:
// slot number
ofstream ofs;
ofs.open(filename, ios_base::out | ios_base::trunc);
int k =0;
for(auto entry : slots) {
if (entry.second == true) {
ofs << "Slot " << k << ": ";
Request r = entry.first;
ofs << "Client IP(" << getIP(r.clientAddr) << ") Port("
<< getPort(r.clientAddr) << ") seq("
<< r.seq << ") text(";
ofs.write(r.text, r.textLen);
ofs << ")";
ofs << endl;
} else {
ofs << "(Empty slot)" << endl;
}
k++;
}
ofs.close();
}
void saveAccept(string filename) {
// save format:
// slot number
ofstream ofs;
ofs.open(filename, ios_base::out | ios_base::trunc);
int k =0;
for(auto entry : slots) {
if (entry.second == true) {
ofs << "Slot " << k << ": ";
Request r = entry.first;
ofs << "view(" << r.view << ") "
<< "Client IP(" << getIP(r.clientAddr) << ") Port("
<< getPort(r.clientAddr) << ") seq("
<< r.seq << ") text(";
ofs.write(r.text, r.textLen);
ofs << ")";
ofs << endl;
} else {
ofs << "(Empty slot)" << endl;
}
k++;
}
ofs.close();
}
void add(const Request r) { // store r here
// replace previous request
int pos = r.position;
if(pos >= (int)slots.size()) {
slots.resize(pos+1);
}
if(slots[pos].second) {
// free previous request
slots[pos].first.freeText();
slots[pos].first = r;
} else {
slots[pos].first = r;
slots[pos].second = true;
length ++;
}
}
void update(Request r) { // copy r here
// update the request if incoming has higher view number
int pos = r.position;
if(pos >= (int)slots.size()) {
slots.resize(pos+1);
}
if(slots[pos].second) {
if(slots[pos].first.view < r.view) {
slots[pos].first.freeText();
slots[pos].first = r.make_copy();
}
} else {
slots[pos].first = r.make_copy();;
slots[pos].second = true;
length ++;
}
}
void setView(int view) {
for(auto& entry : slots) {
if(entry.second) {
entry.first.view = view;
}
}
}
vector<pair<Request, bool>> slots; // (request, occupiedQ)
int length=0;
};
class LearnerSlot {
unordered_map<int, pair<Request, unordered_set<int>>> history;
// format: view_number->(request, (list of replicas))
public:
// ~LearnerSlot() {
// for(auto hentry : history) {
// hentry.second.first.freeText();
// }
// }
int add(Request r, int ri) {
// return the size of accepted of this request
Request& myr = history[r.view].first;
unordered_set<int>& myset = history[r.view].second;
if(myset.size() == 0) {
// the first message of this view
myr = r;
} else {
// error detection, request of the same view should be the same
// if(!(myr == r)) {
// cerr << "Error: inconsistent request of a same view at a same slot" << endl;
// exit(-1);
// }
// free the myr to save space
myr.freeText();
myr = r;
}
myset.insert(ri);
return myset.size();
}
};
class Learner {
// data structure for learn a value
public:
Phone* phone;
RequestList learnLog;
int en=0;
int execN() {
int k =0;
for(auto entry : learnLog.slots) {
if(entry.second == false)
return k-1;
k++;
}
return k-1;
}
void updateExecN(int id) {
int temp = en;
en = execN();
if (en > temp) {
cout << " leader " << id << " chat log executable up to slot " << en << endl;
}
}
void init(Phone* p, int id) {
phone = p;
chatLogFile = get_config(CHATLOG_PREFIX) + to_string(id) + get_config(CHATLOG_SUFFIX);
}
bool filledQ(int k) {
// return true if slot k is learned
if ((int) learnLog.slots.size() <= k)
return false;
return learnLog.slots[k].second;
}
bool response(Request r) {
// return false if it is not executable
// return true if it is executable
for(auto entry : learnLog.slots) {
if(entry.second == false)
return false;
if(entry.first.contentMatch(r))
return true;
}
return false;
}
void accepted() {
// format: request, replicaID
Request r = phone->read_request();
int ri = phone->read_int();
if( lss[r.position].add(r, ri) > phone->get_f() ) {
// the request r is learned
learnLog.add(r.make_copy());
// log it
phone->write_learnLog(r);
// learnLog.print();
learnLog.save(chatLogFile);
}
}
string chatLogFile;
unordered_map<int, LearnerSlot> lss;
//format: position -> learnerslot
};
class TempLog {
public:
void freeTempLog() {
for(auto logEntry : logset) {
logEntry.second.freeText();
}
}
unordered_map<int, Request> logset; // (position, request)
int total;
int append(Request r) {
// append one log entry
// and return the number of entries received
if(logset.find(r.position) == logset.end()) {
logset[r.position] = r;
} else {
r.freeText();
}
return logset.size();
}
};
class ViewChange {
public:
Phone* phone;
void init(Phone* p) {
phone = p;
viewchange_view = 0;
}
void printProgress() {
cout << "partially received promises: " << endl;
for (auto entry : viewchange_data) {
int k = entry.first;
if(completeList.find(k) == completeList.end()) {
cout << "replica " << k << " : received "
<< entry.second.logset.size() << " out of "
<< entry.second.total << endl;
}
}
cout << completeList.size() << " promises completed: ";
for(auto k : completeList) {
cout << k << " ";
}
cout << endl << "total packets received: ";
int sum = 0;
for(auto entry : viewchange_data) {
sum += entry.second.logset.size();
}
cout << sum << endl;
}
void start(int view) {
viewchange_view = view;
// clear data
for(auto entry : viewchange_data) {
entry.second.freeTempLog();
}
viewchange_data.clear();
completeList.clear();
}
unordered_map<int, TempLog> viewchange_data; // (id, packets)
unordered_set<int> completeList; // (id)
int viewchange_view;
int add_data() {
// format: view_number, replicaID, totalLogLen, request
// return the number of completed replicas
int hisview = phone->read_int();
if(viewchange_view > hisview) {
return completeList.size();
}
// proceed only when tempview >= view
int replicaID = phone->read_int();
int totalLogLen = phone->read_int();
if(totalLogLen == 0) {
completeList.insert(replicaID);
} else {
Request r = phone->read_request();
TempLog& mylog = viewchange_data[replicaID]; // a new templog will be created if needed
mylog.total = totalLogLen;
if(mylog.append(r) == totalLogLen) {
completeList.insert(replicaID);
}
}
return completeList.size();
}
}; | true |
bd90659fe7cfc2abe09155d61a5168b0daaf916e | C++ | NateRiz/OpenGLRendering_2 | /Engine/Headers/world.h | UTF-8 | 2,068 | 3.140625 | 3 | [] | no_license | #ifndef WORLD_H
#define WORLD_H
#include <vector>
class Actor;
class GLFWwindow;
class Renderer;
class Mesh;
class Camera;
class Sun;
class World
{
public:
virtual ~World();
void Update();
void SetWindow(GLFWwindow*);
GLFWwindow* GetWindow() const;
/**
* Gets the time since GLFW initialized.
* @return Time in seconds
*/
double GetTime() const;
/**
* Adds an Actor object to Vector of Actors, mActors.
*/
void AddActor(Actor*);
/**
* Sends a mesh to the Renderer class' mesh vector.
*/
void AddMesh(Mesh*);
/**
* Adds an actor to the list of actors to be notified for events.
*/
void AddInputListener(Actor*);
/**
* Sets the passed in Camera to the active camera.
* @param camera Camera to set as active camera.
*/
void SetActiveCamera(Camera* camera);
Camera* GetActiveCamera() const;
Mesh* GetSun() const;
/**
* Sends RELATIVE mouse events to all actors that are input listeners
* @param x Current x mouse Position
* @param y Current y mouse Position
*/
void MouseCallback(GLFWwindow*, double x, double y);
/**
* This callback calls the implemented MouseCallback().
*/
static void MouseCallbackWrapper(GLFWwindow*, double x, double y);
static World& GetInstance();
private:
World();
std::vector<Actor*>mActors; /**< All actors in the scene. Automatically added in Actor constuctor.*/
std::vector<Actor*>mInputListeners;/**< All actors that need to be notified of input events.*/
Camera* mActiveCamera;/**< Must be one active camera at a time.*/
Renderer* mRenderer;/**< Handles draw calls of all mesh objects.*/
Sun* mSun;
GLFWwindow* mWindow;
float mWorldTime;/**< Time since GLFW initialized.*/
float mDeltaTime;/**< Time since last Tick() call.*/
float mLastTime;
double mMouseLastX = 0;/**< Used to calculate relative mouse X position*/
double mMouseLastY = 0;/**< Used to calculate relative mouse Y position*/
};
#endif // WORLD_H
| true |
a98c9eee523028df7640d5d6c8969863f7594981 | C++ | dangokyo/leetcode_cpp | /004-MedianOfTwoSortedArray.cpp | UTF-8 | 3,725 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int l1 = nums1.size();
int l2 = nums2.size();
int k = (l1+l2)/2;
double ans;
if(l1 == 0 && l2 >0)
{
if(l2%2 == 1) return nums2[l2/2];
else return (nums2[l2/2-1] + nums2[l2/2])/2.0;
}
else if(l1 > 0 && l2 == 0)
{
if(l1%2 == 1) return nums1[l1/2];
else return (nums1[l1/2-1] + nums1[l1/2])/2.0;
}
else if((l1 + l2)%2 == 0)
{
ans =(SortedArraySolver(0, l1-1, 0, l2-1, nums1, nums2, k-1) + SortedArraySolver(0, l1-1, 0, l2-1, nums1, nums2, k))/2.0;
}
else
{
ans = SortedArraySolver(0, l1-1, 0, l2-1, nums1, nums2, k);
}
return ans;
}
int SortedArraySolver(int left1, int right1, int left2, int right2, vector<int>& nums1, vector<int>& nums2, int k)
{
int middle1 = (left1 + right1)/2;
int middle2 = (left2 + right2)/2;
double ans;
int t;
//cout<<left1<<" "<<right1<<endl<<left2<<" "<<right2<<endl<<k<<endl<<endl;
//return 0;
if(k == 0) return min(nums1[left1], nums2[left2]);
if(left1 == right1 && left2 < right2)
{
t = nums2[left2 + k];
if(t < nums1[left1]) return t;
else return max(nums1[left1], nums2[left2+k-1]);
}
else if(left1 < right1 && left2 == right2)
{
t = nums1[left1 + k];
if(t < nums2[left2]) return t;
else return max(nums2[left2], nums1[left1+k-1]);
}
else if(left1 == right1 && left2 == right2)
{
if(k>=1) return max(nums1[left1], nums2[left2]);
else return min(nums1[left1], nums2[left2]);
}
//cout<<"length:"<<middle1 - left1 + 1 + middle2 - left2 + 1<<endl;
if(middle1 - left1 + 1 + middle2 - left2 + 1 >= k + 1)
{
//cout<<"drop right"<<endl;
if(nums1[middle1] >= nums2[middle2])
{
ans = SortedArraySolver(left1, middle1, left2, right2, nums1, nums2, k);
}
else
{
ans = SortedArraySolver(left1, right1, left2, middle2, nums1, nums2, k);
}
}
else //if(middle1 -left1 + 1 + middle2 < k)
{
if(nums1[middle1] <= nums2[middle2])
{
ans = SortedArraySolver(middle1+1, right1, left2, right2, nums1, nums2, (k -(middle1 - left1 + 1)));
}
else
{
ans = SortedArraySolver(left1, right1, middle2+1, right2, nums1, nums2, (k-(middle2- left2+1)));
}
}
return ans;
}
};
int main()
{
vector<int> in1;
vector<int> in2;
in1.push_back(1);
//in1.push_back(1);
//in1.push_back(5);
//in1.push_back(5);
in2.push_back(2);
in2.push_back(3);
in2.push_back(4);
Solution *slt = new Solution();
cout<<slt->findMedianSortedArrays(in1, in2)<<endl;
getchar();
return 0;
}
| true |
ffd28e1afbbaff7e786961c1afb5c820e350776a | C++ | likstepan/source | /mediatek/source/frameworks/libs/a3m/engine/facility/api/a3m/vertexarray.h | UTF-8 | 6,281 | 2.875 | 3 | [] | no_license | /*****************************************************************************
*
* Copyright (c) 2010 MediaTek Inc. All Rights Reserved.
* --------------------
* This software is protected by copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc.
*
*****************************************************************************/
/** \file
* VertexArray class
*
*/
#pragma once
#ifndef A3M_VERTEXARRAY_H
#define A3M_VERTEXARRAY_H
/*****************************************************************************
* Include Files
*****************************************************************************/
#include <a3m/base_types.h> /* for A3M_INT32 */
#include <a3m/assert.h> /* for A3M_ASSERT */
#include <stdlib.h> /* for malloc */
#include <string.h> /* for memcpy */
#include <a3m/pointer.h> /* for SharedPtr */
namespace a3m
{
/** \defgroup a3mVertexarray Vertex Array
* \ingroup a3mRefScene
*
* VertexArray objects contain data for one attribute of a vertex. They
* should be created dynamically and have their lifetime managed using
* VertexArray::Ptr. Add several VertexArray objects to a VertexBuffer
* object for each attribute of the vertex (position, normal etc.)
*
* Example:
* \code
* A3M_FLOAT positions[] = { -0.5f,-0.5f,0, 0.5f,-0.5f,0,
0.5f,0.5f,0, -0.5f,0.5f,0 };
* A3M_UINT8 colours[] = { 255,0,0, 0,255,0, 0,0,255, 255,255,255 };
*
* a3m::VertexArray::Ptr v_pos( new a3m::VertexArray( 4, 3, positions ) );
* a3m::VertexArray::Ptr v_col( new a3m::VertexArray( 4, 3, colours ) );
* a3m::VertexBuffer::Ptr vb( new a3m::VertexBuffer );
*
* vb->addAttrib( v_pos, "a_position" );
* vb->addAttrib( v_col, "a_colour", a3m::VertexBuffer::ATTRIB_FORMAT_UCHAR,
* a3m::VertexBuffer::ATTRIB_USAGE_WRITE_MANY, true );
* \endcode
* @{
*/
/** Vertex array class.
* Holds a chunk of memory containing per-vertex data for an attribute
* (position, normal, colour etc.)
*/
class VertexArray : public Shared, NonCopyable
{
public:
A3M_NAME_SHARED_CLASS( VertexArray )
/** Smart pointer type */
typedef a3m::SharedPtr< VertexArray > Ptr;
/** Templated constructor. Reserves space for the array and optionally
* initialises with supplied data.
*/
template< typename T >
VertexArray( A3M_INT32 vertexCount,
/**< [in] number of vertices */
A3M_INT32 componentCount,
/**< [in] number of components per vertex */
T const *dataInit = 0,
/**< [in] pointer to data to copy */
A3M_BOOL externalManaged = A3M_FALSE
/**< [in] allow the data to be managed externally */
);
/** Destructor.
* Frees the vertex array's data.
*/
~VertexArray();
/** Access to the vertex array's data.
* \return writable pointer to the vertex array's data
*/
template< typename T >
T *data();
/** Const access to the vertex array's data.
* \return non-writable pointer to the vertex array's data
*/
template< typename T >
T const *data() const;
/** Const access to the vertex array's data as void *.
* \return non-writable pointer to the vertex array's data
*/
void const *voidData() const;
/** Vertex count.
* \returns the number of vertices contained in array.
*/
A3M_INT32 vertexCount() const {return m_vertexCount;}
/** Component count.
* \returns the number of components per vertex.
*/
A3M_INT32 componentCount() const {return m_componentCount;}
/** Type size.
* \returns the size in bytes of the type contained in this vertex array.
*/
A3M_INT32 typeSize() const {return m_typeSize;}
/** Array size.
* \returns the total size in bytes of this vertex array.
*/
A3M_INT32 arraySizeInBytes() const {return m_arraySizeInBytes;}
private:
A3M_INT32 m_vertexCount; /**< number of vertices */
A3M_INT32 m_typeSize; /**< size of type (float, char etc.) used for
each component */
A3M_INT32 m_componentCount; /**< number of components per vertex */
A3M_INT32 m_arraySizeInBytes; /**< size of array in bytes */
void *m_data; /**< pointer to data held in this array */
A3M_BOOL m_externalManaged;
};
/****************************************************************************
* Implementation
****************************************************************************/
/*
* Constructor
*/
template< typename T >
inline VertexArray::VertexArray( A3M_INT32 vertexCount,
A3M_INT32 componentCount,
T const *dataInit,
A3M_BOOL externalManaged )
: m_vertexCount( vertexCount ),
m_typeSize( sizeof( T ) ),
m_componentCount( componentCount ),
m_arraySizeInBytes( vertexCount * componentCount * sizeof( T ) ),
m_externalManaged ( externalManaged )
{
if ( externalManaged )
{
m_data = (void*) dataInit;
}
else
{
m_data = malloc( m_arraySizeInBytes );
if( m_data && dataInit )
{
memcpy( m_data, dataInit, m_arraySizeInBytes );
}
}
}
/*
* Destructor
*/
inline VertexArray::~VertexArray()
{
if ( !m_externalManaged )
{
if( m_data ) { free( m_data ); }
}
}
/*
* Data access as type
*/
template< typename T >
inline T *VertexArray::data()
{
A3M_ASSERT( sizeof( T ) == m_typeSize );
return (T *)m_data;
}
/*
* Constant data access as type
*/
template< typename T >
inline T const *VertexArray::data() const
{
A3M_ASSERT( sizeof( T ) == m_typeSize );
return (T *)m_data;
}
/*
* Generic data access
*/
inline void const *VertexArray::voidData() const
{
return m_data;
}
/** @} */
} /* namespace a3m */
#endif /* A3M_VERTEXARRAY_H */
| true |
3214d0a4f72f1010d84d724d27e773f84f6dd1d6 | C++ | todace/G-CVSNT | /cvsnt/tortoiseCVS/TortoiseCVS/src/Utils/LineReader.h | UTF-8 | 6,849 | 2.625 | 3 | [] | no_license | // TortoiseCVS - a Windows shell extension for easy version control
// Copyright (C) 2003 - Hartmut Honisch
// <Hartmut_Honisch@web.de> - March 2003
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef _LINEREADER_H
#define _LINEREADER_H
#include <iostream>
#include "TortoiseDebug.h"
template <class T> class LineReader
{
public:
typedef typename T::value_type value_type;
typedef typename T::size_type size_type;
enum CrlfStyle
{
CrlfStyleAutomatic = -1,
CrlfStyleDos = 0,
CrlfStyleUnix = 1,
CrlfStyleMac = 2
};
// Constructor
LineReader(std::istream *in, CrlfStyle crlfStyle = CrlfStyleAutomatic);
// Destructor
virtual ~LineReader();
// Guess CRLF style
void GuessCrlfStyle();
// Read a line
bool ReadLine(T &sLine);
// Set crlf style
void SetCrlfStyle(CrlfStyle crlfStyle);
// Get crlf style
CrlfStyle GetCrlfStyle();
// Converter
std::istream *m_in;
protected:
// Find buffer content
const value_type *MemFind(const value_type *buf, size_type count,
const value_type *findbuf, size_type findcount);
// Buffer size
static const size_type m_bufferSize;
// Buffer
value_type *m_buffer;
// Current length
size_type m_bufferLength;
// Buffer pointer
size_type m_bufferPtr;
// EOF
bool m_eof;
// CRLF-Style
CrlfStyle m_crlfStyle;
// CRLF according to style
const value_type *m_crlf;
// CRLF length
size_type m_crlfLength;
private:
};
template <class T> const typename LineReader<T>::size_type LineReader<T>::m_bufferSize = 32768;
// Constructor
template <class T> LineReader<T>::LineReader(std::istream *in, CrlfStyle crlfStyle)
{
m_in = in;
if (crlfStyle != CrlfStyleAutomatic)
{
SetCrlfStyle(crlfStyle);
}
else
{
m_crlfStyle = CrlfStyleAutomatic;
m_crlf = 0;
m_crlfLength = 0;
}
m_buffer = 0;
m_bufferLength = 0;
m_bufferPtr = 0;
m_eof = false;
}
// Destructor
template <class T> LineReader<T>::~LineReader()
{
if (m_buffer)
{
delete m_buffer;
}
}
// Guess CRLF style
template <class T> void LineReader<T>::GuessCrlfStyle()
{
if (m_buffer == 0)
{
m_buffer = new value_type[m_bufferSize];
}
m_in->read((char*) m_buffer, m_bufferSize * sizeof(value_type));
m_bufferLength = m_in->gcount() / sizeof(value_type);
if (m_crlfStyle == CrlfStyleAutomatic)
{
// Try to determine current CRLF mode
size_type I;
for (I = 0; I < m_bufferSize - 1; I++)
{
if ((m_buffer[I] == L'\x0d') || (m_buffer[I] == L'\x0a'))
break;
}
if (I == m_bufferSize - 1)
{
// By default (or in the case of empty file), set DOS style
m_crlfStyle = CrlfStyleDos;
}
else
{
// Otherwise, analyse the first occurance of line-feed character
if (m_buffer[I] == L'\x0a')
{
m_crlfStyle = CrlfStyleUnix;
}
else
{
if (I < m_bufferSize - 1 && m_buffer[I + 1] == L'\x0a')
m_crlfStyle = CrlfStyleDos;
else
m_crlfStyle = CrlfStyleMac;
}
}
}
SetCrlfStyle(m_crlfStyle);
}
// Read a line
template <class T> bool LineReader<T>::ReadLine(T &sLine)
{
const int capacityMul = 2;
const int capacityDiv = 1;
const size_type minCapacity = 2048;
size_type currentCapacity;
size_type newCapacity;
size_type dwCharsLeft;
const value_type *pw;
sLine.erase();
if (m_eof)
{
return false;
}
if (m_buffer == 0)
{
m_buffer = new value_type[m_bufferSize];
}
if (m_crlfStyle == CrlfStyleAutomatic)
{
GuessCrlfStyle();
}
// Set min capacity
currentCapacity = sLine.capacity();
if (currentCapacity < minCapacity)
{
sLine.reserve(minCapacity);
currentCapacity = minCapacity;
}
while (true)
{
// load next chunk of characters if buffer is empty
dwCharsLeft = m_bufferLength - m_bufferPtr;
if ((dwCharsLeft < m_crlfLength) && !m_eof)
{
// Copy remaining bytes to beginning of buffer
if (dwCharsLeft > 0)
{
memcpy(&m_buffer[0], &m_buffer[m_bufferPtr], dwCharsLeft * sizeof(value_type));
}
m_bufferPtr = 0;
// Read new chars
DWORD dwCharsRead;
m_in->read((char*) &m_buffer[dwCharsLeft], (m_bufferSize - dwCharsLeft) * sizeof(value_type));
dwCharsRead = static_cast<DWORD>(m_in->gcount() / sizeof(value_type));
m_eof = (dwCharsRead == 0);
m_bufferLength = dwCharsLeft + dwCharsRead;
}
// scan for crlf
pw = MemFind(&m_buffer[m_bufferPtr], m_bufferLength - m_bufferPtr, m_crlf, m_crlfLength);
if (pw != 0)
{
// We found the end of the line
size_type dwLen = pw - &m_buffer[m_bufferPtr];
sLine.append(&m_buffer[m_bufferPtr], dwLen);
m_bufferPtr += (dwLen + m_crlfLength);
return true;
}
else if (m_eof)
{
// We're at the end of the file => take everything
size_type dwLen = m_bufferLength - m_bufferPtr;
ASSERT(dwLen >= 0);
sLine.append(&m_buffer[m_bufferPtr], dwLen);
m_bufferPtr += dwLen;
return true;
}
else
{
// No crlf found => take entire buffer
size_type dwLen = m_bufferLength - m_bufferPtr;
dwLen -= (m_crlfLength - 1);
if (dwLen > 0)
{
if (sLine.length() + dwLen > currentCapacity)
{
newCapacity = std::max(currentCapacity, sLine.length() + dwLen);
newCapacity = newCapacity / capacityDiv * capacityMul;
newCapacity = std::min(newCapacity, sLine.max_size());
sLine.reserve(newCapacity);
currentCapacity = newCapacity;
}
sLine.append(&m_buffer[m_bufferPtr], dwLen);
m_bufferPtr += dwLen;
}
}
}
}
// Get crlf style
template <class T> typename LineReader<T>::CrlfStyle LineReader<T>::GetCrlfStyle()
{
return m_crlfStyle;
}
#endif
| true |
25c68fbae098380c0afc5d9a876016001eb28233 | C++ | Marius-Juston/Autonomous-Vehicule | /C++/HistogramFilterOptimization/normalize.cpp | UTF-8 | 495 | 3.140625 | 3 | [] | no_license | #include "headers/normalize.h"
using namespace std;
vector<vector<float> > normalize(vector<vector<float> > &grid) {
float total = 0.0;
for (const vector<float> &r: grid) {
for (float e : r) {
total += e;
}
}
unsigned int i, j, height = grid.size(), width = grid[0].size(), area = height * width, k;
for (k = 0; k < area; ++k) {
i = k / width;
j = k % width;
grid[i][j] = grid[i][j] / total;
}
return grid;
}
| true |
8953b873479b2ecfc2fc85aaa37b39b4c3448b33 | C++ | UniversityofWarwick/LACE | /src/LpcVertex.cc | UTF-8 | 1,210 | 2.5625 | 3 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright University of Warwick 2014
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Authors:
// John Back
/*! \file LpcVertex.cc
\brief Simple class that defines an lpc vertex object
*/
#include "LACE/LpcVertex.hh"
#include <iostream>
LpcVertex::LpcVertex() :
index_(0),
coords_(Eigen::VectorXd::Zero(3)),
curveId_(0),
branchId_(0)
{
}
LpcVertex::LpcVertex(int index, const Eigen::VectorXd& coords,
int curveId, int branchId) :
index_(index),
coords_(coords),
curveId_(curveId),
branchId_(branchId)
{
}
LpcVertex::LpcVertex(const LpcVertex& other) :
index_(other.index_),
coords_(other.coords_),
curveId_(other.curveId_),
branchId_(other.branchId_)
{
}
LpcVertex& LpcVertex::operator = (const LpcVertex& other)
{
index_ = other.index_;
coords_ = other.coords_;
curveId_ = other.curveId_;
branchId_ = other.branchId_;
return *this;
}
LpcVertex::~LpcVertex()
{
}
void LpcVertex::print() const
{
std::cout<<"Vertex "<<index_<<" ["<<curveId_
<<","<<branchId_<<"] = "<<coords_.transpose()<<std::endl;
}
| true |
9272a81c807956749e059c712255e807ef256f62 | C++ | astrivedi/CSCI2270 | /lec09/main.cpp | UTF-8 | 476 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct Node {
int value;
Node* next;
};
int main() {
Node* tmp = new Node();
(*tmp).value = 20;
(*tmp).next=0;
Node* tmp2 = new Node();
tmp2->value = 30;
tmp2->next= tmp;
Node* tmp3 = new Node();
tmp3->value = 40;
tmp3->next= tmp2;
Node* head = tmp3;
while (head != 0) {
cout << head->value << " ";
head = head->next;
}
cout << endl;
return 0;
} | true |
bee92bfeec6592cf7e26b23632acc5020c65b3ae | C++ | HeladodePistacho/DirectXEngine | /DirectXHermano/DirectXHermano/Texture.h | UTF-8 | 443 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Bindable.h"
class Texture : public Bindable
{
public:
Texture(Render& ren, unsigned char* data, unsigned int width, unsigned int height, unsigned int color_channels);
~Texture();
void Bind(Render& ren) override;
ID3D11ShaderResourceView* GetTexture() const { return texture_data; }
bool IsNull() const { return is_empty; }
private:
ID3D11ShaderResourceView* texture_data = nullptr;
bool is_empty = false;
};
| true |
29629ada913103b024bb143175fe9d00cc239a4b | C++ | taiyaki-ichi/FBXLoader | /lib/include/DataStruct.hpp | SHIFT_JIS | 1,158 | 2.59375 | 3 | [] | no_license | #pragma once
#include<variant>
#include<vector>
#include<string>
#include<optional>
#include<type_traits>
#include<unordered_map>
namespace FBXL
{
template<typename Vector2D,typename Vector3D>
struct Vertex
{
Vector3D position;
Vector3D normal;
Vector2D uv;
};
template<typename Vector3D>
struct Material
{
Vector3D diffuseColor;
double diffuseFactor;
std::optional<std::string> diffuseColorTexturePath;
Vector3D ambientColor;
double ambientFactor;
Vector3D specularColor;
double specularFactor;
//Phong̔˃fQ
//e
double shininess;
double shininessFactor;
//g
Vector3D emissive;
double emissiveFactor;
//ߓx
//alphâݍp
double transparent;
double transparentFactor;
Vector3D reflectionColor;
double reflectionFactor;
//BumpMap,NormapMapƂlj邩
};
template<typename Vector2D, typename Vector3D>
struct Model3D
{
std::vector<std::size_t> indeces{};
std::vector<Vertex<Vector2D, Vector3D>> vertices;
std::vector<std::size_t> materialRange{};
std::vector<Material<Vector3D>> material{};
};
} | true |
5a00a0bce9e33bc4360cd7349d6987922d2d5a06 | C++ | pdralston/CSE130 | /asgn2/source/sync_htable/sync_hash.h | UTF-8 | 881 | 2.515625 | 3 | [] | no_license | /**
* Synchronized Hash Table Header File
* @author Perry David Ralston Jr.
* @date 11/20/2020
*/
#ifndef SYNCH_HASHH
#define SYNCH_HASHH
#include <inttypes.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include "hash.h"
static const int8_t NO_PARENT = -1;
struct bucket_lock {
sem_t mutex;
int64_t owner;
};
typedef struct bucket_lock bucket_lock;
class SyncHash : public Hash {
public:
SyncHash(size_t size);
void insert(uint8_t*, int64_t, int64_t);
int8_t remove(uint8_t*, int64_t);
int8_t lookup(uint8_t*, int64_t&, int64_t);
void clear(int64_t);
int8_t dump(const char*, int64_t);
int8_t load(const char*, int64_t);
void acquire(uint8_t*, int64_t);
void release(uint8_t*);
private:
void acquire(uint32_t, int64_t);
void acquire_all(int64_t);
void release(uint32_t hash);
void release_all();
bucket_lock* locks;
};
#endif | true |
c322c2ac3dc5bf34efd489f5caff26f5185ee651 | C++ | vir/supervisor | /config.cxx | UTF-8 | 3,352 | 2.53125 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2012 Vasily i. Redkin <vir@ctm.ru>
* License: MIT (See LICENSE.txt or http://www.opensource.org/licenses/MIT)
*/
#include "config.hpp"
#include "supervisor.hpp"
#include <iostream>
#include <dirent.h>
#include <unistd.h>
ConfTarget * ConfTarget::confcontext(const std::string & ctx, bool brackets)
{
return NULL;
}
Config config;
void trim(std::string & str)
{
const static char * whitespace = " \t\r\n";
std::string::size_type pos = str.find_last_not_of(whitespace);
if(pos != std::string::npos) {
str.erase(pos + 1);
pos = str.find_first_not_of(whitespace);
if(pos != std::string::npos) str.erase(0, pos);
} else
str.erase(str.begin(), str.end());
}
bool Config::load_confdir(const std::string & path)
{
DIR * d = opendir(path.c_str());
if(! d) {
perror(path.c_str());
return false;
}
dirent * e;
while((e = readdir(d))) {
if(e->d_type != DT_REG)
continue;
std::string p(path);
if(*p.rbegin() != '/')
p += '/';
p += e->d_name;
if(p.length() > 5 && p.substr(p.length() - 5) != ".conf")
continue;
if(0 != access(path.c_str(), R_OK))
continue;
reset_context();
if(! read_file(p))
return false;
}
closedir(d);
return true;
}
bool Config::parse_line(std::string line)
{
trim(line);
if(!line.length() || line[0] == '#' || line[0] == ';')
return true;
if(line[0] == '[' && line[line.length() - 1] == ']') {
std::string context = line.substr(1, line.length() - 2);
trim(context);
reset_context();
return change_context(context, true);
}
if(line.substr(0, 8) == "confdir ") {
size_t pos = line.find_first_not_of(" \t", 8);
std::string path = line.substr(pos);
trim(path);
return load_confdir(path);
}
size_t eqpos = line.find('=');
if(eqpos == std::string::npos)
return false; // no =
std::string key = line.substr(0, eqpos);
std::string val = line.substr(eqpos+1);
trim(key);
trim(val);
//std::cout << "Config line: '" << key << "' = '" << val << "'" << std::endl;
ConfTarget * save = m_curtarget;
std::string save2 = m_curctx; // XXX ??? may be drop it ???
bool retval = false;
for(;;) {
size_t pos = key.find('.');
if(pos == std::string::npos)
break;
if(!change_context(key.substr(0, pos)))
return false;
key.erase(0, pos+1);
}
if(m_curtarget)
retval = m_curtarget->configure(key, val);
m_curtarget = save;
m_curctx = save2;
return retval;
}
bool Config::read_file(const std::string & fname)
{
std::ifstream f(fname.c_str());
std::string line;
bool result = true;
int linenum = 1;
if(!f)
return false;
while(getline(f, line)) {
if(!parse_line(line)) {
std::cerr << "Error in " << fname << " line " << linenum << ": " << line << std::endl;
result = false;
}
linenum++;
}
reset_context();
return result;
}
bool Config::change_context(const std::string & context, bool brackets)
{
std::map<std::string, ConfTarget *>::iterator it = m_contexts.find(context);
if(it != m_contexts.end()) {
m_curctx = it->first;
m_curtarget = it->second;
return true;
}
ConfTarget * newctx = m_curtarget->confcontext(context, brackets);
if(newctx) {
//std::cout << "Config context changed to " << context << std::endl;
m_curctx = context; // XXX last part only
m_curtarget = newctx;
return true;
} else {
//std::cout << "Can not change config context to " << context << std::endl;
return false;
}
}
| true |
083c62c1cbe86bec5c8fb84c66a713eed6962453 | C++ | LeBronWilly/Engineering_Cpp | /ch09/prog9_13.cpp | BIG5 | 860 | 3.8125 | 4 | [] | no_license | // prog9_13, ǻƨLƤ
#include <iostream>
#include <cstdlib>
using namespace std;
double triangle(double,double),rectangle(double,double);
void showarea(double,double,double (*pf)(double,double));
int main(void)
{
cout << "triangle(6,3.2)=";
showarea(6,3.2,triangle); // pf=&triangle(&iٲ) // Istriangle(),æLX
cout << "rectangle(4,6.1)=";
showarea(4,6.1,rectangle); // pf=&rectangle(&iٲ) // Isrectangle(),æLX
system("pause");
return 0;
}
double triangle(double base,double height) // pTέn
{
return (base*height/2);
}
double rectangle(double height,double width) // pέn
{
return (height*width);
}
void showarea(double x,double y,double (*pf)(double,double))
{
cout << (*pf)(x,y) << endl;
return;
}
| true |
b05612eddfb5105cab467e5b90752237acd2b2bd | C++ | TheBlubb14/LED | /esp32-src/src/main.cpp | UTF-8 | 818 | 2.84375 | 3 | [
"MIT"
] | permissive | #include "BLE.h"
#include "LED.h"
std::unique_ptr<LED> led;
std::unique_ptr<BLE> ble;
void setup()
{
Serial.begin(115200);
// Serial.setDebugOutput(true);
pinMode(22, OUTPUT);
try
{
led = std::unique_ptr<LED>(new LED());
ble = std::unique_ptr<BLE>(new BLE(*led));
}
catch (const std::exception &e)
{
Serial.println("error class initialisation: ");
Serial.println(e.what());
}
try
{
led->WriteToAllLeds(0, 0, 10, 1);
digitalWrite(22, HIGH);
// led->RainbowCycle(10, 20);
}
catch (const std::exception &e)
{
Serial.println(e.what());
}
Serial.println("intialized");
}
void loop()
{
// put your main code here, to run repeatedly:
// digitalWrite(22, HIGH);
// led->WriteToAllLeds(0, 0, 80, 0);
// delay(5000);
// digitalWrite(22, LOW);
// led->TurnLedOff();
// delay(5000);
}
| true |
f3732b519ff0dc2161c163db5998df25d9ced8c8 | C++ | Skrillite/informatics_contests | /heap/heap_task_H.cpp | UTF-8 | 2,049 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
struct Heap {
Heap () = delete;
Heap ( int _size )
: arr ( new int[_size] )
, arr_size ( _size )
, size ( 0 ) {}
Heap ( int _size, istream& stream )
: arr ( new int[_size] )
, arr_size ( _size )
, size ( _size ) {
int counter ( 0 );
while (counter < size)
stream >> arr[counter++];
for (int i = size / 2; i >= 0; i--)
swift_down ( i );
}
int& operator[] ( int idx ) {
return arr[idx];
}
int add ( int data ) {
if (size < arr_size) {
arr[size] = data; size++;
return swift_up ( size - 1 );
} else return -2;
}
int swift_up ( int i ) {
while (arr[i] > arr[(i - 1) / 2]) {
swap ( arr[i], arr[(i - 1) / 2] );
i = (i - 1) / 2;
}
return i;
}
int swift_down ( int i ) {
if (size < 1) return -1;
int largestChild = i
, leftChild
, rightChild;
while (true) {
leftChild = 2 * i + 1;
rightChild = 2 * i + 2;
if (leftChild < size && arr[leftChild] > arr[largestChild]) largestChild = leftChild;
if (rightChild < size && arr[rightChild] > arr[largestChild]) largestChild = rightChild;
if (largestChild == i) return i;
swap ( arr[largestChild], arr[i] );
i = largestChild;
}
}
int erase ( int idx ) {
if (idx < size && idx > -1) {
int ret = arr[idx];
arr[idx] = arr[size - 1]; size--;
swift_down ( idx );
swift_up ( idx );
return ret;
} else return -1e9 - 1;
}
int pop () {
arr[0] = arr[size - 1]; size--;
return swift_down ( 0 );
}
int get_max () const {
if (size > 0) return arr[0];
else return -1e9 - 1;
}
void show () const {
int counter = 0;
while (counter < size)
cout << arr[counter++] << ' ';
cout << endl;
}
void sort () {
int tmp;
while (size > 0) {
tmp = get_max ();
pop ();
show ();
arr[size] = tmp;
}
for (int i = 0; i < arr_size; i++) {
cout << arr[i] << ' ';
}
}
private:
const int arr_size;
int* arr;
int size;
};
int main () {
int n; cin >> n;
Heap hp ( n, cin );
hp.show ();
hp.sort ();
} | true |
012acc878b6ec317a728f3192703e5ba187a6358 | C++ | clickto/no2-linggong-road | /src/roleinfowidget.h | UTF-8 | 1,057 | 2.578125 | 3 | [
"WTFPL"
] | permissive | #ifndef ROLEINFOWIDGET_H
#define ROLEINFOWIDGET_H
//此类根据RoleInfo指针从堆上读取当前各角色的相关信息,根据接收消息显示不同的信息,被多个widget复用
/*roleInfo是一个指针数组,大小为ROLENUMBER宏定义,每个元素是相应角色当前
的Role指针,如果当前不拥有该角色则指针为NULL。注意数组索引,roleID是从1开始的。
*/
#define ROLEINFOWIDGETWIDTH 240
#define ROLEINFOWIDGETHEIGHT 480
#include "lgl.h"
#include "role.h"
class RoleInfoWidget : public QWidget
{
Q_OBJECT
public:
explicit RoleInfoWidget(QWidget *parent,Role **roleInfo);
void changeToRoleOf(int id);
signals:
public slots:
private:
void paintEvent(QPaintEvent *);
int currentRoleID;
Role **roleInfo;
QPixmap lvIcon;
QPixmap hpIcon;
QPixmap expIcon;
QPixmap paIcon;
QPixmap pdIcon;
QPixmap iqIcon;
// QPixmap maIcon;
// QPixmap mdIcon;
QPixmap moveIcon;
QFont font;
};
#endif // ROLEINFOWIDGET_H
| true |
d82ab5d471c64b9a0645d220e85c5ad68e65e4cb | C++ | jgmatu/SimpleEngine | /include/Program/Uniforms.hpp | UTF-8 | 1,433 | 2.859375 | 3 | [] | no_license | #ifndef DATA_H
#define DATA_H
#include <map>
#include <vector>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
class Uniforms {
public:
Uniforms();
~Uniforms();
void update(Uniforms *uniforms);
void setUniformInt(std::string name, int value);
void setUniformFloat(std::string name, float value);
void setUniformVec4(std::string name, glm::vec4 value);
void setUniformVec3(std::string name, glm::vec3 value);
void setUniformMat4(std::string name, glm::mat4 value);
std::vector<std::string> getUniformsNamesInt();
std::vector<std::string> getUniformsNamesFloat();
std::vector<std::string> getUniformsNamesVec4();
std::vector<std::string> getUniformsNamesVec3();
std::vector<std::string> getUniformsNamesMat4();
glm::mat4 getUniformValueMat4(std::string name);
glm::vec3 getUniformValueVec3(std::string name);
glm::vec4 getUniformValueVec4(std::string name);
int getUniformValueInt(std::string name);
float getUniformValueFloat(std::string name);
friend std::ostream& operator<<(std::ostream& os, const Uniforms& uniforms);
private:
// Uniforms engine abstraction
std::map<std::string, int> _uniformsInt;
std::map<std::string, float> _uniformsFloat;
std::map<std::string, glm::vec3> _uniformsVec3;
std::map<std::string, glm::vec4> _uniformsVec4;
std::map<std::string, glm::mat4> _uniformsMat4;
};
#endif
| true |
1d2c8f43c24b4ac4134b84ee9b409c5aafd28bd0 | C++ | siqihuang/Movable-Tree | /Movable_Tree/MoveReadyTree/connectingNode.cpp | UTF-8 | 4,766 | 2.53125 | 3 | [] | no_license | #include "connectingNode.h"
MTypeId connectingNode::id( 0x80002 );
MObject connectingNode::tmp;
MObject connectingNode::tmp1;
MObject connectingNode::index1;
MObject connectingNode::index2;
MObject connectingNode::trigger;
MObject connectingNode::rootNumber;
int connectingNode::state;
connectingNode::connectingNode(){
}
connectingNode::~connectingNode(){
}
void* connectingNode::creator(){
return new connectingNode();
}
MStatus connectingNode::initialize()
{
MFnTypedAttribute tAttr;
MFnNumericAttribute nAttr;
MStatus returnStatus;
connectingNode::state=0;
connectingNode::tmp=nAttr.create("tmp","t",MFnNumericData::kInt,0,&returnStatus);
connectingNode::tmp1=nAttr.create("tmp1","t1",MFnNumericData::kInt,0,&returnStatus);
connectingNode::index1=nAttr.create("index1","in1",MFnNumericData::kInt,-1,&returnStatus);
connectingNode::index2=nAttr.create("index2","in2",MFnNumericData::kInt,-1,&returnStatus);
connectingNode::trigger=nAttr.create("trigger","tri",MFnNumericData::kBoolean,true,&returnStatus);
connectingNode::rootNumber=nAttr.create("rootNum","rN",MFnNumericData::kInt,0,&returnStatus);
addAttribute(tmp);
addAttribute(tmp1);
addAttribute(index1);
addAttribute(index2);
addAttribute(trigger);
addAttribute(rootNumber);
attributeAffects(tmp1,tmp);
return MS::kSuccess;
}
MStatus connectingNode::compute(const MPlug &plug,MDataBlock &data){
MStatus status=MStatus::kSuccess;
bool tri=data.inputValue(trigger,&status).asBool();
if(plug==tmp&&tri){
//4.3 compute F-domain graph
if(state==0)
{
//jason
//fdg.beforeInit();
fdg.InitAnchorPoints();
fdg.compute();
extractBlockNum();
state=1;
std::string fdNum=std::to_string((long double)fdomain_list.size());
MGlobal::executeCommand("$FDomainNum="+MString(fdNum.c_str())+";");
//pass F Domain numbers to mel
std::string preferredRoot=std::to_string((long double)fdg.GetInitialRootDomain());
MGlobal::executeCommand("$preferredDomainIndex="+MString(preferredRoot.c_str())+";");
//pass preferred root index to mel
MGlobal::executeCommand("button -edit -enable true $connectingNextButton;");
turnOffTrigger(data);
}
else if(state==1){//compute new blocks num and highlight blocks
MGlobal::executeCommand("clear($connectingBlock)");//clear the last data
hideOtherMesh();
setBlockGroup();
MGlobal::executeCommand("highlightBlocks();");
if(fdomain_components.size()>1)
state=2;
else
state=3;
turnOffTrigger(data);
}
else if(state==2){//connect edge
int in1=data.inputValue(index1,&status).asInt();
int in2=data.inputValue(index2,&status).asInt();
in1=domain_list[in1]->index;
in2=domain_list[in2]->index;
fdg.ConnectFdomain(in1,in2);
extractBlockNum();
state=1;
turnOffTrigger(data);
}
else if(state==3){//select root domain
int rootIndex=data.inputValue(rootNumber,&status).asInt();
std::string s=std::to_string((long double)rootIndex);
MGlobal::displayInfo(MString(s.c_str()));
fdg.SetRootDomain(rootIndex);
MGlobal::displayInfo("successful!");
turnOffTrigger(data);
}
}
return MS::kSuccess;
}
void connectingNode::extractBlockNum(){
std::string num=std::to_string((long double)fdomain_components.size());
MString com="$unconnectedDomainNum="+MString(num.c_str())+";";
com+="string $tmp=\"connected domains: \"+$unconnectedDomainNum;";
com+="text -edit -label $tmp $domainsToBeConnected;";
MGlobal::executeCommand(com);
}
void connectingNode::hideOtherMesh(){
MGlobal::executeCommand("hide -all");//hide all domain first;
std::string com;
com="select ";
for(int i=0;i<fdomain_list.size();i++){
com+="instancing"+std::to_string((long double)fdomain_list[i]->index)+" ";
}
std::string s=std::to_string((long double)fdomain_list.size());
MGlobal::displayInfo(MString(s.c_str()));
com+=";showHidden -above;";
MGlobal::executeCommand(MString(com.c_str()));
}
void connectingNode::setBlockGroup(){
std::map<Domain*, std::vector<Domain*>>::iterator it;
int n=0;
std::string com;
com="";
it=fdomain_components.begin();//once at a time, no need to loop, recompute after every operation
com="$connectingBlock["+std::to_string((long double)n)+"]="+std::to_string((long double)it->first->index)+";";
MGlobal::executeCommand(MString(com.c_str()));
n++;
for(int i = 0; i < it->second.size(); ++i)
{
com="$connectingBlock["+std::to_string((long double)n)+"]="+std::to_string((long double)it->second[i]->index)+";";
MGlobal::executeCommand(MString(com.c_str()));
n++;
MGlobal::displayInfo(MString(com.c_str()));
}
state=2;
}
void connectingNode::turnOffTrigger(MDataBlock &data){
MStatus status=MStatus::kSuccess;
MDataHandle triggerHandle=data.outputValue(trigger,&status);
triggerHandle.setBool(false);
} | true |
4482925e3c492b2d2adc53041abdcccde7eebb9d | C++ | ricardocosme/msqlite | /test/connection.cpp | UTF-8 | 2,333 | 3.25 | 3 | [
"MIT"
] | permissive | #include <boost/core/lightweight_test.hpp>
#include <msqlite/db.hpp>
#include <iostream>
using namespace std;
using namespace msqlite;
int main(){
//default ctor
{
db c;
BOOST_TEST(c.get() == nullptr);
BOOST_TEST(c == db{});
}
//close the db when 'db' is destroyed
{
sqlite3* pdb;
sqlite3_open("", &pdb);
{
db c{pdb};
BOOST_TEST(c.get() != nullptr);
BOOST_TEST(c.get() == pdb);
BOOST_TEST(c != db{});
}
}
//should be ok if the dbs had been closed before the
//destruction of 'db'
{
sqlite3* pdb;
sqlite3_open("", &pdb);
{
db c{pdb};
BOOST_TEST(c.get() != nullptr);
BOOST_TEST(c.get() == pdb);
}
}
//move ctor
{
sqlite3* pdb;
sqlite3_open("", &pdb);
{
db c{pdb};
auto c2 = std::move(c);
BOOST_TEST(c.get() == nullptr);
BOOST_TEST(c2.get() == pdb);
}
}
//move assignment op
{
sqlite3 *pdb, *pdb2;
sqlite3_open("", &pdb);
sqlite3_open("", &pdb2);
{
db c{pdb};
db c2{pdb2};
BOOST_TEST(c != c2);
c2 = std::move(c);
BOOST_TEST(c.get() == nullptr);
BOOST_TEST(c2.get() == pdb);
}
}
//release
{
sqlite3* pdb;
sqlite3_open("", &pdb);
{
db c{pdb};
sqlite3_close(c.release());
BOOST_TEST(c.get() == nullptr);
}
}
//explicit close
{
sqlite3* pdb;
sqlite3_open("", &pdb);
{
db c{pdb};
c.close();
BOOST_TEST(c.get() == nullptr);
}
}
//reset with nullptr
{
sqlite3* pdb;
sqlite3_open("", &pdb);
{
db c{pdb};
c.reset();
BOOST_TEST(c.get() == nullptr);
}
}
//reset with othe db
{
sqlite3* pdb;
sqlite3_open("", &pdb);
{
db c{pdb};
sqlite3* pdb2;
sqlite3_open("", &pdb2);
c.reset(pdb2);
BOOST_TEST(c.get() == pdb2);
}
}
return boost::report_errors();
}
| true |
38a5f4b571e27fb243c4bfd305a991e58e41d5e9 | C++ | long327/RestAPIWt | /restapi/src/db/mongowrapper.cpp | UTF-8 | 2,742 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive |
#include <iostream>
using namespace std;
#include <cstdlib>
#include <db/mongowrapper.h>
#include <db/constants.h>
mongoWrapper :: mongoWrapper()
{
mongo::client::initialize();
}
bool mongoWrapper::connect()
{
bool bRet = true;
try {
_error = "";
c.connect(DB_CONN_STR);
} catch( const mongo::DBException &e )
{
_error = e.what();
bRet = false;
}
return bRet;
}
std::string mongoWrapper::error()
{
return _error;
}
std::string mongoWrapper::insert(std::string dbpath , BSONObj &obj)
{
if(!c.isStillConnected ())
{
connect();
}
std::string retId = "";
try {
_error = "";
c.insert(dbpath, obj);
retId = obj["_id"];
} catch( const mongo::DBException &e )
{
_error = e.what();
}
return retId;
}
std::string mongoWrapper::update(std::string dbpath ,mongo::Query query, BSONObj &obj)
{
if(!c.isStillConnected ())
{
connect();
}
std::string retId = "";
try {
_error = "";
c.update(dbpath,query, obj);
} catch( const mongo::DBException &e )
{
_error = e.what();
}
return retId;
}
std::list<BSONObj> mongoWrapper::getAll(std::string dbpath, std::string searchcri)
{
if(!c.isStillConnected ())
{
std::cout << "mongoWrapper::getAll():db not connected, connecting.." << endl;
connect();
}
std::cout << "mongoWrapper::getAll():db connected :" <<dbpath << endl;
int nc =c.count(dbpath);
std::cout << "mongoWrapper::getAll():#" << nc << endl;
std::list<BSONObj> retList;
if(nc >0)
{
auto_ptr<mongo::DBClientCursor> cursor ;
if(searchcri != "")
{
BSONObj bquery = mongo::fromjson(searchcri);
mongo::Query q = mongo::Query(bquery);
cursor = c.query(dbpath, q);
}
else
{
cursor = c.query(dbpath, BSONObj());
}
while (cursor->more())
{
BSONObj p = cursor->next().getOwned();
if(p.isEmpty() || !p.isValid())
break;
std::string pval = p.toString();
std::cout << ' ' << pval << std::endl;
retList.push_back(p);
}
}
return retList;
}
/*************
#include <db/constants.h>
int main() {
mongoWrapper mongo;
if(mongo.connect("192.168.1.191"))
std::cout << "connected ok" << std::endl;
else
std::cout << " failed to connect " << mongo.error() << std::endl;
BSONObj o = BSON( "_id" << mongo::OID::gen() << "name" << "ABC Publishers") ;
std::string id = mongo.insert(DB_PUBLISHERS , o);
std::cout <<"Id=" << id << endl;
std::list<BSONObj> list = mongo.getAll(DB_PUBLISHERS);
std::list<BSONObj>::iterator it;
for (it=list.begin(); it!=list.end(); ++it)
{
std::string jstr = (*it).toString();
std::cout << ' ' << jstr;
}
return 0;
}
*********************/
| true |
2e63b0293f68a831573564c07b9f1a39714c0731 | C++ | penut85420/CppWork | /Cpp_Lab/lab10-1/StudentList.h | UTF-8 | 365 | 2.84375 | 3 | [] | no_license | #pragma once
#include "Student.h"
class StudentList {
public:
StudentList();
~StudentList();
void appendEntry(Student*);
bool deleteEntry(char*);
Student* find(char*);
private:
class Node {
public:
Node(Student *data);
Node();
~Node();
friend class StudentList;
private:
Student *mData;
Node *mNext;
};
Node *mHead, *mTail;
}; | true |
9b89b921ff734bcfa2da9b9f40c899dfd01fe589 | C++ | smart-tai/maya_SDK | /2020/include/maya/adskDataIndex.h | UTF-8 | 4,861 | 2.765625 | 3 | [] | no_license | #ifndef adskDataIndex_h
#define adskDataIndex_h
#include <maya/adskCommon.h>
#include <maya/adskDebugCount.h> // For DeclareObjectCounter()
#include <map>
#include <string>
// Forward declaration of member data
namespace adsk {
namespace Debug {
class Print;
class Count;
class Footprint;
};
namespace Data {
class IndexType;
typedef unsigned int IndexCount;
// ****************************************************************************
/*!
\class adsk::Data::Index
\brief Lightweight class handling index values
adsk::Data::Stream objects contain a list of data elements. Each element
has to be accessed by index. In the simplest case the index is an array
index (of type IndexCount, whose typedef appears above) but there can be
more complex cases as well, such as a pair of integers, or a string.
This is the base class used by the adsk::Data:Stream indexing system. It
is configured to be as efficient as possible in the simple index case
while allowing extension to arbitrary index types. The simple integer
index value is contained within this class. More complex index types
are stored in a letter class of type "IndexType".
It can be used as the basis of a mapping from a general index type onto
an adsk::Data::Index value, used for data referencing. Its purpose is
to overload the concept of a general std::map<Index, Index> so that
in the simple case where Index is the same as Index no mapping is
required. The calling classes are responsible for creating that relationship,
the methods in this class are defined to support that use.
*/
class METADATA_EXPORT Index
{
public:
//----------------------------------------------------------------------
// Constructor and type conversions
Index () : fComplexIndex( nullptr ), fIndex( 0 ) {}
Index ( IndexCount value );
Index ( const Index& rhs );
Index ( const IndexType& rhs );
Index ( const std::string& indexValue );
~Index ();
//
Index& operator= ( IndexCount rhs );
Index& operator= ( const Index& rhs );
Index& operator= ( const IndexType& rhs );
operator IndexCount () const;
IndexCount index () const;
operator IndexType* ();
std::string asString () const;
//! \fn IndexType* complexIndex()
//! \brief Quick access to the complex index, if it's used
//! \return Pointer to the complex index type, or NULL if the index is simple
IndexType* complexIndex() { return fComplexIndex; }
const IndexType* complexIndex() const { return fComplexIndex; }
//----------------------------------------------------------------------
// Dense mapping support
bool supportsDenseMode () const;
IndexCount denseSpaceBetween ( const Index& rhs ) const;
//----------------------------------------------------------------------
// Comparison operators for easy sorting
bool operator== (const Index& rhs) const;
bool operator!= (const Index& rhs) const;
bool operator< (const Index& rhs) const;
bool operator<= (const Index& rhs) const;
bool operator> (const Index& rhs) const;
bool operator>= (const Index& rhs) const;
//----------------------------------------------------------------------
// Debug support
static bool Debug(const Index* me, Debug::Print& request);
static bool Debug(const Index* me, Debug::Footprint& request);
DeclareObjectCounter(adsk::Data::Index);
private:
IndexCount fIndex; //! Array index for direct data storage
IndexType* fComplexIndex; //! Further data for complex index types
public:
// Support for creation of arbitrary index types and values from a pair of
// strings (one for the type, one for the value)
//
typedef Index (*IndexCreator) ( const std::string& );
enum eCreationErrors { kNoCreator, kBadSyntax, kExcessData };
static Index doCreate ( const std::string&, const std::string& );
static IndexCreator creator ( const std::string& );
static std::string theTypeName ();
std::string typeName () const;
private:
// Everything down here is for internal use to manage the creation list.
// The public access methods above is all of the useful functionality.
friend class IndexType; // Friended to allow for automatic registration
typedef std::map<std::string, IndexCreator> IndexTypeRegistry;
static bool registerType ( const std::string&, IndexCreator );
static Index TypeCreator ( const std::string& );
static IndexTypeRegistry& creators ();
};
} // namespace Data
} // namespace adsk
//=========================================================
//-
// Copyright 2015 Autodesk, Inc. All rights reserved.
// Use of this software is subject to the terms of the
// Autodesk license agreement provided at the time of
// installation or download, or which otherwise accompanies
// this software in either electronic or hard copy form.
//+
//=========================================================
#endif // adskDataIndex_h
| true |
83cdaf88b7bc40eea88ecd1208d77ab475185ad6 | C++ | ragrag/Queue-Simulation-QT | /Result.cpp | UTF-8 | 2,405 | 3.09375 | 3 | [] | no_license | #include "Result.h"
//Members clearing
Result::Result()
{
clear();
}
//Constructor
Result::Result(float avgDriveinSvc,float avgInsideSvc,float avgWaitingDrivein,float avgWaitingInside, float maxQueueLength, float probInside,int idleTime,float avgSvcAll,float avgInterArrival,float probToGoInside,float timeSpent)
{
this-> avgSvcDrivein= avgDriveinSvc;
this->avgSvcInside= avgInsideSvc;
this->avgWaitingDrivein = avgWaitingDrivein;
this->avgWaitingInside = avgWaitingInside;
this->maxQueueLength= maxQueueLength;
this->probInside= probInside;
this->idleTime= idleTime;
this->avgSvcAll = avgSvcAll;
this->avgInterArrival = avgInterArrival;
this->probToGoInside = probToGoInside;
this->avgTimeSpent = timeSpent;
}
//Get by order
float Result::operator[] (int i)
{
switch (i) {
case 0: return (float) avgSvcAll;
case 1: return (float) avgInterArrival;
case 2: return avgSvcDrivein;
case 3: return avgSvcInside;
case 4: return avgWaitingDrivein;
case 5: return avgWaitingInside;
case 6: return (float) maxQueueLength;
case 7: return probInside;
case 8: return (float) idleTime;
case 9 : return probToGoInside;
case 10 : return avgTimeSpent;
default: return -1;
}
}
//Overloaded + operator for adding results together
Result Result::operator+(Result other)
{
return Result(avgSvcDrivein + other.avgSvcDrivein, avgSvcInside + other.avgSvcInside,
avgWaitingDrivein + other.avgWaitingDrivein, avgWaitingInside + other.avgWaitingInside ,maxQueueLength + other.maxQueueLength, probInside + other.probInside, idleTime + other.idleTime,
avgSvcAll+other.avgSvcAll,avgInterArrival +other.avgInterArrival,probToGoInside+other.probToGoInside,avgTimeSpent+other.avgTimeSpent);
}
//Overloaded / operator for deviding a result by a number
Result Result::operator/(int n)
{
return Result(avgSvcDrivein/n , avgSvcInside/n, avgWaitingDrivein / n, avgWaitingInside / n, maxQueueLength/n, probInside/n, idleTime/n,avgSvcAll/n,avgInterArrival/n,probToGoInside/n,avgTimeSpent/n);
}
//Set all members to 0
void Result::clear()
{
avgSvcDrivein = 0;
avgSvcInside = 0;
avgWaitingDrivein = 0;
avgWaitingInside = 0;
maxQueueLength = 0;
probInside = 0;
idleTime = 0;
avgSvcAll = 0;
avgInterArrival = 0;
probToGoInside = 0;
avgTimeSpent = 0;
}
Result::~Result()
{
}
| true |
9557e32f8f3d20797dda6bfa27681ea6d6eb8d33 | C++ | BeenEncoded/Simple-Task-List-Program | /Source code/functions/display/common.cpp | UTF-8 | 7,228 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include "../../functions/display/iofunctions.hpp"
#include "common.hpp"
#include "../../globals/global_defines.hpp"
namespace
{
bool char_match(const char&, const std::string&);
template<class type1, class type2>
inline type2 conv(const type1& t1)
{
std::stringstream ss;
type2 t2;
ss<< t1;
ss>> t2;
return t2;
}
inline bool char_match(const char& ch, const std::string& s)
{
bool match(false);
for(std::string::const_iterator it = s.begin(); ((it != s.end()) && !match); ++it)
{
match = (*it == ch);
}
return match;
}
}
namespace common
{
bool is_number(const char& ch)
{
return char_match(ch, NUMBERS);
}
bool is_special(const char& ch)
{
return char_match(ch, SPECIALS);
}
bool is_letter(const char& ch)
{
return char_match(ch, LETTERS);
}
bool is_char(const char& ch)
{
return (is_letter(ch) || is_number(ch) || is_special(ch));
}
void center(const std::string& s)
{
using namespace std;
int max = (s.size() / 2);
max -= int(HCENTER);
if(max < 0) max = 0;
for(int x = 0; x < max; x++) cout<< " ";
cout<< s;
}
bool string_is_int(const std::string& s)
{
unsigned short count(0);
for(std::string::const_iterator it = s.begin(); ((it != s.end()) && (count == 0)); ++it)
{
if(!is_number(*it))
{
count++;
}
}
return (count == 0);
}
void wait()
{
for(short x = 0; x < 3; x++) std::cout<< std::endl;
std::cout<< "Press any key to continue..."<< std::endl;
cl();
gkey();
cl();
}
void cl()
{
input::cl();
}
void cls()
{
output::cls();
}
char gkey()
{
return input::getch();
}
bool kbhit()
{
return input::kbhit();
}
std::vector<int> gkey_funct()
{
using namespace std;
vector<int> key;
key.push_back(input::getch());
if(IS_CONTROL(key[0]))
{
while(input::kbhit())
{
key.push_back(input::getch());
}
}
return key;
}
namespace inp
{
std::string get_user_string(const std::string& s)
{
using namespace std;
vector<int> key;
bool finished(false);
string input;
while(!finished)
{
cls();
for(short x = 0; x < 6; x++) cout<< endl;
cout<< ((s.size() > 0) ? s : ">> ")<< input;
cin.rdbuf()->in_avail();
cl();
do
{
key = gkey_funct();
if(key.size() > 0)
{
switch(IS_CONTROL(key[0]))
{
case true:
{
if(key == END_KEY)
{
input.erase();
input = GSTRING_CANCEL;
finished = true;
}
}
break;
case false:
{
switch(is_char(key[0]))
{
case true:
{
input += char(key[0]);
}
break;
case false:
{
switch(key[0])
{
case ENTER_KEY:
{
finished = true;
}
break;
case BACKSPACE_KEY:
{
if(input.size() > 0)
{
input.resize((input.size() - 1));
}
}
break;
default:
{
}
break;
}
}
break;
default:
{
}
break;
}
}
break;
default:
{
}
break;
}
}
}while(kbhit());
}
return input;
}
bool is_sure(const std::string& message)
{
using namespace std;
bool sure(false), finished(false);
do
{
common::cls();
cout.flush();
for(char x = 0; x < VCENTER; x++) cout<< '\n';
cout.flush();
common::center((message.empty() ? "ARE YOU SURE?" : message));
cout<< "\n\n";
common::center("[Y]es or [N]o?");
cout<< '\n';
switch(tolower(common::gkey()))
{
case 'y':
{
finished = true;
sure = true;
}
break;
case 'n':
{
finished = true;
sure = false;
}
break;
default:
{
}
break;
}
}while(!finished);
return sure;
}
}
}
| true |
63f8722fb5c4130557aac6a951f89376192be168 | C++ | swd3e2/Snake | /Snake/src/Import/Model/gltf/GltfImporter.cpp | UTF-8 | 16,809 | 2.546875 | 3 | [] | no_license | #include "GltfImporter.h"
bool GltfImporter::canParseFile(const std::string& filename) {
return filename.substr(filename.size() - 4, 4).compare("gltf") == 0;
}
std::shared_ptr<Import::Model> GltfImporter::import(const std::string& filename)
{
meshCounter = nodeCounter = animationNodeCounter = 0;
tinygltf::Model gltfModel;
tinygltf::TinyGLTF loader;
if (!loader.LoadASCIIFromFile(&gltfModel, nullptr, nullptr, filename)) {
return nullptr;
}
Import::Model* model = new Import::Model();
model->filename = filename;
std::string binaryFilePath = getBinaryFileFolder(filename) + gltfModel.buffers[0].uri;
std::ifstream binary(binaryFilePath, std::fstream::in | std::fstream::binary);
if (!binary.is_open()) {
delete model;
return nullptr;
}
tinygltf::Node& modelRootNode = gltfModel.nodes[gltfModel.scenes[0].nodes[0]];
model->rootNode = 0;// gltfModel.scenes[0].nodes[0];
processHierarchy(model, gltfModel);
processSkin(model, gltfModel, binary);
processMaterials(model, gltfModel);
processMeshes(model, gltfModel, binary);
processAnimations(model, gltfModel, binary);
binary.close();
calculateTangent(model);
return std::shared_ptr<Import::Model>(model);
}
void GltfImporter::processMeshes(Import::Model* model, const tinygltf::Model& gltfModel, std::ifstream& binary)
{
for (int i = 0; i < gltfModel.meshes.size(); i++) {
const tinygltf::Mesh& gltfMesh = gltfModel.meshes[i];
for (auto& primitive : gltfMesh.primitives) {
std::shared_ptr<Import::Mesh> mesh = std::make_shared<Import::Mesh>();
mesh->material = primitive.material;
mesh->name = gltfMesh.name.size() ? gltfMesh.name : ("Mesh " + std::to_string(meshCounter));
mesh->id = i;
for (auto& attribute : primitive.attributes) {
const tinygltf::Accessor& accessor = gltfModel.accessors[attribute.second];
const tinygltf::BufferView& bufferView = gltfModel.bufferViews[accessor.bufferView];
binary.seekg(bufferView.byteOffset + accessor.byteOffset, std::fstream::beg);
if (mesh->vertices.size() < accessor.count) {
mesh->vertices.resize(accessor.count);
}
if (accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) {
if (attribute.first == "NORMAL") {
float* data = new float[accessor.count * 3];
binary.read((char*)data, sizeof(float) * accessor.count * 3);
for (int i = 0; i < accessor.count; i++) {
mesh->vertices[i].normal.x = data[i * 3];
mesh->vertices[i].normal.y = data[i * 3 + 1];
mesh->vertices[i].normal.z = data[i * 3 + 2];
}
delete[] data;
} else if (attribute.first == "POSITION") {
float* data = new float[accessor.count * 3];
binary.read((char*)data, sizeof(float) * accessor.count * 3);
for (int i = 0; i < accessor.count; i++) {
mesh->vertices[i].pos.x = data[i * 3];
mesh->vertices[i].pos.y = data[i * 3 + 1];
mesh->vertices[i].pos.z = data[i * 3 + 2];
}
delete[] data;
} else if (attribute.first == "WEIGHTS_0") {
float* data = new float[accessor.count * 4];
binary.read((char*)data, sizeof(float) * accessor.count * 4);
for (int i = 0; i < accessor.count; i++) {
mesh->vertices[i].boneData.weights[0] = data[i * 4];
mesh->vertices[i].boneData.weights[1] = data[i * 4 + 1];
mesh->vertices[i].boneData.weights[2] = data[i * 4 + 2];
mesh->vertices[i].boneData.weights[3] = data[i * 4 + 3];
}
delete[] data;
} else if (attribute.first == "TEXCOORD_0") {
float* data = new float[accessor.count * 2];
binary.read((char*)data, sizeof(float) * accessor.count * 2);
for (int i = 0; i < accessor.count; i++) {
mesh->vertices[i].texCoord.x = data[i * 2];
mesh->vertices[i].texCoord.y = data[i * 2 + 1];
}
delete[] data;
} else if (attribute.first == "TANGENT") {
mesh->hasTangent = true;
float* data = new float[accessor.count * 4];
binary.read((char*)data, sizeof(float) * accessor.count * 4);
for (int i = 0; i < accessor.count; i++) {
mesh->vertices[i].tangent = glm::eulerAngles(glm::quat(data[i * 4 + 3], data[i * 4], data[i * 4 + 1], data[i * 4 + 2]));
}
delete[] data;
}
} else if (accessor.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) {
if (attribute.first == "JOINTS_0") {
unsigned short* data = new unsigned short[accessor.count * 4];
binary.read((char*)data, sizeof(unsigned short) * accessor.count * 4);
for (int i = 0; i < accessor.count; i++) {
mesh->vertices[i].boneData.joints[0] = data[i * 4 + 0];
mesh->vertices[i].boneData.joints[1] = data[i * 4 + 1];
mesh->vertices[i].boneData.joints[2] = data[i * 4 + 2];
mesh->vertices[i].boneData.joints[3] = data[i * 4 + 3];
}
delete[] data;
}
}
}
// Indices
const tinygltf::Accessor& accessor = gltfModel.accessors[primitive.indices];
const tinygltf::BufferView& bufferView = gltfModel.bufferViews[accessor.bufferView];
binary.seekg(bufferView.byteOffset + accessor.byteOffset, std::fstream::beg);
if (accessor.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) {
unsigned short* data = new unsigned short[accessor.count];
binary.read((char*)data, sizeof(unsigned short) * accessor.count);
for (int i = 0; i < accessor.count; i++) {
mesh->indices.push_back(data[i]);
}
delete[] data;
} else if (accessor.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) {
unsigned int* data = new unsigned int[accessor.count];
binary.read((char*)data, sizeof(unsigned int) * accessor.count);
for (int i = 0; i < accessor.count; i++) {
mesh->indices.push_back(data[i]);
}
delete[] data;
}
model->meshes[mesh->id].push_back(mesh);
}
}
}
void GltfImporter::processMaterials(Import::Model* model, const tinygltf::Model& gltfModel)
{
for (int i = 0; i < gltfModel.materials.size(); i++) {
const tinygltf::Material& gltfMaterial = gltfModel.materials[i];
Import::Material material;
material.id = i;
material.name = gltfMaterial.name;
for (auto& value : gltfMaterial.values) {
if (value.first == "baseColorTexture") {
material.diffuseTexture = gltfModel.images[gltfModel.textures[value.second.TextureIndex()].source].uri;
} else if (value.first == "metallicRoughnessTexture") {
material.roughnesTexture = gltfModel.images[gltfModel.textures[value.second.TextureIndex()].source].uri;
} else if (value.first == "metallicFactor") {
material.metallicFactor = (float)value.second.number_value;
} else if (value.first == "roughnessFactor") {
material.roughnessFactor = (float)value.second.number_value;
} else if (value.first == "baseColorFactor") {
material.baseColorFactor = glm::vec4(
value.second.number_array[0],
value.second.number_array[1],
value.second.number_array[2],
value.second.number_array[3]
);
}
}
for (auto& value : gltfMaterial.additionalValues) {
if (value.first == "emisiveTexture") {
material.emisiveTexture = gltfModel.images[gltfModel.textures[value.second.TextureIndex()].source].uri;
} else if (value.first == "normalTexture") {
material.normalTexture = gltfModel.images[gltfModel.textures[value.second.TextureIndex()].source].uri;
} else if (value.first == "occlusionTexture") {
material.occlusionTexture = gltfModel.images[gltfModel.textures[value.second.TextureIndex()].source].uri;
} else if (value.first == "emissiveFactor") {
material.emissiveFactor = (float)value.second.number_value;
}
}
for (auto& it : gltfMaterial.extensions) {
std::vector<std::string> keys = it.second.Keys();
for (std::string& key : keys) {
auto& value = it.second.Get(key);
if (value.IsObject()) {
std::vector<std::string> innerKeys = value.Keys();
for (std::string& innerKey : innerKeys) {
if (key == "diffuseTexture" && innerKey == "index") {
tinygltf::Value index = value.Get(innerKey);
int val = index.Get<int>();
material.diffuseTexture = gltfModel.images[gltfModel.textures[val].source].uri;
} else if (key == "specularGlossinessTexture" && innerKey == "index") {
tinygltf::Value index = value.Get(innerKey);
int val = index.Get<int>();
material.specularTexture = gltfModel.images[gltfModel.textures[val].source].uri;
}
}
}
}
}
model->materials.push_back(material);
}
}
void GltfImporter::processSkin(Import::Model* model, const tinygltf::Model& gltfModel, std::ifstream& binary)
{
if (gltfModel.skins.size() > 0) {
model->skinned = true;
const tinygltf::Accessor& accessor = gltfModel.accessors[gltfModel.skins[0].inverseBindMatrices];
const tinygltf::BufferView& bufferView = gltfModel.bufferViews[accessor.bufferView];
binary.seekg(bufferView.byteOffset + accessor.byteOffset, std::fstream::beg);
glm::mat4* matrixData = new glm::mat4[gltfModel.skins[0].joints.size()];
binary.read((char*)matrixData, sizeof(glm::mat4) * accessor.count);
model->rootJoint = gltfModel.skins[0].skeleton;
model->joints = gltfModel.skins[0].joints;
for (int i = 0; i < gltfModel.skins[0].joints.size(); i++) {
model->inverseBindMatrices.push_back(glm::transpose(matrixData[i]));
}
delete[] matrixData;
}
}
/**
* Loads keyframes for animation
*/
void GltfImporter::processAnimations(Import::Model* model, tinygltf::Model& gltfModel, std::ifstream& binary)
{
for (auto& animation : gltfModel.animations) {
std::shared_ptr<Import::Animation> mAnimation = std::make_shared<Import::Animation>();
mAnimation->name = animation.name;
for (tinygltf::AnimationChannel& channel : animation.channels) {
tinygltf::AnimationSampler& sampler = animation.samplers[channel.sampler];
tinygltf::Accessor& timeAccessor = gltfModel.accessors[sampler.input];
tinygltf::BufferView& timeBufferView = gltfModel.bufferViews[timeAccessor.bufferView];
binary.seekg(timeBufferView.byteOffset + timeAccessor.byteOffset, std::fstream::beg);
float* timeData = new float[timeAccessor.count];
binary.read((char*)timeData, sizeof(float) * timeAccessor.count);
if (timeData[timeAccessor.count - 1] > mAnimation->duration) {
mAnimation->duration = timeData[timeAccessor.count - 1];
}
tinygltf::Accessor& valueAccessor = gltfModel.accessors[sampler.output];
tinygltf::BufferView& valueBufferView = gltfModel.bufferViews[valueAccessor.bufferView];
binary.seekg(valueBufferView.byteOffset + valueAccessor.byteOffset, std::fstream::beg);
float* valueData = nullptr;
if (channel.target_path == "rotation") {
valueData = new float[valueAccessor.count * 4];
binary.read((char*)valueData, sizeof(float) * valueAccessor.count * 4);
} else {
valueData = new float[valueAccessor.count * 3];
binary.read((char*)valueData, sizeof(float) * valueAccessor.count * 3);
}
std::shared_ptr<Import::AnimationData> data;
if (mAnimation->data.find(channel.target_node) != mAnimation->data.end()) {
data = mAnimation->data[channel.target_node];
} else {
data = std::make_shared<Import::AnimationData>();
mAnimation->data[channel.target_node] = data;
}
if (channel.target_path == "rotation") {
for (int i = 0; i < timeAccessor.count; i++) {
data->rotations[timeData[i]] = glm::quat(valueData[i * 4 + 3], valueData[i * 4], valueData[i * 4 + 1], valueData[i * 4 + 2]);
}
} else if (channel.target_path == "translation") {
for (int i = 0; i < timeAccessor.count; i++) {
data->positions[timeData[i]] = glm::vec3(valueData[i * 3], valueData[i * 3 + 1], valueData[i * 3 + 2]);
}
} else if (channel.target_path == "scale") {
for (int i = 0; i < timeAccessor.count; i++) {
data->scale[timeData[i]] = glm::vec3(valueData[i * 3], valueData[i * 3 + 1], valueData[i * 3 + 2]);
}
}
delete[] timeData;
delete[] valueData;
}
model->animations.push_back(mAnimation);
}
}
void GltfImporter::calculateTangent(Import::Model* model)
{
for (auto& meshId : model->meshes) {
for (auto& it : meshId.second) {
if (it->hasTangent) {
for (int i = 0; i < it->indices.size(); i++) {
it->vertices[it->indices[i]].bitangent = glm::cross(it->vertices[it->indices[i]].normal, it->vertices[it->indices[i]].tangent);
}
}
else {
for (int i = 0; i < it->indices.size() - 2; i += 3) {
vertex& first = it->vertices[it->indices[i + 0]];
vertex& second = it->vertices[it->indices[i + 1]];
vertex& third = it->vertices[it->indices[i + 2]];
glm::vec3 edge1 = second.pos - first.pos;
glm::vec3 edge2 = third.pos - first.pos;
glm::vec2 uv1 = second.texCoord - first.texCoord;
glm::vec2 uv2 = third.texCoord - first.texCoord;
float f = 1.0f / uv1.x * uv2.y - uv2.x * uv1.y;
glm::vec3 tangent(
f * (uv2.y * edge1.x - uv1.y * edge2.x),
f * (uv2.y * edge1.y - uv1.y * edge2.y),
f * (uv2.y * edge1.z - uv1.y * edge2.z)
);
glm::vec3 bitangent(
f * (uv1.x * edge2.x - uv2.x * edge1.x),
f * (uv1.x * edge2.y - uv2.x * edge1.y),
f * (uv1.x * edge2.z - uv2.x * edge1.z)
);
first.tangent += tangent;
second.tangent += tangent;
third.tangent += tangent;
first.bitangent += bitangent;
second.bitangent += bitangent;
third.bitangent += bitangent;
}
}
for (auto& vertex : it->vertices) {
vertex.bitangent = glm::normalize(vertex.bitangent);
vertex.tangent = glm::normalize(vertex.tangent);
}
}
}
}
/**
* Creates hierarchy of nodes
*/
void GltfImporter::processHierarchy(Import::Model* model, const tinygltf::Model& gltfModel)
{
for (int i = 0; i < gltfModel.nodes.size(); i++) {
const tinygltf::Node& gltfNode = gltfModel.nodes[i];
std::shared_ptr<Import::Node> node = std::make_shared<Import::Node>();
node->id = i;
node->jointId = getJointByNode(node->id, gltfModel);
node->meshId = gltfNode.mesh;
node->childs = gltfNode.children;
node->name = gltfNode.name.size() > 0 ? gltfNode.name : ("Node " + std::to_string(nodeCounter++));
model->nodes.push_back(node);
getTransformMatrix(gltfNode, node);
}
}
int GltfImporter::getSkinByMesh(int mesh, const tinygltf::Node& node, const tinygltf::Model& model)
{
if (node.mesh == mesh) {
return node.skin;
}
if (node.children.size() == 0) {
return -1;
} else {
int result = -1;
for (auto it : node.children) {
result = getSkinByMesh(mesh, model.nodes[it], model);
if (result >= 0) {
return result;
}
}
return -1;
}
}
std::string GltfImporter::getBinaryFileFolder(std::string gltfFilePath) {
std::replace(gltfFilePath.begin(), gltfFilePath.end(), '\\', '/');
gltfFilePath = trimToLastLineEntry(gltfFilePath.c_str(), '/');
return gltfFilePath;
}
int GltfImporter::getJointByNode(int nodeId, const tinygltf::Model& gltfModel) {
if (gltfModel.skins.size() == 0) {
return -1;
}
const std::vector<int>& joints = gltfModel.skins[0].joints;
int lastJointId = 0;
for (int i = 0; i < joints.size(); i++) {
if (joints[i] == nodeId) return i;
}
return -1;
}
int GltfImporter::getNodeByJoint(int jointId, const tinygltf::Model& gltfModel)
{
const std::vector<int>& joints = gltfModel.skins[0].joints;
if (jointId < joints.size()) {
return joints[jointId];
}
return -1;
}
void GltfImporter::getTransformMatrix(const tinygltf::Node& modelNode, const std::shared_ptr<Import::Node>& node)
{
if (modelNode.matrix.data()) {
glm::mat4 transform = glm::mat4(
modelNode.matrix[0], modelNode.matrix[1], modelNode.matrix[2], modelNode.matrix[3],
modelNode.matrix[4], modelNode.matrix[5], modelNode.matrix[6], modelNode.matrix[7],
modelNode.matrix[8], modelNode.matrix[9], modelNode.matrix[10], modelNode.matrix[11],
modelNode.matrix[12], modelNode.matrix[13], modelNode.matrix[14], modelNode.matrix[15]
);
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(transform, node->scale, node->rotation, node->translation, skew, perspective);
} else {
if (modelNode.translation.size() > 0) {
node->translation = glm::vec3(modelNode.translation[0], modelNode.translation[1], modelNode.translation[2]);
}
if (modelNode.rotation.size() > 0) {
node->rotation = glm::quat((float)modelNode.rotation[3], (float)modelNode.rotation[0], (float)modelNode.rotation[1], (float)modelNode.rotation[2]);
}
if (modelNode.scale.size() > 0) {
node->scale = glm::vec3(modelNode.scale[0], modelNode.scale[1], modelNode.scale[2]);
}
}
}
bool GltfImporter::hasMesh(const tinygltf::Node& node, const tinygltf::Model& model)
{
if (node.mesh >= 0) {
return true;
}
if (node.children.size() == 0) {
return false;
}
for (auto& child : node.children) {
if (hasMesh(model.nodes[child], model)) {
return true;
}
}
return false;
}
| true |