blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
293b0b025b22c36043cfe8b391843eaa9e74290d
da52e4595d0dd93054362bdb66136bbaa8d0afa5
/old/oSpy/Agent/ObsoleteCode/hooks.h
a4d07346590439c54217624f2ddb468b916c69d1
[]
no_license
lupier/ospy
3edecb7f893944a8b134396d0673c053bced2319
9a6cb0dcc0f91087acdfc84de4c0d0f5bb5b71ca
refs/heads/master
2021-01-10T07:43:08.831867
2019-11-24T09:20:40
2019-11-24T09:20:40
43,726,097
1
0
null
2019-11-24T09:20:41
2015-10-06T02:34:42
C#
ISO-8859-15
C++
false
false
1,229
h
hooks.h
// // Copyright (c) 2006-2007 Ole André Vadla Ravnås <oleavr@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #pragma once class CHookContext; extern CHookContext g_getaddrinfoHookContext; extern CHookContext g_recvHookContext; extern CHookContext g_sendHookContext; extern CHookContext g_connectHookContext; extern CHookContext g_encryptMessageHookContext; extern CHookContext g_decryptMessageHookContext; void hook_kernel32(); void hook_winsock(); void hook_secur32(); void hook_crypt(); void hook_wininet(); void hook_httpapi(); void hook_activesync(); void hook_msn();
8b033c93993f967645a1e67c8591ecd0320fdc1f
ec2f343b988bb87e472817d078e5efbebae88016
/QtTestClient/statupdate/statchargeitem.cpp
8612c8b62286b6cf44312ff45afd89a6274b3cf8
[]
no_license
kihaseet/Alien
a1e9e8312a94733855fc2684f2ad0780eaaadf94
7f5fd769e0c48a59f3e8d6160fad92041687192b
refs/heads/master
2021-01-22T20:29:08.839667
2016-02-21T21:31:36
2016-02-21T21:31:36
25,159,489
0
0
null
2015-11-11T20:30:29
2014-10-13T13:22:00
C++
UTF-8
C++
false
false
635
cpp
statchargeitem.cpp
#include "statchargeitem.h" StatChargeItem::StatChargeItem(Item item) { this->item = item; } StatChargeItem::StatChargeItem(const StatChargeItem &s) { this->item = s.item; } void StatChargeItem::apply(CurrentPlayer &player) const { auto items = player.getItems(); for (Item& _item: items) { if (_item.getType() == this->item.getType()) { if (_item.getType() != ItemType::IT_BADGE) { _item.setChargeLevel(-1); } else { _item.setChargeLevel(2); } } } player.setItems(items); }
58f5fbd80a4480bf4c14052e37784be583b201b8
47d609bb14ac2e939f213711d95d9bc8dbb551d6
/ArduNano_OLEDDisplay/ArduNano_OLEDDisplay.ino
e438e5c2aee3c43399db84c39d0e6318f93f7b72
[]
no_license
pejan-ocz/PJ-Arduino-Display
b2d51bf8c1bc4518b25b674a5ab19ae86d9290f2
b90663a45cc7cdf051faac209aa701b43f2b6772
refs/heads/master
2021-01-19T19:13:44.297415
2017-04-17T23:16:53
2017-04-17T23:16:53
88,406,807
0
0
null
null
null
null
UTF-8
C++
false
false
1,514
ino
ArduNano_OLEDDisplay.ino
// OLED displej přes I2C řadič SSD1306 // připojení knihovny U8glib #include "U8glib.h" // Hello World - for use with Monochrome OLEDs //************************************************** // inicializace OLED displeje z knihovny U8glib // Change this constructor to match your display!!! //U8GLIB_SSD1306_128X64 mujOled(U8G_I2C_OPT_NONE); U8GLIB_SSD1306_ADAFRUIT_128X64 mujOled(U8G_I2C_OPT_NONE); //konečně funkční //************************************************** uint8_t pozice = 0; //pro rolování textu void setup() { // put your setup code here, to run once: mujOled.setFont(u8g_font_unifont); mujOled.setColorIndex(1); // Instructs the display to draw with a pixel on. } void loop() { // put your main code here, to run repeatedly: mujOled.firstPage(); do { draw(); } while( mujOled.nextPage() ); delay(500); } void draw(){ // nastavení písma, toto písmo umožní vypsat // přibližně 15x4 znaků mujOled.setFont(u8g_font_unifont); // nastavení pozice výpisu v pixelech // souřadnice jsou ve tvaru x, y // souřadnice 0, 0 je v levém horní rohu // OLED displeje, maximum je 128, 64 mujOled.setPrintPos(5, 30); // výpis textu na zadanou souřadnici //mujOled.println("- Arduino test -"); mujOled.print("2017"); mujOled.drawStr( 5, 60, "Test"); mujOled.drawCircle(60, 30, 10); mujOled.drawDisc(80, 30, 10); mujOled.drawLine(90, 20, 110, 40); mujOled.drawBox(50, 50, 20, 10); mujOled.drawFrame(1, 1, 127, 63); }
a4149486783ecad1d1024e22f27bf988eabaf9d1
1a747b63129a60390005837279778d821cf3837d
/StringAndFormatting/CaseTest.cpp
99d15c65996c121e2471220d181f978d75789f12
[]
no_license
zgglj2/PocoStudy
53b3b2bd40b12da7f3f71bbd729022fdc168e882
05b9fc08e4a3fb0dc0a1069aa66f71d1ad4bacbb
refs/heads/master
2021-06-24T07:37:09.188997
2020-12-26T14:44:28
2020-12-26T14:44:28
84,742,840
2
0
null
null
null
null
UTF-8
C++
false
false
547
cpp
CaseTest.cpp
#include <iostream> #include "Poco/String.h" using Poco::toUpper; using Poco::toLower; using Poco::toUpperInPlace; using Poco::toLowerInPlace; using Poco::icompare; int main(int argc, char **argv) { std::string hello("Hello world!!!"); std::string s1(toUpper(hello)); std::cout << "toUpper s1:" << s1 << std::endl; toLowerInPlace(s1); std::cout << "toLowerInPlace s1:" << s1 << std::endl; std::cout << icompare(hello, s1) << std::endl; std::cout << icompare(hello, "Hello universal") << std::endl; return 0; }
68cc2a66dad89bc15620030ccd92974bd1d84b19
b34c187e5d1cbb6f72ca65c5a3830de5193059e1
/Day18/SudokuBuild/NorvigSudoku.hpp
f90d29568b8711625b09083ec8c81d144b053a5a
[]
no_license
carllevin/CML_CPP_bootcamp
9fc682b9f2688a2d02b4e2d6ef176cb7a34a1a7d
175b37ce52460cb98bccc53a84d318fb63a6e9fd
refs/heads/main
2023-08-25T05:28:03.685494
2021-11-02T15:47:14
2021-11-02T15:47:14
416,713,305
0
0
null
null
null
null
UTF-8
C++
false
false
1,582
hpp
NorvigSudoku.hpp
#ifndef NORVIGSUDOKU_HPP #define NORVIGSUDOKU_HPP #include <iostream> #include <fstream> #include<sstream> #include<vector> #include <algorithm> #include <iomanip> #include <chrono> #define GRID_FULL std::make_pair(10, 10) extern int numberOfGuesses; class Square{ public: std::vector<int> possibleValues; int commitVal; Square(){ possibleValues.assign({1,2,3,4,5,6,7,8,9}); this->commitVal = 0; } void removePossibleValue(int value){ possibleValues.erase(std::remove(possibleValues.begin(), possibleValues.end(), value), possibleValues.end()); }; void printPossibleValues(); void commitValue(int value){ this->commitVal = value; this->possibleValues.clear(); } int getCommitValue(){ return commitVal; } int getNumberOfPossibles(){ return possibleValues.size(); }; }; bool used_in_row(Square **grid, const int row, const int value); bool used_in_col(Square **grid, const int col, const int value); bool used_in_box(Square **grid, const int box_start_rpw, const int box_start_col, const int value); bool isSafe(Square **grid, const int row, const int col, const int num); bool checkForUniqueInUnits(Square **grid, const int baseRow, const int baseCol); bool removeInPeers(Square **grid, const int baseRow, const int baseCol, const int value); std::pair<int, int> getLocationOfLeastPossibles(Square **grid); bool guessSudoku(Square **grid); #endif // NORVIGSUDOKU_HPP
70247b5ef63fae6f4faf623b01ff462d5d29ab49
987b43cb95103fe3af35e8756c29aee7f3c7a07c
/include/RE/B/BSMemStorage.h
cca40e0f66ff881048567e5ace684eac4b500a08
[ "MIT" ]
permissive
powerof3/CommonLibSSE
29e6017c8bae90665db4d30318ee66fd19e6c139
ff2afeaf5d6f6cac4c5b7cb1caaa2e0d89713393
refs/heads/dev
2023-08-31T05:15:02.732037
2023-08-21T09:52:55
2023-08-21T09:52:55
374,565,412
38
26
MIT
2023-09-10T13:09:57
2021-06-07T06:55:35
C++
UTF-8
C++
false
false
984
h
BSMemStorage.h
#pragma once #include "RE/B/BSStorage.h" namespace RE { class Win32FileType; class BSMemStorage : public BSStorage { public: inline static auto RTTI = RTTI_BSMemStorage; inline static auto VTABLE = VTABLE_BSMemStorage; ~BSMemStorage() override; // 00 // override BSStorage std::size_t GetSize() const override; // 01 std::size_t GetPosition() const override; // 02 BSStorageDefs::ErrorCode Seek(std::size_t a_offset, BSStorageDefs::SeekMode a_seekMode) const override; // 03 BSStorageDefs::ErrorCode Read(std::size_t a_numBytes, std::byte* a_bytes) const override; // 04 BSStorageDefs::ErrorCode Write(std::size_t a_numBytes, const std::byte* a_bytes) override; // 05 // members Win32FileType* file; // 20 std::uint64_t unk28; // 28 }; static_assert(sizeof(BSMemStorage) == 0x30); }
660a7acaab1f885dc7d5eed0aadeb8282ab66ef0
fe8eaf2f1b229b982febd3d9dc79e6c63b16a159
/Octree.txt
01d51660d3b418e91ecba7a542523e0c6ba2ec2e
[]
no_license
PieterMarius/PhysicsEngine
e48cd68e3d2fcf3b479506de2b5ba51311970242
147a9b991947989f41f6c8d0070399052c7ac6c6
refs/heads/master
2021-08-30T08:29:01.612072
2019-12-20T16:25:59
2019-12-20T16:25:59
51,477,497
0
0
null
2021-08-04T21:24:22
2016-02-10T22:32:49
C#
UTF-8
C++
false
false
11,706
txt
Octree.txt
// COTD Entry submitted by Paul Nettle [midnight@FluidStudios.com] // Corresponds with an Ask MidNight response (http://www.flipcode.com/askmid/) // ----------------------------------------------------------------------------- // This defines a callback for traversal // ----------------------------------------------------------------------------- class Octree; typedef bool (*callback)(const Octree &o, void *data); // ----------------------------------------------------------------------------- // This defines a point class (it's incomplete, but the data elements are there) // ----------------------------------------------------------------------------- class Point { public: double x, y, z; // Position double n; // User's unique identifier unsigned int code; // Used during octree generation // Insert typical operators, such as *, +, -, etc. }; // ----------------------------------------------------------------------------- // This defines a cubic bounding volume (center, radius) // ----------------------------------------------------------------------------- typedef struct { Point center; // Center of a cubic bounding volume double radius; // Radius of a cubic bounding volume } Bounds; // ----------------------------------------------------------------------------- // The octree class -- almost real code! // ----------------------------------------------------------------------------- class Octree { public: // Construction/Destruction Octree(); virtual ~Octree(); // Accessors inline const Point * const * points() const {return _points;} inline const unsigned int pointCount() const {return _pointCount;} // Implementation virtual const bool build(Point **points, const unsigned int count, const unsigned int threshold, const unsigned int maximumDepth, const Bounds &bounds, const unsigned int currentDepth = 0); static const Bounds calcCubicBounds(const Point * const * points, const unsigned int count); virtual const bool traverse(callback proc, void *data) const; protected: Octree *_child[8]; unsigned int _pointCount; Point **_points; Point _center; double _radius; }; // ----------------------------------------------------------------------------- // Construction -- Just "nullify" the class // ----------------------------------------------------------------------------- Octree::Octree() : _pointCount(0), _points(NULL), _center(0,0,0,0), _radius(0.0) { memset(_child, 0, sizeof(_child)); } // ----------------------------------------------------------------------------- // Destruction -- free up memory // ----------------------------------------------------------------------------- Octree::~Octree() { delete[] _points; } // ----------------------------------------------------------------------------- // Build the octree // ----------------------------------------------------------------------------- const bool Octree::build(Point **points, const unsigned int count, const unsigned int threshold, const unsigned int maximumDepth, const Bounds &bounds, const unsigned int currentDepth) { // You know you're a leaf when... // // 1. The number of points is <= the threshold // 2. We've recursed too deep into the tree // (currentDepth >= maximumDepth) // // NOTE: We specifically use ">=" for the depth comparison so that we // can set the maximumDepth depth to 0 if we want a tree with // no depth. if (count <= threshold || currentDepth >= maximumDepth) { // Just store the points in the node, making it a leaf _pointCount = count; _points = new Point *[count]; memcpy(_points, points, sizeof(Point *) * count); return true; } // We'll need this (see comment further down in this source) unsigned int childPointCounts[8]; // Classify each point to a child node for (unsigned int i = 0; i < count; i++) { // Current point Point &p = *points[i]; // Center of this node const Point &c = bounds.center; // Here, we need to know which child each point belongs to. To // do this, we build an index into the _child[] array using the // relative position of the point to the center of the current // node p.code = 0; if (p.x > c.x) p.code |= 1; if (p.y > c.y) p.code |= 2; if (p.z > c.z) p.code |= 4; // We'll need to keep track of how many points get stuck in each // child so we'll just keep track of it here, since we have the // information handy. childPointCounts[p.code]++; } // Recursively call build() for each of the 8 children for (i = 0; i < 8; i++) { // Don't bother going any further if there aren't any points for // this child if (!childPointCounts[i]) continue; // Allocate the child _child[i] = new Octree; // Allocate a list of points that were coded JUST for this child // only Point **newList = new Point *[childPointCounts[i]]; // Go through the input list of points and copy over the points // that were coded for this child Point **ptr = newList; for (unsigned int j = 0; j < count; j++) { if (points[j]->code == i) { *ptr = points[j]; ptr++; } } // At this point, we have a list of points that will belong to // this child node. We'll want to remove any point with a // duplicate 'n' in them... // // [We won't need to reallocate the list, since it's temporary] int newCount = 0; for (j = 0; j < childPointCounts[i]; j++) { // Remove duplicates from newList // ... // Keep track of the new count in 'newCount' } // Generate a new bounding volume -- We do this with a touch of // trickery... // // We use a table of offsets. These offsets determine where a // node is, relative to it's parent. So, for example, if want to // generate the bottom-left-rear (-x, -y, -z) child for a node, // we use (-1, -1, -1). // // However, since the radius of a child is always half of its // parent's, we use a table of 0.5, rather than 1.0. // // These values are stored the following table. Note that this // won't compile because it assumes Points are structs, but you // get the idea. Point boundsOffsetTable[8] = { {-0.5, -0.5, -0.5}, {+0.5, -0.5, -0.5}, {-0.5, +0.5, -0.5}, {+0.5, +0.5, -0.5}, {-0.5, -0.5, +0.5}, {+0.5, -0.5, +0.5}, {-0.5, +0.5, +0.5}, {+0.5, +0.5, +0.5} }; // Calculate our offset from the center of the parent's node to // the center of the child's node Point offset = boundsOffsetTable[i] * bounds.radius; // Create a new Bounds, with the center offset and half the // radius Bounds newBounds; newBounds.radius = bounds.radius * 0.5; newBounds.center = bounds.center + offset; // Recurse _child[i]->build(newList, newCount, threshold, maximumDepth, newBounds, currentDepth+1); // Clean up delete[] newList; } return true; } // ----------------------------------------------------------------------------- // Determine the [cubic] bounding volume for a set of points // ----------------------------------------------------------------------------- const Bounds Octree::calcCubicBounds(const Point * const * points, const unsigned int count) { // What we'll give to the caller Bounds b; // Determine min/max of the given set of points Point min = *points[0]; Point max = *points[0]; for (unsigned int i = 1; i < count; i++) { const Point &p = *points[i]; if (p.x < min.x) min.x = p.x; if (p.y < min.y) min.y = p.y; if (p.z < min.z) min.z = p.z; if (p.x > max.x) max.x = p.x; if (p.y > max.y) max.y = p.y; if (p.z > max.z) max.z = p.z; } // The radius of the volume (dimensions in each direction) Point radius = max - min; // Find the center of this space b.center = min + radius * 0.5; // We want a CUBIC space. By this, I mean we want a bounding cube, not // just a bounding box. We already have the center, we just need a // radius that contains the entire volume. To do this, we find the // maxumum value of the radius' X/Y/Z components and use that b.radius = radius.x; if (b.radius < radius.y) b.radius = radius.y; if (b.radius < radius.z) b.radius = radius.z; // Done return b; } // ----------------------------------------------------------------------------- // Generic tree traversal // ----------------------------------------------------------------------------- const bool Octree::traverse(callback proc, void *data) const { // Call the callback for this node (if the callback returns false, then // stop traversing. if (!proc(*this, data)) return false; // If I'm a node, recursively traverse my children if (!_pointCount) { for (unsigned int i = 0; i < 8; i++) { // We store incomplete trees (i.e. we're not guaranteed // that a node has all 8 children) if (!_child[i]) continue; if (!_child[i]->traverse(proc, data)) return false; } } return true; }
bb2bd1b8b2fade4d5463386b45f7f5a761c9659e
80bc696dfcf4ce57059b952b4ed36cba288c3ae0
/CIE205Project_Code_S2021/Enemies/Enemy.cpp
8a4fbb78bfdbcb3903b3ae6548503e82bfb37d9d
[]
no_license
HossamAshraf10/Battle
4f93a3c80593c4ad35eac13ac6c51a79f2eb8913
2f3e3e4c59c046cf08def260ec82596735688cb3
refs/heads/main
2023-05-23T23:52:16.337818
2021-06-16T14:41:07
2021-06-16T14:41:07
377,200,095
0
0
null
2021-06-16T10:36:07
2021-06-15T14:54:49
C
UTF-8
C++
false
false
801
cpp
Enemy.cpp
#include "Enemy.h" Enemy::Enemy(int id, ENMY_TYPE type, int arrTime, double health, int power, int reload, int speed, int distance) { SetID(id); SetType(type); SetArrvTime(arrTime); this->maxHealth = health; SetHealth(health); SetPower(power); SetReload(reload); SetSpeed(speed); SetDistance(distance); SetStatus(INAC); // FirstShotTime = -1; KillTime = -1; waitTillNextShot = reload; } Enemy::~Enemy() { } bool Enemy::isInReloadPeriod() { waitTillNextShot++; return !(waitTillNextShot == reload + 1); //not ready to act } bool Enemy::operator>(Enemy* other) { return this->priority > other->GetPriority(); } bool Enemy::operator>=(Enemy* other) { return this->priority >= other->GetPriority(); } void Enemy::DecrementDist() { if (Distance > MinDistance) Distance--; }
4b7d5b60c4ed2d3df85defbd5aff4f3e06ca9598
1a5242c246f80201231b05856dcd1db84b80ae6c
/C++/DataStructures/LinkedList/ConvertSinglyLinkedListToCircularLinkedList.cpp
fb8dc12e097b1568608cd8d751107e75c5e8cfc2
[]
no_license
andresfe24/Coding
5690cffa1bc253d26e82c0be0907ffccdce20a21
7b0a24ce3a4e279d36f9cda38db3fd96ca1067b7
refs/heads/master
2021-01-19T20:02:42.928802
2019-04-11T23:46:46
2019-04-11T23:46:46
75,341,140
0
0
null
null
null
null
UTF-8
C++
false
false
2,312
cpp
ConvertSinglyLinkedListToCircularLinkedList.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: andresfe24 * * Created on September 22, 2017, 8:32 PM * * Description: Convert singly linked list to circular linked list */ /* Include Libraries */ #include <cstdlib> #include <iostream> /* Data Structures */ struct Node { int data; struct Node* next; }; /* Methods */ /* * \brief Convert singly linked list to circular linked list */ struct Node* circular(struct Node* head) { /* Start node */ struct Node* start = head; /* Find end of linked list */ while (head->next != NULL) { head = head->next; } /* Point last node to first */ head->next = start; /* Return start of circular linked list */ return start; } /* * \brief Push node to beginning of linked list */ void push(struct Node** head, int data) { /* Allocate memory for new node */ struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); /* Assign new node */ newNode->data = data; newNode->next = (*head); /* head becomes the new node */ (*head) = newNode; } /* * \brief Print circular linked list */ void PrintCircularLinkedList(struct Node* head) { /* Check that head is not null */ if (head == NULL) { std::cout << "Head is null" << std::endl; return; } /* Save head to check when the search has reached the beginning */ struct Node* start = head; /* Print linked list */ std::cout << "Circular linked list:" << std::endl; while (head->next != start) { std::cout << head->data << std::endl; head = head->next; } /* Print last node */ std::cout << head->data << std::endl; } /* * \brief Main method */ int main(int argc, char** argv) { /* Define head node */ struct Node* head = NULL; /* Push nodes */ // 1->2->3->4->5 push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); /* Make list circular */ circular(head); /* Print circular linked list */ PrintCircularLinkedList(head); return 0; }
b2e4bbb6189356d9b64158e39dd81972ea4b9945
8f466a357ff704373c2e8c5d0f06fa86b0e6e71d
/PhysicsEngine/cRigidBody.cpp
74b59c9de3f595e8f92b85b135a2c44982d42a28
[]
no_license
Richard-ML/Uber_Game_Engine
26be718dc2c3e700a84a5e843bdc67b945bf65d9
dbbde71fe3d8c82e053c8a291eb93c686f9ab3fe
refs/heads/master
2021-09-14T12:33:05.808807
2017-05-03T03:12:16
2017-05-03T03:12:16
77,706,695
1
0
null
null
null
null
UTF-8
C++
false
false
1,971
cpp
cRigidBody.cpp
#include "stdafx.h" #include "cRigidBody.h" PhysicsEngine::cRigidBody::cRigidBody(const sRigidBody & rigidBody) { m_rigidBody = rigidBody; } PhysicsEngine::cRigidBody::~cRigidBody() { } void PhysicsEngine::cRigidBody::getOrientation(glm::mat4 & orientation) { glm::mat3 RotationMatrix = glm::transpose(glm::lookAt(glm::vec3(0.0f), glm::normalize(this->m_rigidBody.velocity), glm::vec3(0.0f, 1.0f, 0.0f))); orientation = RotationMatrix; } void PhysicsEngine::cRigidBody::getPosition(glm::vec3 & position) { position = m_rigidBody.position; } void PhysicsEngine::cRigidBody::setPosition(const glm::vec3 & position) { m_rigidBody.position = position; } void PhysicsEngine::cRigidBody::getVelocity(glm::vec3 & velocity) { velocity = m_rigidBody.velocity; } void PhysicsEngine::cRigidBody::setVelocity(const glm::vec3 & velocity) { m_rigidBody.velocity = velocity; } void PhysicsEngine::cRigidBody::getMass(float & mass) { mass = m_rigidBody.mass; } void PhysicsEngine::cRigidBody::setMass(const float & mass) { m_rigidBody.mass = mass; } void PhysicsEngine::cRigidBody::getAcceleration(glm::vec3 & acceleration) { acceleration = m_rigidBody.acceleration; } void PhysicsEngine::cRigidBody::setAcceleration(const glm::vec3 & acceleration) { m_rigidBody.acceleration = acceleration; } PhysicsEngine_API void PhysicsEngine::cRigidBody::applyForce(const glm::vec3 velocity) { this->m_rigidBody.velocity += velocity; } PhysicsEngine_API void PhysicsEngine::cRigidBody::isCollision( bool& collision) { collision = this->m_rigidBody.collision; } PhysicsEngine_API void PhysicsEngine::cRigidBody::setCollision(bool & collision) { this->m_rigidBody.collision = collision; } //void PhysicsEngine::cRigidBody::translate(glm::vec3 & translation) //{ //} //glm::mat4 PhysicsEngine::cRigidBody::getTransform() //{ // glm::mat4 matrix = glm::translate(matrix, m_position); // matrix *= glm::eulerAngleXYZ(m_angle.x, m_angle.y, m_angle.z); // return matrix; //}
8699286c296cd2c71e570c2f6572d7f05d281c8c
5d6f3330bc5699134eacaf46267feab9708ddb19
/webrtc-jni/src/main/cpp/include/media/Device.h
f51d501455f0bf6097f9857d1f1f18a3495f0108
[ "BSD-3-Clause", "DOC", "LicenseRef-scancode-html5", "Apache-2.0" ]
permissive
devopvoid/webrtc-java
ca0549864591e000a63ed95055646ed54264426c
682a40187f653613eefb0a51ac4337781ce15ff6
refs/heads/master
2023-05-02T11:06:46.538322
2023-01-16T17:04:54
2023-01-16T17:04:54
224,890,850
203
56
Apache-2.0
2023-01-01T20:41:51
2019-11-29T16:41:25
C++
UTF-8
C++
false
false
1,583
h
Device.h
/* * Copyright 2019 Alex Andres * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef JNI_WEBRTC_MEDIA_DEVICE_H_ #define JNI_WEBRTC_MEDIA_DEVICE_H_ #include "JavaClass.h" #include "JavaRef.h" #include <jni.h> #include <string> #include <memory> namespace jni { namespace avdev { class Device { public: virtual ~Device() {}; virtual bool operator==(const Device & other); virtual bool operator!=(const Device & other); virtual bool operator<(const Device & other); std::string getName() const; std::string getDescriptor() const; protected: Device(std::string name, std::string descriptor); private: const std::string name; const std::string descriptor; }; using DevicePtr = std::shared_ptr<Device>; } namespace Device { class JavaDeviceClass : public JavaClass { public: explicit JavaDeviceClass(JNIEnv * env); jclass cls; jmethodID ctor; jfieldID name; jfieldID descriptor; }; JavaLocalRef<jobject> toJavaDevice(JNIEnv * env, avdev::DevicePtr device); } } #endif
2b9333967fb5cfa3349a7f7ad0ad6119dd4b1733
74899b133bb4b0dd704b1645ba28dd33c30261ef
/Geant4/in-readout1/include/myActionInitialization.hh
901f2c508342483f87e2b973ce58c3e6ec6d34fc
[]
no_license
hpmouse523/CEPC
003223c0c5ce356087112cb19b74ce3b4a9b6180
d9ee3a5e1b2df838f6a636e7c8ec42089a2c6982
refs/heads/master
2021-01-21T20:33:20.167012
2017-06-15T01:54:02
2017-06-15T01:54:02
92,246,428
0
0
null
null
null
null
UTF-8
C++
false
false
487
hh
myActionInitialization.hh
#ifndef myActionInitialization_h #define myActionInitialization_h 1 #include "G4VUserActionInitialization.hh" #include "myDetectorConstruction.hh" class myActionInitialization : public G4VUserActionInitialization { public: myActionInitialization( myDetectorConstruction *); virtual ~myActionInitialization(); public: virtual void BuildForMaster() const override; virtual void Build() const override; private: myDetectorConstruction *detector; }; #endif
815fa0fdfdd1b0d7fa1a0d8617955f4905ae7a3f
691f9eb723ee76f734ea5f423ef6cb9406d30434
/src/df_factory.h
4eb83b03a8636d9c9f4cd7f73befbe40e32d9052
[]
no_license
lwang-astro/Agama
1b1a9c8c8abdf3530f76d9027c52c8355aec8c4c
2a067b69a969aabbc793446437f399329a5c83f4
refs/heads/master
2021-06-23T19:21:38.644442
2017-08-21T17:16:15
2017-08-21T17:16:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,152
h
df_factory.h
/** \file df_factory.h \brief Creation of DistributionFunction instances \author EV \date 2015 */ #pragma once #include "df_base.h" #include "units.h" #include "smart.h" // forward declaration namespace utils { class KeyValueMap; } namespace df { /** A trivial collection of several distribution functions */ class CompositeDF: public BaseDistributionFunction{ public: CompositeDF(const std::vector<PtrDistributionFunction> &comps) : components(comps) {}; /// the number of components in this composite DF unsigned int size() const { return components.size(); } /// pointer to the given component PtrDistributionFunction component(unsigned int index) const { return components.at(index); } /// the value of a composite DF is simply the sum of values of all its components virtual double value(const actions::Actions &J) const { double sum=0; for(unsigned int i=0; i<components.size(); i++) sum += components[i]->value(J); return sum; } private: std::vector<PtrDistributionFunction> components; }; /** Create an instance of distribution function according to the parameters contained in the key-value map. \param[in] params is the list of parameters (pairs of "key" and "value" strings). \param[in] potential is the instance of global potential, required by some of the DF classes at construction (it is not stored in the DF but only used to initialize internal interpolation tables); may pass an empty pointer if the DF does not need it. \param[in] converter is the unit converter for transforming the dimensional quantities in parameters into internal units; can be a trivial converter. \return a new instance of shared pointer to BaseDistributionFunction on success. \throws std::invalid_argument or std::runtime_error or other df-specific exception on failure. */ PtrDistributionFunction createDistributionFunction( const utils::KeyValueMap& params, const potential::BasePotential* potential = NULL, const units::ExternalUnits& converter = units::ExternalUnits()); }; // namespace
4a1b2cc8ee53aa0cc2681aecf86adc8e29f43354
665813341b9d0911aaab3658c38b495ff1dae30a
/AOJ/ITP1/9/Shuffle.cpp
9a2d6c70f032ac5861a8a8de89cc39bb6a0975f9
[]
no_license
THEToilet/program
1fd54802d8e90ae648a50685d2ff8ee1838ebeb9
30b13449e114849981f832a6360dd0ab702682d1
refs/heads/master
2021-12-22T07:14:47.025845
2021-12-19T17:10:29
2021-12-19T17:10:29
243,990,671
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
Shuffle.cpp
#include <bits/stdc++.h> using namespace std; int main() { string s = ""; int m, h; cin >> s; while (s != "-") { cin >> m; for (int i = 0; i < m; i++) { cin >> h; for (int j = 0; j < h; j++) { char g = s.at(0); s = s.substr(1, s.size() - 1) + g; } } cout << s << endl; cin >> s; } }
6b25be936f59f1af1abaa619fd5e4344217975b4
20484b9f9fa9da67ddc2cd062ae2290b2bee996f
/assignment-1/answer2.cpp
aba769c8d4784b3486d628b66befd6538ed4fee3
[]
no_license
tewarig/OOP-With-CPP-assignments
c0e2e18cc57b778d29bf1cf461c1ce58edd3ed38
366cf545a36dffa055e444886c821cdb35d71416
refs/heads/master
2023-01-01T07:34:10.379809
2020-10-22T16:39:27
2020-10-22T16:39:27
282,418,719
2
1
null
null
null
null
UTF-8
C++
false
false
1,170
cpp
answer2.cpp
//To find 2nd max and 2nd min number from an integer array. #include <iostream> using namespace std; #define INT_MAX -2147483647 #define INT_MIN 2147483647 void secondnumber(int arr[] , int size){ int max = INT_MAX; int min = INT_MIN; int smin = INT_MIN; int smax = INT_MAX; for(int i=0;i<size;i++) { if(arr[i]<min) { min = arr[i]; } } for(int i=0;i<size;i++) { if(arr[i]<smin && arr[i]>min) { smin = arr[i]; } } for(int i=0;i<size;i++) { if(arr[i]>max) { max = arr[i]; } } cout<<max; for(int i=0;i<size;i++) { if(arr[i]>smax && arr[i]<max) { smax = arr[i]; } } cout<<"2nd max element: " <<smax<<"\n"; cout<<"2nd min element: " <<smin<<"\n"; } int main() { cout<<"Please enter the size of the array"<<"\n"; int size; cin>>size; int array[size]; cout<<"Enter array elements"<<"\n"; for(int i=0;i<size;i++) { cin>>array[i]; } secondnumber(array , size); return 0; }
b47137bf9ab7b2a70f121721d225243b17bc1304
2bf138c0ada9d577383eaf31a6183fd72e6acc05
/src/driver.cpp
f4eef1ea881ac03b003adf2e26063b137347f753
[]
no_license
chenjyr/AutonomousRobot
e8ae6e1a808d11f2c1df4bfb8b0886a759b3ce05
eef9e7034bd48b692611ce1b6962179f9bd363ff
refs/heads/master
2020-12-25T19:15:36.083873
2012-11-22T07:46:26
2012-11-22T07:46:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,135
cpp
driver.cpp
#include <cv.h> #include <cxcore.h> #include <highgui.h> #include <iostream> #include <stdio.h> #include "PathFinder.h" #include "My_GUI.h" using namespace std; int main(void) { int hsv_thresh[] = {25,135,135,35,215,215, 167,20,177,187,255,227, 40,20,150,80,170,250}; ImgProcessor * mImgPr = new ImgProcessor(); PathFinder * mPathFr = new PathFinder(mImgPr); My_GUI * mGUI = new My_GUI(mImgPr,mPathFr); mImgPr->start_getting(); mImgPr->start_processing(hsv_thresh); mImgPr->start_processing2(hsv_thresh); mGUI->start_updating(hsv_thresh); mPathFr->start_updating(); mImgPr->join_getting(); mImgPr->join_processing(); mImgPr->join_processing2(); mGUI->join_updating(); return 0; } /* #include <cv.h> #include <cxcore.h> #include <highgui.h> #include <iostream> #include <math.h> #include <string.h> #include <math.h> #include "serial.h" #include <stdio.h> #include <string> // for STL string class #include <windows.h> // for HANDLE #include <process.h> // for _beginthread() #include<TCHAR.h> #define pi 3.14159265 using namespace std; int main() { IplImage *frame = 0; CvCapture* capture = 0; CvSize size = cvSize(600,400); cvNamedWindow("FAG", CV_WINDOW_AUTOSIZE); while(1) { capture = cvCreateFileCapture("http://137.82.120.10:8008.mjpeg"); if (capture){break;} } // 160,130,150,255,190,190, 35,80,110,50,170,170}; int hue_b_low = 35; int sat_b_low = 80; int val_b_low = 50; int hue_b_high = 50; int sat_b_high = 200; int val_b_high = 200; char key = 0; cvDestroyWindow("Robot Front HSV"); cvDestroyWindow("Robot Back HSV"); cvNamedWindow("Tennis Ball HSV", CV_WINDOW_AUTOSIZE ); cvResizeWindow("Tennis Ball HSV", 650, 350); cvMoveWindow("Tennis Ball HSV", 0, 400); cvCreateTrackbar( "Ball HueL", "Tennis Ball HSV", &hue_b_low, 255, NULL); cvCreateTrackbar( "Ball SatL", "Tennis Ball HSV", &sat_b_low, 255, NULL); cvCreateTrackbar( "Ball ValL", "Tennis Ball HSV", &val_b_low, 255, NULL); cvCreateTrackbar( "Ball HueH", "Tennis Ball HSV", &hue_b_high, 255, NULL); cvCreateTrackbar( "Ball SatH", "Tennis Ball HSV", &sat_b_high, 255, NULL); cvCreateTrackbar( "Ball ValH", "Tennis Ball HSV", &val_b_high, 255, NULL); while (key!='q') { for(int i = 0 ; i <10; i++) frame = cvQueryFrame( capture ); if ( !frame ) continue; cvSetImageROI( frame, cvRect(160,0,420,480) ); cvSmooth( frame, frame,CV_GAUSSIAN,3,0); IplImage* imgHSV= cvCreateImage( cvGetSize(frame), 8, 3); IplImage* imgThreshed = cvCreateImage(cvGetSize(frame), 8, 1); cvCvtColor(frame, imgHSV, CV_BGR2HSV); cvInRangeS(imgHSV, cvScalar(hue_b_low, sat_b_low, val_b_low), cvScalar(hue_b_high, sat_b_high, val_b_high),imgThreshed); //ball - green cvShowImage("FAG", imgThreshed); cvWaitKey(1); } } */
a18ab01cc95a9bccd703d38ca4aae3ef853252a3
aa4e9d009bed4e9a8d9674bceae3bcd92309c385
/d00/ex01/Bills_PC.cpp
8248d15ba5ee9cf8cf3b4a2ac04dec16861c7bc5
[]
no_license
LeoTD/cpp-piscine
8b1d12070d1d58ba5f4a4548c840862e5ca511a9
6b0bce73758842f38bfa8cdef1de941073acadc1
refs/heads/master
2020-03-30T11:00:38.136992
2018-10-05T22:37:17
2018-10-05T22:37:17
151,148,713
0
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
Bills_PC.cpp
#include <Book.class.hpp> #include <Entry.class.hpp> #include <iostream> #include <string> void to_upper(std::string& str) { for (std::string::iterator i = str.begin(); i != str.end(); i++) { if (*i >= 'a' && *i <= 'z') { *i += ('A' - 'a'); } } } int main(void) { std::string buf; Book b; while (1) { std::cout << "-ϞϞ(๑⚈ ․̫ ⚈๑)∩> "; std::getline(std::cin, buf); to_upper(buf); if (buf == "ADD") { b.add_entry(); } else if (buf == "SEARCH") { b.search(); } else if (buf == "EXIT") { break ; } } }
fc5e13ac660c0da9ff68f5372742f8e6f292fddc
4a72c8a643170d2c6bd9b9cca3c8fa3ee65ffcc3
/common.cpp
00747ed035816f16412db332eab9c7ae1811d316
[ "MIT" ]
permissive
mc-imperial/get-image-egl
2ef6780da89b437de86e15680dabb74a97300362
55c756fe6e825c3a3f73553f47d576d2eb79b70a
refs/heads/master
2021-09-11T19:42:45.714285
2018-04-11T16:13:40
2018-04-11T16:13:40
87,563,840
1
0
null
null
null
null
UTF-8
C++
false
false
2,983
cpp
common.cpp
#include "common.h" #include <iostream> const char *gl_error_to_str(EGLint error){ switch(error){ case EGL_SUCCESS: return "EGL_SUCCESS"; case EGL_NOT_INITIALIZED: return "EGL_NOT_INITIALIZED"; case EGL_BAD_ACCESS: return "EGL_BAD_ACCESS"; case EGL_BAD_ALLOC: return "EGL_BAD_ALLOC"; case EGL_BAD_ATTRIBUTE: return "EGL_BAD_ATTRIBUTE"; case EGL_BAD_CONTEXT: return "EGL_BAD_CONTEXT"; case EGL_BAD_CONFIG: return "EGL_BAD_CONFIG"; case EGL_BAD_CURRENT_SURFACE: return "EGL_BAD_CURRENT_SURFACE"; case EGL_BAD_DISPLAY: return "EGL_BAD_DISPLAY"; case EGL_BAD_MATCH: return "EGL_BAD_MATCH"; case EGL_BAD_PARAMETER: return "EGL_BAD_PARAMETER"; case EGL_BAD_NATIVE_PIXMAP: return "EGL_BAD_NATIVE_PIXMAP"; case EGL_BAD_NATIVE_WINDOW: return "EGL_BAD_NATIVE_WINDOW"; case EGL_CONTEXT_LOST: return "EGL_CONTEXT_LOST"; default: return "BAD ERROR"; } } bool init_gl( const int width, const int height, EGLDisplay& display, EGLConfig& config, EGLContext& context, EGLSurface& surface ) { const EGLint config_attribute_list[] = { //EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RED_SIZE, 4, EGL_GREEN_SIZE, 4, EGL_BLUE_SIZE, 4, EGL_ALPHA_SIZE, 4, EGL_CONFORMANT, EGL_OPENGL_ES3_BIT, EGL_DEPTH_SIZE, 16, EGL_NONE }; const EGLint context_attrib_list[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE }; const EGLint pbuffer_attrib_list[] = { EGL_WIDTH, width, EGL_HEIGHT, height, EGL_TEXTURE_FORMAT, EGL_NO_TEXTURE, EGL_TEXTURE_TARGET, EGL_NO_TEXTURE, EGL_LARGEST_PBUFFER, EGL_TRUE, EGL_NONE }; display = eglGetDisplay(EGL_DEFAULT_DISPLAY); EGLint major; EGLint minor; if(eglInitialize(display, &major, &minor) == EGL_FALSE) { std::cerr << "eglInitialize failed with " << gl_error_to_str(eglGetError()) << std::endl; return false; } EGLint num_config; if(eglChooseConfig(display, config_attribute_list, &config, 1, &num_config) == EGL_FALSE) { std::cerr << "eglChooseConfig failed." << std::endl; return false; } if(num_config != 1) { std::cerr << "eglChooseConfig did not return 1 config." << std::endl; return false; } context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attrib_list); if(context == EGL_NO_CONTEXT) { std::cerr << "eglCreateContext failed: " << std::hex << eglGetError() << std::endl; return false; } surface = eglCreatePbufferSurface(display, config, pbuffer_attrib_list); if(surface == EGL_NO_SURFACE) { std::cerr << "eglCreatePbufferSurface failed: " << std::hex << eglGetError() << std::endl; return false; } eglMakeCurrent(display, surface, surface, context); return true; }
5c70f1aedf56b794976a5f596e999b3f307c3fca
24643916cd1515911b7837ce81ebd17b0890cc81
/frameworks-ext/av/media/libstagefright/MtkAACExtractor.cpp
351ab97d0714b9dad94be72d1a119ae8e9b4f9a5
[ "Apache-2.0" ]
permissive
touxiong88/92_mediatek
3a0d61109deb2fa77f79ecb790d0d3fdd693e5fd
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
refs/heads/master
2020-05-02T10:20:49.365871
2019-04-25T09:12:56
2019-04-25T09:12:56
177,894,636
1
1
null
null
null
null
UTF-8
C++
false
false
105,529
cpp
MtkAACExtractor.cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /***************************************************************************** * * Filename: * --------- * MtkAACExtractor.cpp * * Project: * -------- * MT65xx * * Description: * ------------ * MTK AAC Parser * * Author: * ------- * mtk80830 * mtk80712 ****************************************************************************/ //#define LOG_NDEBUG 0 #define LOG_TAG "MtkAACExtractor" #include <utils/Log.h> #include <cutils/xlog.h> #define ENABLE_AAC_EXTR_DEBUG #ifdef ENABLE_AAC_EXTR_DEBUG #define AAC_EXTR_VEB(fmt, arg...) SXLOGV(fmt, ##arg) #define AAC_EXTR_DBG(fmt, arg...) SXLOGD(fmt, ##arg) #define AAC_EXTR_INFO(fmt, arg...) SXLOGI(fmt, ##arg) #define AAC_EXTR_WARN(fmt, arg...) SXLOGW(fmt, ##arg) #define AAC_EXTR_ERR(fmt, arg...) SXLOGE("Err: %5d:, "fmt, __LINE__, ##arg) #else #define AAC_EXTR_VEB ALOGV #define AAC_EXTR_DBG ALOGD #define AAC_EXTR_INFO ALOGI #define AAC_EXTR_WARN ALOGW #define AAC_EXTR_ERR ALOGE #endif #include "MtkAACExtractor.h" #include "include/ID3.h" #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/foundation/AMessage.h> #include <media/stagefright/foundation/ABuffer.h> #include <media/stagefright/DataSource.h> #include <media/stagefright/MediaBuffer.h> #include <media/stagefright/MediaBufferGroup.h> #include <media/stagefright/MediaDefs.h> #include <media/stagefright/MediaErrors.h> #include <media/stagefright/MediaSource.h> #include <media/stagefright/MetaData.h> #include <media/stagefright/Utils.h> #include <utils/String8.h> #include "include/ESDS.h" // for AAC seek table ---> #include "TableOfContentThread.h" #include "include/AwesomePlayer.h" #include <cutils/properties.h> // <---for AAC seek table #ifdef USE_PV_AAC #include "codecs/aacdec/pvmp4audiodecoder_api.h" #endif #ifdef USE_MTK_AAC #include "heaacdec_exp.h" #endif #ifdef USE_FRAUNHOFER_AAC #include "aacdecoder_lib.h" #define ADIF_DEC_INBUF_LEN 3072 #define ADIF_DEC_OUTBUF_LEN 8192 #define ADIF_DEC_BUFFER_SIZE 3072 #define FILEREAD_MAX_LAYERS 2 #else #define ADIF_DEC_INBUF_LEN 4096 #define ADIF_DEC_OUTBUF_LEN 8192 #define ADIF_DEC_BUFFER_SIZE 1536 #endif namespace android { // adts fixheader must match except for // layer,protection, private bit, mode, mode extension, // copyright/original bit ,home bit,copyright identification bit,and copyright identification start bit. // Yes ... there are things that must indeed match... static const uint32_t kMask = 0xfff8fdc0;//for adts #define MEDIA_BUFFER_LEN 8192 // AAC seek table ---> #define ADTS_MANDATORY_SEEK // for ADTS mandatory seek //#define ADIF_MANDATORY_SEEK // for ADIF mandatory seek #define ENABLE_USE_TABLE_OF_CONTENT // <--- for AAC seek table /* * Sampling Frequency look up table * The look up index is found in the * header of an ADTS packet */ static const uint32_t AACSampleFreqTable[16] = { 96000, /* 96000 Hz */ 88200, /* 88200 Hz */ 64000, /* 64000 Hz */ 48000, /* 48000 Hz */ 44100, /* 44100 Hz */ 32000, /* 32000 Hz */ 24000, /* 24000 Hz */ 22050, /* 22050 Hz */ 16000, /* 16000 Hz */ 12000, /* 12000 Hz */ 11025, /* 11025 Hz */ 8000, /* 8000 Hz */ -1, /* future use */ -1, /* future use */ -1, /* future use */ -1 /* escape value */ }; static bool isAACADTSHeader(uint8_t header[4]) { if (header[0] != 0xFF || (header[1] & 0xF0) != 0xF0) // test syncword { return false; } if ((header[1] & 0x06) != 0) // layer must be 0 { return false; } if (((header[2] >> 2) & 0x0F) >= 12) // samplerate index must <12 { return false; } if ((header[3] & 0x02) != 0) // frame size can not lager than 4096 { return false; } return true; } static bool findADTSSyncword( const sp<DataSource> &source, off_t *inout_pos, uint32_t *out_header) { if (*inout_pos == 0) { // Skip an optional ID3 header if syncing at the very beginning // of the datasource. for (;;) { uint8_t id3header[10]; if (source->readAt(*inout_pos, id3header, sizeof(id3header)) < (ssize_t)sizeof(id3header)) { // If we can't even read these 10 bytes, we might as well bail // out, even if there _were_ 10 bytes of valid mp3 audio data... return false; } if (memcmp("ID3", id3header, 3)) { break; } // Skip the ID3v2 header. size_t len = ((id3header[6] & 0x7f) << 21) | ((id3header[7] & 0x7f) << 14) | ((id3header[8] & 0x7f) << 7) | (id3header[9] & 0x7f); len += 10; *inout_pos += len; //AAC_EXTR_DBG("skipped ID3 tag, new starting offset is %ld (0x%08lx)", // *inout_pos, *inout_pos); } } off_t pos = *inout_pos; bool valid = false; const size_t kMaxReadBytes = 1024; const off_t kMaxBytesChecked = 128 * 1024; uint8_t buf[kMaxReadBytes]; ssize_t bytesToRead = kMaxReadBytes; ssize_t totalBytesRead = 0; ssize_t remainingBytes = 0; bool reachEOS = false; uint8_t *tmp = buf; do { if (pos >= *inout_pos + kMaxBytesChecked) { // Don't scan forever. //AAC_EXTR_DBG("giving up at offset %ld", pos); break; } if (remainingBytes < 7) { if (reachEOS) { break; } else { memcpy(buf, tmp, remainingBytes); bytesToRead = kMaxReadBytes - remainingBytes; /* * The next read position should start from the end of * the last buffer, and thus should include the remaining * bytes in the buffer. */ totalBytesRead = source->readAt(pos + remainingBytes, buf + remainingBytes, bytesToRead); if (totalBytesRead <= 0) { break; } reachEOS = (totalBytesRead != bytesToRead); totalBytesRead += remainingBytes; remainingBytes = totalBytesRead; tmp = buf; continue; } } uint32_t header = U32_AT(tmp); if (!isAACADTSHeader(tmp)) { ++pos; ++tmp; --remainingBytes; continue; } size_t frame_size; frame_size = ((tmp[3] & 0x03) << 11) | (tmp[4] << 3) | ((tmp[5] & 0xe0) >> 5); if (frame_size <= 7) { ++pos; ++tmp; --remainingBytes; continue; } //AAC_EXTR_DBG("found possible 1st frame at %ld, frame size = %d ", pos, frame_size); // We found what looks like a valid frame, // now find its successors. off_t test_pos = pos + frame_size; valid = true; for (int j = 0; j < 3; ++j) { uint8_t tmp[7]; if (source->readAt(test_pos, tmp, 7) < 7) { valid = false; break; } uint32_t test_header = U32_AT(tmp); if (header != 0 && (test_header & kMask) != (header & kMask)) // compare frame fixed header { valid = false; break; } size_t test_frame_size; test_frame_size = ((tmp[3] & 0x03) << 11) | (tmp[4] << 3) | ((tmp[5] & 0xe0) >> 5); if (test_frame_size <= 7) // compare frame fixed header { valid = false; break; } //AAC_EXTR_DBG("found subsequent frame #%d at %ld", j + 2, test_pos); test_pos += test_frame_size; } if (valid) { *inout_pos = pos; if (out_header != NULL) { *out_header = header; } } else { //AAC_EXTR_DBG("no dice, no valid sequence of frames found."); } ++pos; ++tmp; --remainingBytes; } while (!valid); return valid; } static bool findADIFHeader( const sp<DataSource> &source, off_t *inout_pos, uint32_t *out_header, uint32_t *pSampleFreqIndex, uint32_t *pBitRate, uint32_t *pProfile, uint32_t *pChannelNum) { if (*inout_pos == 0) { // Skip an optional ID3 header if syncing at the very beginning // of the datasource. for (;;) { uint8_t id3header[10]; if (source->readAt(*inout_pos, id3header, sizeof(id3header)) < (ssize_t)sizeof(id3header)) { // If we can't even read these 10 bytes, we might as well bail // out, even if there _were_ 10 bytes of valid mp3 audio data... return false; } if (memcmp("ID3", id3header, 3)) { break; } // Skip the ID3v2 header. size_t len = ((id3header[6] & 0x7f) << 21) | ((id3header[7] & 0x7f) << 14) | ((id3header[8] & 0x7f) << 7) | (id3header[9] & 0x7f); len += 10; *inout_pos += len; //AAC_EXTR_DBG("skipped ID3 tag, new starting offset is %ld (0x%08lx)", // *inout_pos, *inout_pos); } } off_t pos = *inout_pos; uint8_t tmpBuf[4]; if (source->readAt(pos, tmpBuf, 4) != 4) { return false; } if (tmpBuf[0] == 0x41 && // 'A' tmpBuf[1] == 0x44 && // 'D' tmpBuf[2] == 0x49 && // 'I' tmpBuf[3] == 0x46) // 'F' { *out_header = U32_AT(tmpBuf); uint8_t pBuffer[4096]; memset(pBuffer, 0, 4096); if (source->readAt(pos, pBuffer, 4096) <= 0) { return false; } uint32_t id; uint32_t bitstreamType; uint32_t numProgConfigElem; uint32_t ADIFHeaderLen; uint32_t numFrontChanElem; uint32_t numSideChanElem; uint32_t numBackChanElem; uint32_t numLfeChanElem; uint32_t numAssocDataElem; uint32_t numValidCCElem; uint32_t commentFieldBytes; uint32_t offset; uint32_t bitIndex = 0; uint8_t tmp; uint32_t iBitrate = 0; uint32_t iAudioObjectType = 0; uint32_t iSampleFreqIndex = 0; uint32_t iChannelConfig = 0; uint32_t sampleFreqIndex = 0; uint32_t bitRate = 0; int32_t i = 0; ADIFHeaderLen = 32; // adif_id 4 bytes // check copyright_id_present (1 bit) id = pBuffer[4] & 0x80; if (id != 0) //copyright ID is presented { ADIFHeaderLen += 75; // copyright_id_present 1 bit // copyright_id 72 bits, // original_copy 1 bit, // home 1 bit, // check bitstream type bitstreamType = pBuffer[13] & 0x10; // get number of program config. element numProgConfigElem = (pBuffer[16] & 0x1E) >> 1; // get bitrate (max for variable rate bitstream) /* iBitrate = bitRate = ((pBuffer[13] & 0xF0) << 15) | (pBuffer[14] << 11) | (pBuffer[15] << 3) | ((pBuffer[16] & 0xE0) >> 5); */ //Modified by HP Cheng, fix the bug of getting bit rate iBitrate = bitRate = ((pBuffer[13] & 0x0F) << 19) | (pBuffer[14] << 11) | (pBuffer[15] << 3) | ((pBuffer[16] & 0xE0) >> 5); if (iBitrate == 0) //bitrate is not known { ////PVMF_AACPARSER_LOGERROR((0, "AACBitstreamObject::getFileInfo- Misc Error")); ////return AACBitstreamObject::MISC_ERROR; AAC_EXTR_ERR("findADIFHeader -- iBitrate is 0"); return false; } ADIFHeaderLen += 28; // bitstream_type 1 bit, // bitrate 23 bits // num_program_config_elements 4 bits for (i = 0; i < (int32_t)numProgConfigElem + 1; i++) { if (bitstreamType == 0) //bistream type is constant rate bitstream { ADIFHeaderLen += 20; //adif_buffer_fullness 20 bits // get audio object type iAudioObjectType = (uint8_t)(((pBuffer[19] & 0x1) << 1) | ((pBuffer[20] & 0x80) >> 7)); // get sampling rate index iSampleFreqIndex = sampleFreqIndex = (uint8_t)((pBuffer[20] & 0x78) >> 3); // get number of front channel elements numFrontChanElem = (uint32_t)(((pBuffer[20] & 0x7) << 1) | ((pBuffer[21] & 0x80) >> 7)); // get number of side channel elements numSideChanElem = (uint32_t)((pBuffer[21] & 0x78) >> 3); // get number of back channel elements numBackChanElem = (uint32_t)(((pBuffer[21] & 0x7) << 1) | ((pBuffer[22] & 0x80) >> 7)); // get number of LFE channel elements numLfeChanElem = (uint32_t)((pBuffer[22] & 0x60) >> 5); // get number of assoc data elements numAssocDataElem = (uint32_t)((pBuffer[22] & 0x1C) >> 2); // get number of valid CC elements numValidCCElem = (uint32_t)(((pBuffer[22] & 0x3) << 2) | ((pBuffer[23] & 0xC0) >> 6)); ADIFHeaderLen += 31; //element_instance_tag 4 bits, //object_type 2 bits, //sampling_frequency_index 4 bits, //num_front_channel_elements 4 bits, //num_side_channel_elements 4 bits, //num_back_channel_elements 4 bits, //num_lfe_channel_elements 2 bits, //num_assoc_data_elements 3 bits, //num_valid_cc_elements 4 bits // check mono_mixdown_present if ((pBuffer[23] & 0x20) != 0) //mono mixdown is presented { ADIFHeaderLen += 5; //mono_mixdown_present 1 bit //mono_mixdown_element_number 4 bits //check stereo_mixdown_present if ((pBuffer[23] & 0x1) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[24] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[24] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[23] & 0x1) != 0) } else //mono mixdown is not presented { ADIFHeaderLen += 1; //mono_mixdown_present 1 bit //check stereo_mixdown_present if ((pBuffer[23] & 0x10) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[24] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[23] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[23] & 0x10) != 0) }//if ((pBuffer[23] & 0x20) != 0) } else //bistream type is variable rate bitstream { // get audio object type iAudioObjectType = (uint8_t)((pBuffer[17] & 0x18) >> 3); // get sampling rate index iSampleFreqIndex = sampleFreqIndex = (uint8_t)(((pBuffer[17] & 0x7) << 1) | ((pBuffer[18] & 0x80) >> 7)); // get number of front channel elements numFrontChanElem = (uint32_t)((pBuffer[18] & 0x78) >> 3); // get number of side channel elements numSideChanElem = (uint32_t)(((pBuffer[18] & 0x7) << 1) | ((pBuffer[19] & 0x80) >> 7)); // get number of back channel elements numBackChanElem = (uint32_t)((pBuffer[19] & 0x78) >> 3); // get number of LFE channel elements numLfeChanElem = (uint32_t)((pBuffer[19] & 0x6) >> 1); // get number of assoc data elements numAssocDataElem = (uint32_t)(((pBuffer[19] & 0x1) << 2) | ((pBuffer[20] & 0xC0) >> 6)); // get number of valid CC elements numValidCCElem = (uint32_t)((pBuffer[20] & 0x3C) >> 2); ADIFHeaderLen += 31; //element_instance_tag 4 bits, //object_type 2 bits, //sampling_frequency_index 4 bits, //num_front_channel_elements 4 bits, //num_side_channel_elements 4 bits, //num_back_channel_elements 4 bits, //num_lfe_channel_elements 2 bits, //num_assoc_data_elements 3 bits, //num_valid_cc_elements 4 bits // check mono_mixdown_present if ((pBuffer[20] & 0x2) != 0) //mono mixdown is presented { ADIFHeaderLen += 5; //mono_mixdown_present 1 bit //mono_mixdown_element_number 4 bits //check stereo_mixdown_present if ((pBuffer[21] & 0x10) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[22] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[21] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[21] & 0x10) != 0) } else //mono mixdown is not presented { ADIFHeaderLen += 1; //mono_mixdown_present 1 bit //check stereo_mixdown_present if ((pBuffer[20] & 0x1) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[21] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[21] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[20] & 0x1) != 0) }//if ((pBuffer[20] & 0x2) != 0) }// if (bitstreamType == 0) for (i = 0; i < (int32_t)numFrontChanElem; i++) { //calculate channel configuration offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; tmp = (uint8_t)((pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex))); tmp >>= (8 - 1); //front channel element takes 1 bit iChannelConfig += tmp; //update ADIF variable header length ADIFHeaderLen += 5; //front_element_is_cpe[i] 1 bit, //front_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numSideChanElem; i++) { //calculate channel configuration offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; tmp = (uint8_t)((pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex))); tmp >>= (8 - 1); //side channel element takes 1 bit iChannelConfig += (tmp + 1); //update ADIF variable header length ADIFHeaderLen += 5; //side_element_is_cpe[i] 1 bit, //side_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numBackChanElem; i++) { //calculate channel configuration offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; tmp = (uint8_t)((pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex))); tmp >>= (8 - 1); //back channel element takes 1 bit iChannelConfig += (tmp + 1); //update ADIF variable header length ADIFHeaderLen += 5; //back_element_is_cpe[i] 1 bit, //back_element_tag_select[i] 4 bits } if (numLfeChanElem != 0) { iChannelConfig++; //1 front low frequency effects speaker } for (i = 0; i < (int32_t)numLfeChanElem; i++) { ADIFHeaderLen += 4; //lfe_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numAssocDataElem; i++) { ADIFHeaderLen += 4; //assoc_data_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numValidCCElem; i++) { ADIFHeaderLen += 5; //cc_element_is_ind_sw[i] 1 bit, //valid_cc_element_tag_select[i] 4 bits } // byte_allignment ADIFHeaderLen += 7; ADIFHeaderLen &= 0xF8; // comment_field_bytes (8 bits) offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; commentFieldBytes = (pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex)); ADIFHeaderLen += 8; //comment_field_bytes 8 bits for (i = 0; i < (int32_t)commentFieldBytes; i++) { ADIFHeaderLen += 8; //comment_field_data 8 bits } }// for (i = 0; i < (int32)numProgConfigElem + 1; i++) } else //copyright ID is not presented { ADIFHeaderLen += 3; // copyright_id_present 1 bit // original_copy 1 bit, // home 1 bit, // check bitstream type bitstreamType = pBuffer[4] & 0x10; // get number of program config. element numProgConfigElem = (pBuffer[7] & 0x1E) >> 1; // get bitrate (max for variable rate bitstream) /* iBitrate = bitRate = ((pBuffer[4] & 0xF0) << 15) | (pBuffer[5] << 11) | (pBuffer[6] << 3) | ((pBuffer[7] & 0xE0) >> 5); */ //Modified by HP Cheng, fix the bug of getting bit rate iBitrate = bitRate = ((pBuffer[4] & 0x0F) << 19) | (pBuffer[5] << 11) | (pBuffer[6] << 3) | ((pBuffer[7] & 0xE0) >> 5); if (iBitrate == 0) //bitrate is not known { AAC_EXTR_ERR("findADIFHeader--the adif bitrate is 0"); return false; //PVMF_AACPARSER_LOGERROR((0, "AACBitstreamObject::getFileInfo- Misc Error")); //return AACBitstreamObject::MISC_ERROR; } ADIFHeaderLen += 28; // bitstream_type 1 bit, // bitrate 23 bits // num_program_config_elements 4 bits for (i = 0; i < (int32_t)numProgConfigElem + 1; i++) { if (bitstreamType == 0) //bistream type is constant rate bitstream { ADIFHeaderLen += 20; //adif_buffer_fullness 20 bits // get audio object type iAudioObjectType = (uint8_t)(((pBuffer[10] & 0x1) << 1) | ((pBuffer[11] & 0x80) >> 7)); // get sampling rate index iSampleFreqIndex = sampleFreqIndex = (uint8_t)((pBuffer[11] & 0x78) >> 3); // get number of front channel elements numFrontChanElem = (uint32_t)(((pBuffer[11] & 0x7) << 1) | ((pBuffer[12] & 0x80) >> 7)); // get number of side channel elements numSideChanElem = (uint32_t)((pBuffer[12] & 0x78) >> 3); // get number of back channel elements numBackChanElem = (uint32_t)(((pBuffer[12] & 0x7) << 1) | ((pBuffer[13] & 0x80) >> 7)); // get number of LFE channel elements numLfeChanElem = (uint32_t)((pBuffer[13] & 0x60) >> 5); // get number of assoc data elements numAssocDataElem = (uint32_t)((pBuffer[13] & 0x1C) >> 2); // get number of valid CC elements numValidCCElem = (uint32_t)(((pBuffer[13] & 0x3) << 2) | ((pBuffer[14] & 0xC0) >> 6)); ADIFHeaderLen += 31; //element_instance_tag 4 bits, //object_type 2 bits, //sampling_frequency_index 4 bits, //num_front_channel_elements 4 bits, //num_side_channel_elements 4 bits, //num_back_channel_elements 4 bits, //num_lfe_channel_elements 2 bits, //num_assoc_data_elements 3 bits, //num_valid_cc_elements 4 bits // check mono_mixdown_present if ((pBuffer[14] & 0x20) != 0) //mono mixdown is presented { ADIFHeaderLen += 5; //mono_mixdown_present 1 bit //mono_mixdown_element_number 4 bits //check stereo_mixdown_present if ((pBuffer[14] & 0x1) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[15] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[15] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[14] & 0x1) != 0) } else //mono mixdown is not presented { ADIFHeaderLen += 1; //mono_mixdown_present 1 bit //check stereo_mixdown_present if ((pBuffer[14] & 0x10) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[15] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[14] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[14] & 0x10) != 0) }//if ((pBuffer[14] & 0x20) != 0) } else //bistream type is variable rate bitstream { // get audio object type iAudioObjectType = (uint8_t)((pBuffer[8] & 0x18) >> 3); // get sampling rate index iSampleFreqIndex = sampleFreqIndex = (uint8_t)(((pBuffer[8] & 0x7) << 1) | ((pBuffer[9] & 0x80) >> 7)); // get number of front channel elements numFrontChanElem = (uint32_t)((pBuffer[9] & 0x78) >> 3); // get number of side channel elements numSideChanElem = (uint32_t)(((pBuffer[9] & 0x7) << 1) | ((pBuffer[10] & 0x80) >> 7)); // get number of back channel elements numBackChanElem = (uint32_t)((pBuffer[10] & 0x78) >> 3); // get number of LFE channel elements numLfeChanElem = (uint32_t)((pBuffer[10] & 0x6) >> 1); // get number of assoc data elements numAssocDataElem = (uint32_t)(((pBuffer[10] & 0x1) << 2) | ((pBuffer[11] & 0xC0) >> 6)); // get number of valid CC elements numValidCCElem = (uint32_t)((pBuffer[11] & 0x3C) >> 2); ADIFHeaderLen += 31; //element_instance_tag 4 bits, //object_type 2 bits, //sampling_frequency_index 4 bits, //num_front_channel_elements 4 bits, //num_side_channel_elements 4 bits, //num_back_channel_elements 4 bits, //num_lfe_channel_elements 2 bits, //num_assoc_data_elements 3 bits, //num_valid_cc_elements 4 bits // check mono_mixdown_present if ((pBuffer[11] & 0x2) != 0) //mono mixdown is presented { ADIFHeaderLen += 5; //mono_mixdown_present 1 bit //mono_mixdown_element_number 4 bits //check stereo_mixdown_present if ((pBuffer[12] & 0x10) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[13] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[12] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[12] & 0x10) != 0) } else //mono mixdown is not presented { ADIFHeaderLen += 1; //mono_mixdown_present 1 bit //check stereo_mixdown_present if ((pBuffer[11] & 0x1) != 0) //stereo mixdown is presented { ADIFHeaderLen += 5; //stereo_mixdown_present 1 bit //stereo_mixdown_element_number 4 bits //check matrix_mixdown_idx_present if ((pBuffer[12] & 0x8) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } } else //stereo mixdown is not presented { ADIFHeaderLen += 1; //stereo_mixdown_present 1 bit //check matrix_mixdown_idx_present if ((pBuffer[12] & 0x80) != 0) //matrix mixdown is presented { ADIFHeaderLen += 4; //matrix_mixdown_idx_present 1 bit //matrix_mixdown_idx 2 bits //pseudo_surround_enable 1 bit } else //matrix mixdown is not presented { ADIFHeaderLen += 1; //matrix_mixdown_idx_present 1 bit } }//if ((pBuffer[11] & 0x1) != 0) }//if ((pBuffer[11] & 0x2) != 0) }// if (bitstreamType == 0) for (i = 0; i < (int32_t)numFrontChanElem; i++) { //calculate channel configuration offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; tmp = (uint8_t)((pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex))); tmp >>= (8 - 1); //front channel element takes 1 bit iChannelConfig += tmp; //update ADIF variable header length ADIFHeaderLen += 5; //front_element_is_cpe[i] 1 bit, //front_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numSideChanElem; i++) { //calculate channel configuration offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; tmp = (uint8_t)((pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex))); tmp >>= (8 - 1); //side channel element takes 1 bit iChannelConfig += (tmp + 1); //update ADIF variable header length ADIFHeaderLen += 5; //side_element_is_cpe[i] 1 bit, //side_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numBackChanElem; i++) { //calculate channel configuration offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; tmp = (uint8_t)((pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex))); tmp >>= (8 - 1); //back channel element takes 1 bit iChannelConfig += (tmp + 1); //update ADIF variable header length ADIFHeaderLen += 5; //side_element_is_cpe[i] 1 bit, //side_element_tag_select[i] 4 bits } if (numLfeChanElem != 0) { iChannelConfig++; //1 front low frequency effects speaker } for (i = 0; i < (int32_t)numLfeChanElem; i++) { ADIFHeaderLen += 4; //lfe_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numAssocDataElem; i++) { ADIFHeaderLen += 4; //assoc_data_element_tag_select[i] 4 bits } for (i = 0; i < (int32_t)numValidCCElem; i++) { ADIFHeaderLen += 5; //cc_element_is_ind_sw[i] 1 bit, //valid_cc_element_tag_select[i] 4 bits } // byte_allignment ADIFHeaderLen += 7; ADIFHeaderLen &= 0xF8; // comment_field_bytes (8 bits) offset = ADIFHeaderLen >> 3; bitIndex = ADIFHeaderLen & 0x7; commentFieldBytes = (pBuffer[offset] << bitIndex) | (pBuffer[offset + 1] >> (8 - bitIndex)); ADIFHeaderLen += 8; //comment_field_bytes 8 bits for (i = 0; i < (int32_t)commentFieldBytes; i++) { ADIFHeaderLen += 8; //comment_field_data 8 bits } }// for (i = 0; i < (int32)numProgConfigElem + 1; i++) } // if(id!=0) // ADIF header length in bits //iADIFHeaderLen = HeaderLen = ADIFHeaderLen; *inout_pos += ADIFHeaderLen >> 3; *pChannelNum = iChannelConfig + 1; *pSampleFreqIndex = sampleFreqIndex; *pBitRate = iBitrate; *pProfile = iAudioObjectType; return true; } else { return false; } } static bool getAACInfo( const sp<DataSource> &source, off_t *inout_pos, uint32_t *out_header, uint32_t *pSampleFreqIndex, uint32_t *pBitRate, uint32_t *pProfile, uint32_t *pChannelNum, int32_t *pIsADIF) { //uint32_t nSampleFreqIndex; uint32_t header; off_t pos = 0; if (findADTSSyncword(source, inout_pos, out_header)) { header = *out_header; pos = *inout_pos; *pIsADIF = false; *pSampleFreqIndex = (header >> 10) & 0x0F; *pProfile = (header >> 14) & 0x03; *pChannelNum = (header >> 6) & 0x07; AAC_EXTR_DBG("getAACInfo -- ADTS"); return true; } else if (findADIFHeader(source, inout_pos, out_header, pSampleFreqIndex, pBitRate, pProfile, pChannelNum)) { *pIsADIF = true; AAC_EXTR_DBG("getAACInfo -- ADIF"); AAC_EXTR_DBG("getAACInfo -- pos=%d", *inout_pos); return true; } return false; } #ifdef USE_FRAUNHOFER_AAC // <--- add for fraunhofer AAC seek table class AACFrameLenDecoder { public: AACFrameLenDecoder( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos); status_t getNextFramePos(off_t *pCurPos, off_t *pNextPos); bool initAACDec(); void deinitAACDec(); //protected: virtual ~AACFrameLenDecoder(); private: sp<MetaData> mMeta; sp<DataSource> mDataSource; bool mInited; off_t mFirstFramePos; Mutex mLock; HANDLE_AACDECODER mAACDecoder; CStreamInfo *mStreamInfo; uint8_t *mTmpBuf; uint8_t *mOutBuf; uint32_t mTmpBufLen; uint32_t mInterDecBufSize; uint32_t mCurPosition; bool mReadFlag; uint32_t mLastNumTotalBytes; off_t mFramePosition; off_t mCurFliePos; }; AACFrameLenDecoder::AACFrameLenDecoder( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos) : mMeta(meta), mDataSource(source), mFirstFramePos(first_frame_pos), mInited(false) { AAC_EXTR_VEB("FRAUNHOFER_AAC :AACFrameLenDecoder!"); mCurFliePos = first_frame_pos; mFramePosition = first_frame_pos; mTmpBuf = NULL; mOutBuf = NULL; mTmpBufLen = 0; mInterDecBufSize = 0; mCurPosition = 0; mReadFlag = true; mLastNumTotalBytes = 0; } AACFrameLenDecoder::~AACFrameLenDecoder() { AAC_EXTR_VEB("FRAUNHOFER_AAC :~AACFrameLenDecoder!"); deinitAACDec(); } bool AACFrameLenDecoder::initAACDec() { AAC_EXTR_VEB("FRAUNHOFER_AAC--initAACDec"); if (mInited) { return true; } mAACDecoder = aacDecoder_Open(TT_MP4_ADIF, /* num layers */ 1); if (AAC_DEC_OK != aacDecoder_GetFreeBytes(mAACDecoder, (UINT *)&mInterDecBufSize)) { AAC_EXTR_ERR("initDecoder get inbuf size failure"); return false; } AAC_EXTR_VEB("mInterDecBufSize %d", mInterDecBufSize); if (mAACDecoder != NULL) { mStreamInfo = aacDecoder_GetStreamInfo(mAACDecoder); if (mStreamInfo == NULL) { AAC_EXTR_ERR("FRAUNHOFER_AAC--initAACDec:aacDecoder_GetStreamInfo error!"); return false; } } else { AAC_EXTR_ERR("FRAUNHOFER_AAC--initAACDec:aacDecoder_Open fail!"); return false; } mTmpBuf = (uint8_t *) malloc(ADIF_DEC_INBUF_LEN); if (!mTmpBuf) { AAC_EXTR_ERR("initDecoder:adif temp buffer alloc fail!"); return false; } else { memset(mTmpBuf, 0x00, ADIF_DEC_INBUF_LEN); } mOutBuf = (uint8_t *) malloc(ADIF_DEC_OUTBUF_LEN); if (!mOutBuf) { AAC_EXTR_ERR("initDecoder:adif temp buffer alloc fail!"); return false; } else { memset(mOutBuf, 0x00, ADIF_DEC_OUTBUF_LEN); } mCurFliePos = mFirstFramePos;//file position mFramePosition = mCurFliePos; //frame position uint32_t type; const void *data; size_t size; if (mMeta->findData(kKeyESDS, &type, &data, &size)) { const void *codec_specific_data; size_t codec_specific_data_size; ESDS esds((const char *)data, size); if (OK != esds.InitCheck()) { return false; } esds.getCodecSpecificInfo( &codec_specific_data, &codec_specific_data_size); AAC_EXTR_DBG("FRAUNHOFER_AAC--initAACDec codec_specific_data_size =%d", codec_specific_data_size); AAC_DECODER_ERROR decoderErr = aacDecoder_ConfigRaw(mAACDecoder, (UCHAR **)&codec_specific_data, (UINT *)&size); if (decoderErr != AAC_DEC_OK) { AAC_EXTR_ERR("FRAUNHOFER_AAC--aacDecoder_ConfigRaw return err %d", decoderErr); return false; } } mInited = true; return true; } void AACFrameLenDecoder::deinitAACDec() { AAC_EXTR_VEB("FRAUNHOFER_AAC--deinitAACDec"); if (NULL != mTmpBuf) { free(mTmpBuf); mTmpBuf = NULL; } if (NULL != mOutBuf) { free(mOutBuf); mOutBuf = NULL; } aacDecoder_Close(mAACDecoder); mTmpBufLen = 0; mCurPosition = 0; mInited = false; mReadFlag = true; } status_t AACFrameLenDecoder::getNextFramePos(off_t *pCurPos, off_t *pNextPos) { Mutex::Autolock autoLock(mLock); int consumBsLen = 0; ssize_t size = 0; UINT bytesValid[FILEREAD_MAX_LAYERS] = {0}; UCHAR *pFrameDecodeBuffer[FILEREAD_MAX_LAYERS]; AAC_EXTR_VEB("|---------------getNextFramePos:*pCurPos %d mFramePosition %d mTmpBufLen %d-------------------------|", *pCurPos, mFramePosition, mTmpBufLen); if (*pCurPos != mFramePosition) { aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1); mTmpBufLen = 0; mCurPosition = 0; mReadFlag = true; size = mDataSource->readAt(*pCurPos, mTmpBuf, ADIF_DEC_INBUF_LEN); if (size <= 0) { return ERROR_END_OF_STREAM; } mCurFliePos = *pCurPos + size; mFramePosition = *pCurPos; mTmpBufLen += size; mLastNumTotalBytes = 0; AAC_EXTR_VEB("Seek *pCurPos %ld mCurFliePos =%ld mFramePosition = %ld mTmpBufLen %d", *pCurPos, mCurFliePos, mFramePosition, mTmpBufLen); } if (mReadFlag) { if (mTmpBufLen < ADIF_DEC_INBUF_LEN / 2) //Fill { if (mCurPosition > 0) { //move AAC_EXTR_VEB("move mCurPosition %d mTempBufLen %d", mCurPosition, mTmpBufLen); memcpy(mTmpBuf, mTmpBuf + mCurPosition, mTmpBufLen); mCurPosition = 0; } AAC_EXTR_VEB("mCurFliePos %d,mTmpBuf %p mCurPosition %d read %d", mCurFliePos, mTmpBuf, mCurPosition, ADIF_DEC_INBUF_LEN - mTmpBufLen); size = mDataSource->readAt(mCurFliePos, mTmpBuf + mTmpBufLen, ADIF_DEC_INBUF_LEN - mTmpBufLen); if (size <= 0) { mReadFlag = false; AAC_EXTR_VEB("Read all data from file,don't read file"); } else { mCurFliePos += size; mTmpBufLen += size; } } AAC_EXTR_VEB("mCurFliePos %d mReadFlag :mTmpBufLen %d , mCurPosition %d size %d", mCurFliePos, mTmpBufLen, mCurPosition, size); } AAC_DECODER_ERROR decoderErr; // Fill and decode INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(mOutBuf); bytesValid[0] = mTmpBufLen; if (mTmpBufLen > 0) { pFrameDecodeBuffer[0] = mTmpBuf + mCurPosition; decoderErr = AAC_DEC_NOT_ENOUGH_BITS; AAC_EXTR_VEB("mTmpBufLen >0 inbuf %p mTmpBuf %p mCurPosition %d", pFrameDecodeBuffer[0], mTmpBuf, mCurPosition); while (bytesValid[0] > 0 && decoderErr == AAC_DEC_NOT_ENOUGH_BITS) { AAC_EXTR_VEB("--Fill bytesValid[0] %d mTmpBufLen %d mCurPosition %d--", bytesValid[0], mTmpBufLen, mCurPosition); aacDecoder_Fill(mAACDecoder, pFrameDecodeBuffer, (UINT *)&mTmpBufLen, (UINT *)bytesValid); AAC_EXTR_VEB("--After Fill bytesValid[0] %d mTmpBufLen %d--", bytesValid[0], mTmpBufLen); decoderErr = aacDecoder_DecodeFrame(mAACDecoder, outBuffer, ADIF_DEC_OUTBUF_LEN, AACDEC_BYPASS); if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) { AAC_EXTR_WARN("Not enough bits, bytesValid %d", bytesValid[0]); } } int inBufferUsedLength = mTmpBufLen - bytesValid[0]; if (AAC_DEC_OK == decoderErr && inBufferUsedLength >= 0) { *pCurPos = mFramePosition; consumBsLen = mStreamInfo->numTotalBytes - mLastNumTotalBytes; if (consumBsLen <= 0) { AAC_EXTR_WARN("ERROR_END_OF_STREAM consumBsLen %d", consumBsLen); return ERROR_END_OF_STREAM; } } else { AAC_EXTR_WARN("Error 0x%x consumed %d", decoderErr, mStreamInfo->numTotalBytes - mLastNumTotalBytes); *pCurPos = mFramePosition; uint32_t DecFreeBytes = 0; decoderErr = aacDecoder_GetFreeBytes(mAACDecoder, (UINT *)&DecFreeBytes); if (AAC_DEC_OK != decoderErr) { AAC_EXTR_WARN("aacDecoder_GetFreeBytes err 0x%x", decoderErr); return ERROR_END_OF_STREAM; } consumBsLen = (mInterDecBufSize - DecFreeBytes) + (mStreamInfo->numTotalBytes - mLastNumTotalBytes); //discard buffer aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1); AAC_EXTR_WARN("Remain internal buffer len %d ", mInterDecBufSize - DecFreeBytes); } *pNextPos = mFramePosition + consumBsLen; mFramePosition += consumBsLen; mTmpBufLen -= inBufferUsedLength; if (mTmpBufLen == 0) { mCurPosition = 0; } else { mCurPosition += inBufferUsedLength; } mLastNumTotalBytes = mStreamInfo->numTotalBytes; AAC_EXTR_VEB("mCurPosition %d inBufferUsedLength %d mTmpBufLen %d consumBsLen %d mStreamInfo->numTotalBytes %d", mCurPosition, inBufferUsedLength, mTmpBufLen, consumBsLen, mStreamInfo->numTotalBytes); } else { AAC_EXTR_VEB("have no tmp buf"); decoderErr = aacDecoder_DecodeFrame(mAACDecoder, outBuffer, ADIF_DEC_OUTBUF_LEN, AACDEC_BYPASS); if (AAC_DEC_OK != decoderErr) { AAC_EXTR_WARN("Seek Table ERROR_END_OF_STREAM decoderErr 0x%x", decoderErr); aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1); return ERROR_END_OF_STREAM; } else { *pCurPos = mFramePosition; consumBsLen = mStreamInfo->numTotalBytes - mLastNumTotalBytes; if (consumBsLen <= 0) { AAC_EXTR_WARN("3.ERROR_END_OF_STREAM"); return ERROR_END_OF_STREAM; } *pNextPos = mFramePosition + consumBsLen; mFramePosition += consumBsLen; mLastNumTotalBytes = mStreamInfo->numTotalBytes; AAC_EXTR_VEB("consumBsLen %d,", consumBsLen); } } AAC_EXTR_VEB("getNextFramePos end *pCurPos %d,*pNextPos %d consumBsLen %d", *pCurPos, *pNextPos, consumBsLen); return OK; } //<--- add fraunhoferAAC seek table #else #ifdef USE_PV_AAC // add for AAC seek table ---> class AACFrameLenDecoder { public: AACFrameLenDecoder( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos); status_t getNextFramePos(off_t *pCurPos, off_t *pNextPos); bool initAACDec(); void deinitAACDec(); //protected: virtual ~AACFrameLenDecoder(); private: sp<MetaData> mMeta; sp<DataSource> mDataSource; off_t mFirstFramePos; bool mInited; Mutex mLock; uint8_t *mInbufPtr; uint8_t *mInbufStartPtr; int16_t *mOutbufPtr; uint32_t mInbufLen; uint32_t mInBufSize; off_t mCurFliePos; tPVMP4AudioDecoderExternal *mConfig; void *mDecoderBuf; }; AACFrameLenDecoder::AACFrameLenDecoder( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos) : mMeta(meta), mDataSource(source), mFirstFramePos(first_frame_pos), mInited(false) { mInbufPtr = NULL; mInbufStartPtr = NULL; mOutbufPtr = NULL; mInBufSize = 0; mCurFliePos = first_frame_pos; mConfig = NULL; mDecoderBuf = NULL; } AACFrameLenDecoder::~AACFrameLenDecoder() { deinitAACDec(); } bool AACFrameLenDecoder::initAACDec() { if (mInited) { return true; } mInbufStartPtr = (uint8_t *)malloc(ADIF_DEC_INBUF_LEN); if (NULL == mInbufStartPtr) { return false; } mInbufPtr = mInbufStartPtr; mOutbufPtr = (int16_t *)malloc(ADIF_DEC_OUTBUF_LEN * 2); if (NULL == mOutbufPtr) { return false; } mInBufSize = 0; mCurFliePos = mFirstFramePos; mConfig = new tPVMP4AudioDecoderExternal; if (NULL == mConfig) { return false; } memset(mConfig, 0, sizeof(tPVMP4AudioDecoderExternal)); mConfig->outputFormat = OUTPUTFORMAT_16PCM_INTERLEAVED; mConfig->aacPlusEnabled = 1; // Fix me for remove HE AAC fun // The software decoder doesn't properly support mono output on // AACplus files. Always output stereo. mConfig->desiredChannels = 2; UInt32 memRequirements = PVMP4AudioDecoderGetMemRequirements(); mDecoderBuf = malloc(memRequirements); if (NULL == mDecoderBuf) { return false; } status_t err = PVMP4AudioDecoderInitLibrary(mConfig, mDecoderBuf); if (err != MP4AUDEC_SUCCESS) { AAC_EXTR_ERR("MtkAACSource::initAACDec--Failed to initialize MP4 audio decoder"); return false; } uint32_t type; const void *data; size_t size; if (mMeta->findData(kKeyESDS, &type, &data, &size)) { const void *codec_specific_data; size_t codec_specific_data_size; ESDS esds((const char *)data, size); if (OK != esds.InitCheck()) { return false; } esds.getCodecSpecificInfo( &codec_specific_data, &codec_specific_data_size); AAC_EXTR_DBG("initAACDec codec_specific_data_size =%d", codec_specific_data_size); mConfig->pInputBuffer = (UChar *)codec_specific_data; mConfig->inputBufferCurrentLength = size; #if 0 mConfig->pInputBuffer = (UChar *)data; mConfig->inputBufferCurrentLength = size; #endif mConfig->inputBufferMaxLength = 0; mConfig->pOutputBuffer = mOutbufPtr; mConfig->pOutputBuffer_plus = &mConfig->pOutputBuffer[2048]; if (PVMP4AudioDecoderConfig(mConfig, mDecoderBuf) != MP4AUDEC_SUCCESS) { return false; } } mInited = true; return true; } void AACFrameLenDecoder::deinitAACDec() { if (NULL != mInbufStartPtr) { free(mInbufStartPtr); mInbufStartPtr = NULL; mInbufPtr = NULL; } if (NULL != mOutbufPtr) { free(mOutbufPtr); mOutbufPtr = NULL; } if (NULL != mConfig) { delete mConfig; mConfig = NULL; } if (NULL != mDecoderBuf) { free(mDecoderBuf); mDecoderBuf = NULL; } mInited = false; } status_t AACFrameLenDecoder::getNextFramePos(off_t *pCurPos, off_t *pNextPos) { { Mutex::Autolock autoLock(mLock); if (*pCurPos != mCurFliePos) { mInBufSize = mDataSource->readAt(*pCurPos, mInbufStartPtr, ADIF_DEC_BUFFER_SIZE); if (mInBufSize <= 0) { return ERROR_END_OF_STREAM; } mInbufPtr = mInbufStartPtr; mCurFliePos = *pCurPos; } } while (1) { Mutex::Autolock autoLock(mLock); if (0 == mInBufSize) // refill in bufffer { mInBufSize = mDataSource->readAt(mCurFliePos, mInbufStartPtr, ADIF_DEC_BUFFER_SIZE); if (mInBufSize <= 0) { return ERROR_END_OF_STREAM; } mInbufPtr = mInbufStartPtr; } mConfig->pInputBuffer = mInbufPtr; mConfig->inputBufferCurrentLength = mInBufSize; mConfig->inputBufferMaxLength = 0; mConfig->inputBufferUsedLength = 0; mConfig->remainderBits = 0; mConfig->pOutputBuffer = mOutbufPtr; mConfig->pOutputBuffer_plus = &mConfig->pOutputBuffer[2048]; mConfig->repositionFlag = false; Int decoderErr = 1; decoderErr = PVMP4AudioDecodeFrameTwo(mConfig, mDecoderBuf); if (MP4AUDEC_SUCCESS == decoderErr && mConfig->inputBufferUsedLength > 0 && (uint32_t)(mConfig->inputBufferUsedLength) <= mInBufSize) { //LOGV("mConfig->inputBufferUsedLength %d",mConfig->inputBufferUsedLength); mInBufSize -= mConfig->inputBufferUsedLength; mInbufPtr += mConfig->inputBufferUsedLength; *pCurPos = mCurFliePos; *pNextPos = mCurFliePos + mConfig->inputBufferUsedLength; mCurFliePos += mConfig->inputBufferUsedLength; break; } else if (MP4AUDEC_INCOMPLETE_FRAME == decoderErr) { uint32_t size = 0; //AAC_EXTR_WARN("1.mInBufSize %d",mInBufSize); if (mInBufSize < ADIF_DEC_BUFFER_SIZE) { memcpy(mInbufStartPtr, mInbufPtr, mInBufSize); size = mDataSource->readAt(mCurFliePos + mInBufSize, mInbufStartPtr + mInBufSize, ADIF_DEC_BUFFER_SIZE - mInBufSize); // refill to ADIF_DEC_BUFFER_SIZE } else { size = mDataSource->readAt(mCurFliePos + mInBufSize, mInbufStartPtr, ADIF_DEC_BUFFER_SIZE); mCurFliePos += mInBufSize; mInBufSize = 0; } if (size <= 0) { return ERROR_END_OF_STREAM; } mInbufPtr = mInbufStartPtr; mInBufSize += size; //AAC_EXTR_WARN("2.mInBufSize %d",mInBufSize); } else { *pCurPos = mCurFliePos; *pNextPos = mCurFliePos + ADIF_DEC_BUFFER_SIZE; mInBufSize = 0; break; } } AAC_EXTR_VEB("*pCurPos %d *pNextPos %d", *pCurPos , *pNextPos); return OK; } #else // <--- add for AAC seek table #ifdef USE_MTK_AAC //-----> add for mtk aac decoder typedef struct { HEAACDEC_HANDLE *pHEAACDecHdl; int InterBufSize; int TmpBufSize; int PcmBufSize; int BsBufSize; void *pInterBuf; void *pTmpBuf; void *pPcmBuf; void *pBsBuf; } MtkAACDecEngine; class AACFrameLenDecoder { public: AACFrameLenDecoder( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos); virtual ~AACFrameLenDecoder(); public: status_t getNextFramePos(off_t *pCurPos, off_t *pNextPos); bool initAACDec(); void deinitAACDec(); int DecodeFrame(off_t *pCurPos, off_t *pNextPos); bool ReadFromFile(off_t *CurPos); void *GetCurrentPointer(); uint32_t GetRemainCount(); protected: private: sp<MetaData> mMeta; sp<DataSource> mDataSource; off_t mFirstFramePos; off_t mCurFliePos; bool mInited; Mutex mLock; MtkAACDecEngine *mAACDec; void *m_pBsRead; void *m_pBsWrite; void *m_pEndBsBuf; uint32_t mValidCount; uint32_t mReadOutCount; off_t mFramePosition; off64_t mFileSize; }; AACFrameLenDecoder::AACFrameLenDecoder( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos) : mMeta(meta), mDataSource(source), mFirstFramePos(first_frame_pos), mInited(false) { AAC_EXTR_DBG("AACFrameLenDecoder Construct! %ld", mCurFliePos); mCurFliePos = first_frame_pos; mFramePosition = first_frame_pos; mValidCount = 0; mReadOutCount = 0; mFileSize = 0; m_pBsRead = NULL; m_pBsWrite = NULL; m_pEndBsBuf = NULL; } AACFrameLenDecoder::~AACFrameLenDecoder() { AAC_EXTR_VEB("~AACFrameLenDecoder Destruct"); deinitAACDec(); } bool AACFrameLenDecoder::initAACDec() { if (mInited) { return true; } mAACDec = (MtkAACDecEngine *)malloc(sizeof(MtkAACDecEngine)); if (NULL == mAACDec) { return false; } memset(mAACDec, 0, sizeof(MtkAACDecEngine)); HEAACDec_GetMemSize(&mAACDec->InterBufSize, &mAACDec->TmpBufSize, &mAACDec->PcmBufSize, &mAACDec->BsBufSize); AAC_EXTR_VEB("Get SWIP Decoder Required Mem :"); AAC_EXTR_VEB(" InterBufSize = 0x%lx", mAACDec->InterBufSize); AAC_EXTR_VEB(" TmpBufSize = 0x%lx", mAACDec->TmpBufSize); AAC_EXTR_VEB(" PcmBufSize = 0x%lx", mAACDec->PcmBufSize); AAC_EXTR_VEB(" BsBufSize = 0x%lx", mAACDec->BsBufSize); mAACDec->pInterBuf = malloc(mAACDec->InterBufSize); if (NULL == mAACDec->pInterBuf) { AAC_EXTR_ERR("MTK_OMX_ALLOC InterBuf failure!"); return OMX_FALSE; } else { memset(mAACDec->pInterBuf, 0, mAACDec->InterBufSize); AAC_EXTR_VEB("AAC InterBuf = 0x%lx-0x%lx", (unsigned int)(mAACDec->pInterBuf), (unsigned int)(mAACDec->pInterBuf) + mAACDec->InterBufSize); } mAACDec->pPcmBuf = malloc(mAACDec->PcmBufSize); if (NULL == mAACDec->pPcmBuf) { AAC_EXTR_ERR("MTK_OMX_ALLOC PcmBuf failure!"); return OMX_FALSE; } else { memset(mAACDec->pPcmBuf, 0, mAACDec->PcmBufSize); AAC_EXTR_VEB("AAC PcmBuf = 0x%lx-0x%lx", (unsigned int)(mAACDec->pPcmBuf), (unsigned int)(mAACDec->pPcmBuf) + mAACDec->PcmBufSize); } mAACDec->pTmpBuf = malloc(mAACDec->TmpBufSize); if (NULL == mAACDec->pTmpBuf) { AAC_EXTR_ERR("MTK_OMX_ALLOC TmpBuf failure!"); return OMX_FALSE; } else { memset(mAACDec->pTmpBuf, 0, mAACDec->TmpBufSize); AAC_EXTR_VEB("AAC pTmpBuf = 0x%lx-0x%lx", (unsigned int)(mAACDec->pTmpBuf), (unsigned int)(mAACDec->pTmpBuf) + mAACDec->TmpBufSize); } if (mAACDec->pBsBuf == NULL) { mAACDec->pBsBuf = malloc(mAACDec->BsBufSize); if (NULL == mAACDec->pBsBuf) { AAC_EXTR_ERR("MTK_OMX_ALLOC BsBuf failure!"); return OMX_FALSE; } memset(mAACDec->pBsBuf, 0, mAACDec->BsBufSize); m_pBsRead = mAACDec->pBsBuf; m_pBsWrite = mAACDec->pBsBuf; m_pEndBsBuf = (OMX_U8 *)(mAACDec->pBsBuf) + mAACDec->BsBufSize; } AAC_EXTR_VEB("m_pBsRead %p,m_pBsWrite %p,m_pBsBuf %p,m_pEndBsBuf %p,BsBufSize %d", m_pBsRead, m_pBsWrite, mAACDec->pBsBuf, m_pEndBsBuf, mAACDec->BsBufSize); if (NULL == mAACDec->pHEAACDecHdl) { mAACDec->pHEAACDecHdl = HEAACDec_Init(mAACDec->pInterBuf, SBR_AUTO, SBR_MODE_AUTO, 0); } mCurFliePos = mFirstFramePos;//file position mFramePosition = mCurFliePos; //frame position mDataSource->getSize(&mFileSize);//get file size AAC_EXTR_VEB("mCurFliePos %ld,mFramePosition %ld mFileSize =%lld", mCurFliePos, mFramePosition, mFileSize); uint32_t type; const void *data; size_t size; if (mMeta->findData(kKeyESDS, &type, &data, &size)) { const void *codec_specific_data; size_t codec_specific_data_size; ESDS esds((const char *)data, size); if (OK != esds.InitCheck()) { return false; } esds.getCodecSpecificInfo(&codec_specific_data, &codec_specific_data_size); unsigned char *pInputBuffer = (unsigned char *)codec_specific_data; unsigned int audio_config[2]; unsigned int u4AudioObjectType; unsigned int u4SamplingFreqIndex; unsigned char u1ChannelNum; int Status; audio_config[0] = *((unsigned char *)codec_specific_data); audio_config[1] = *((unsigned char *)codec_specific_data + 1); // oooo offf fccc c000 // o - audioObjectType // f - samplingFreqIndex // c - channelConfig u4AudioObjectType = (unsigned int)((audio_config[0] >> 3) & 7);//3bit u4SamplingFreqIndex = (unsigned int)(((audio_config[0] & 7) << 1) + (audio_config[1] >> 7));//4bit u1ChannelNum = (unsigned char)((audio_config[1] >> 3) & 0x0f);//4bit AAC_EXTR_VEB("audio_config[0]=%x,audio_config[1]=%x", audio_config[0], audio_config[1]); Status = HEAACDec_SetAudioSpecificConfig(mAACDec->pHEAACDecHdl, u4AudioObjectType, u4SamplingFreqIndex, u1ChannelNum); if (Status != 0) { AAC_EXTR_ERR(" Set Audio Config Error!"); return false; } else { AAC_EXTR_VEB(" Set Audio Config : objtype = %d fs = %d chnum = %d", u4AudioObjectType, u4SamplingFreqIndex, u1ChannelNum); } } mInited = true; return true; } int AACFrameLenDecoder::DecodeFrame(off_t *pCurPos, off_t *pNextPos) { int consumBsLen = 0; void *ptr = GetCurrentPointer(); int Status = HEAACDec_DecodeFrameBypass(mAACDec->pHEAACDecHdl, mAACDec->pPcmBuf, mAACDec->pTmpBuf, ptr, GetRemainCount(), ptr, &consumBsLen); if ((consumBsLen <= 0) || (consumBsLen > GetRemainCount())) { consumBsLen = GetRemainCount(); } mReadOutCount += consumBsLen; *pCurPos = mFramePosition; *pNextPos = mFramePosition + consumBsLen; mFramePosition += consumBsLen; //AAC_EXTR_VEB("DecodeFrame Status %d mReadOutCount=%d,*pCurPos %ld,*pNextPos %ld mFramePosition= %ld",Status,mReadOutCount,*pCurPos,*pNextPos,mFramePosition); return Status; } status_t AACFrameLenDecoder::getNextFramePos(off_t *pCurPos, off_t *pNextPos) { Mutex::Autolock autoLock(mLock); int consumBsLen = 0; int Status; void *ptr; int remain = 0; if (*pCurPos != mFramePosition) { uint32_t size = mDataSource->readAt(*pCurPos, mAACDec->pBsBuf, mAACDec->BsBufSize); mValidCount = size; mReadOutCount = 0; mCurFliePos = *pCurPos + mValidCount; mFramePosition = *pCurPos; AAC_EXTR_VEB("Seek mCurFliePos =%ld mFramePosition = %ld mValidCount =%d size =%d mReadOutCount =%d", mCurFliePos, mFramePosition, mValidCount, size, mReadOutCount); } if (ReadFromFile(&mCurFliePos)) { DecodeFrame(pCurPos, pNextPos); } else { remain = GetRemainCount(); if (remain > 0) { DecodeFrame(pCurPos, pNextPos); } else { AAC_EXTR_VEB("getNextFramePos ERROR_END_OF_STREAMs"); return ERROR_END_OF_STREAM; } } return OK; } bool AACFrameLenDecoder::ReadFromFile(off_t *CurPos) { off_t size = 0; if (mReadOutCount) { memmove(mAACDec->pBsBuf, mAACDec->pBsBuf + mReadOutCount, mValidCount - mReadOutCount); mValidCount = mValidCount - mReadOutCount; mReadOutCount = 0; //AAC_EXTR_VEB("ReadFromFile mValidCount %d,mReadOutCount %d",mValidCount,mReadOutCount); } off_t remain = mAACDec->BsBufSize - mValidCount; if (*CurPos < mFileSize) { if (mValidCount < mAACDec->BsBufSize) { size = mDataSource->readAt(*CurPos, mAACDec->pBsBuf + mValidCount, remain); } } if (size <= 0) { //AAC_EXTR_VEB("ReadFromFile mValidCount %d CurPos %ld remain %d size %d",mValidCount,*CurPos,remain,size); return false; } else { mValidCount += size; *CurPos += size; } //AAC_EXTR_VEB("ReadFromFile mValidCount %d CurPos %ld remain %d size %d",mValidCount,*CurPos,remain,size); return true; } void *AACFrameLenDecoder::GetCurrentPointer() { return (unsigned char *)(mAACDec->pBsBuf) + mReadOutCount; } uint32_t AACFrameLenDecoder::GetRemainCount() { return mValidCount - mReadOutCount; } void AACFrameLenDecoder::deinitAACDec() { if (mAACDec) { if (mAACDec->pInterBuf) { free(mAACDec->pInterBuf); mAACDec->pInterBuf = NULL; } if (mAACDec->pPcmBuf) { free(mAACDec->pPcmBuf); mAACDec->pPcmBuf = NULL; } if (mAACDec->pTmpBuf) { free(mAACDec->pTmpBuf); mAACDec->pTmpBuf = NULL; } if (mAACDec->pBsBuf) { free(mAACDec->pBsBuf); mAACDec->pBsBuf = NULL; } free(mAACDec); mAACDec = NULL; } mInited = false; } #endif //<----- add for mtk aac decoder #endif //<-----add for pv aac decoder #endif//<------add for fraunhofer aac decoder class MtkAACSource : public MediaSource #ifdef ENABLE_USE_TABLE_OF_CONTENT , public TableOfContentThread #endif { // for AAC seek table public: MtkAACSource( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos, uint32_t fixed_header, bool isADTS); virtual status_t start(MetaData *params = NULL); virtual status_t stop(); virtual sp<MetaData> getFormat(); virtual status_t read( MediaBuffer **buffer, const ReadOptions *options = NULL); // for AAC seek table---> virtual status_t getNextFramePos(off_t *pCurPos, off_t *pNextPos, int64_t *frameTsUs); virtual status_t sendDurationUpdateEvent(int64_t duration); // <--- for AAC seek table protected: virtual ~MtkAACSource(); private: sp<MetaData> mMeta; sp<DataSource> mDataSource; off_t mFirstFramePos; uint32_t mFixedHeader; off_t mCurrentPos; int64_t mCurrentTimeUs; bool mStarted; MediaBufferGroup *mGroup; bool mIsADTS; int64_t mFrameDurationUs; // for AAC seek table ---> AACFrameLenDecoder *mAACFrameLenDecoderPtr; AwesomePlayer *mObserver; // <--- for AAC seek table MtkAACSource(const MtkAACSource &); MtkAACSource &operator=(const MtkAACSource &); }; static size_t getAdtsFrameLength(const sp<DataSource> &source, off64_t offset, size_t* headerSize) { const size_t kAdtsHeaderLengthNoCrc = 7; const size_t kAdtsHeaderLengthWithCrc = 9; size_t frameSize = 0; uint8_t syncword[2]; if (source->readAt(offset, &syncword, 2) != 2) { return 0; } if ((syncword[0] != 0xff) || ((syncword[1] & 0xf6) != 0xf0)) { return 0; } uint8_t protectionAbsent; if (source->readAt(offset + 1, &protectionAbsent, 1) < 1) { return 0; } protectionAbsent &= 0x1; uint8_t header[3]; if (source->readAt(offset + 3, &header, 3) < 3) { return 0; } frameSize = (header[0] & 0x3) << 11 | header[1] << 3 | header[2] >> 5; // protectionAbsent is 0 if there is CRC size_t headSize = protectionAbsent ? kAdtsHeaderLengthNoCrc : kAdtsHeaderLengthWithCrc; if (headSize > frameSize) { return 0; } if (headerSize != NULL) { *headerSize = headSize; } return frameSize; } MtkAACExtractor::MtkAACExtractor( const sp<DataSource> &source, const sp<AMessage> &meta) : mInitCheck(NO_INIT), mDataSource(source), mFirstFramePos(-1), mFixedHeader(0) { off_t pos = 0; uint32_t header; uint32_t nSampleFreqIndex; uint32_t nBitRate = 0; uint32_t nProfile; uint32_t nChannelNum; uint32_t nSampleRate; int32_t bIsADIF; uint64_t nDurationUs = 0; bool success; int64_t meta_offset; uint32_t meta_header; if (meta != NULL && meta->findInt64("offset", &meta_offset) && meta->findInt32("header", (int32_t *)&meta_header) && meta->findInt32("samplefreqidx", (int32_t *)&nSampleFreqIndex) && meta->findInt32("bitrate", (int32_t *)&nBitRate) && meta->findInt32("profile", (int32_t *)&nProfile) && meta->findInt32("channelnum", (int32_t *)&nChannelNum) && meta->findInt32("isadif", (int32_t *)&bIsADIF)) { // The sniffer has already done all the hard work for us, simply // accept its judgement. pos = (off_t)meta_offset; header = meta_header; success = true; } else { success = getAACInfo(source, &pos, &header, &nSampleFreqIndex, &nBitRate, &nProfile, &nChannelNum, &bIsADIF); } if (!success) { // mInitCheck will remain NO_INIT return; } if(!bIsADIF && calculateAdtsAverageBitRate(source,pos,header,nSampleFreqIndex,&nBitRate)) { AAC_EXTR_WARN("no find bitrate!"); // mInitCheck will remain NO_INIT return; } mFirstFramePos = pos; mFixedHeader = header; nSampleRate = AACSampleFreqTable[nSampleFreqIndex]; mMeta = MakeAACCodecSpecificData(nProfile, nSampleFreqIndex, nChannelNum); AAC_EXTR_DBG("AACExtractor::AACExtractor--nBitRate=%d", nBitRate); AAC_EXTR_DBG("AACExtractor::AACExtractor--samplerate = %d", nSampleRate); AAC_EXTR_DBG("AACExtractor::AACExtractor--nProfile = %d", nProfile); AAC_EXTR_DBG("AACExtractor::AACExtractor--num channels = %d", nChannelNum); AAC_EXTR_DBG("AACExtractor::AACExtractor--nSampleFreqIndex = %d", nSampleFreqIndex); #if 0 uint8_t config_info[2]; config_info[0] = config_info[1] = 0; config_info[0] |= (nProfile + 1) << 3; // put it into the highest 5 bits config_info[0] |= ((nSampleFreqIndex & 0x0F) >> 1); // put 3 bits config_info[1] |= ((nSampleFreqIndex & 0x01) << 7); // put 1 bit config_info[1] |= nChannelNum << 3; AAC_EXTR_VEB("AACExtractor::AACExtractor--nBitRate=%d", nBitRate); AAC_EXTR_VEB("AACExtractor::AACExtractor--samplerate = %d", nSampleRate); AAC_EXTR_VEB("AACExtractor::AACExtractor--nProfile = %d", nProfile); AAC_EXTR_VEB("AACExtractor::AACExtractor--num channels = %d", nChannelNum); AAC_EXTR_VEB("AACExtractor::AACExtractor--config_info[0]=%x", config_info[0]); AAC_EXTR_VEB("AACExtractor::AACExtractor--config_info[1]=%x", config_info[1]); mMeta = new MetaData; mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC); mMeta->setInt32(kKeySampleRate, nSampleRate); #ifndef ANDROID_DEFAULT_CODE mMeta->setData(kKeyCodecConfigInfo, 0, config_info, 2); #endif //#ifndef ANDROID_DEFAULT_CODE mMeta->setInt32(kKeyChannelCount, nChannelNum); #endif mMeta->setInt32(kKeyBitRate, nBitRate); // need to add configinfo fix me mMeta->setInt32(kKeyIsAACADIF, bIsADIF); off64_t fileSize; if (mDataSource->getSize(&fileSize) == OK) { nDurationUs = 8000000LL * ((float)(fileSize - mFirstFramePos) / nBitRate); mMeta->setInt64(kKeyDuration, nDurationUs); AAC_EXTR_DBG("AACExtractor::AACExtractor--fileSize=%d", fileSize); AAC_EXTR_DBG("AACExtractor::AACExtractor--nDurationUs=%d", (int32_t)nDurationUs); } #if 0 /* prevent too much time, vbr only below 50m can get accurate duration before play */ if(fileSize < 50000000){ uint32_t sr = nSampleRate; if (sr == 0){ return; } off64_t numFrames = 0; size_t frameSize = 0; int64_t duration = 0; if (fileSize != 0) { while (meta_offset < fileSize) { if ((frameSize = getAdtsFrameLength(mDataSource, meta_offset, NULL)) == 0) { return; } meta_offset += frameSize; numFrames ++; } // Round up and get the duration int64_t nFrameDurationUs = (1024 * 1000000ll + (sr - 1)) / sr; duration = numFrames * nFrameDurationUs; if(duration != 0){ mMeta->setInt64(kKeyDuration, duration); } } } #endif if (0 == bIsADIF) { mIsADTS = true; } else { mIsADTS = false; } mInitCheck = OK; // get iTunes-style gapless info if present ID3 id3(mDataSource); if (id3.isValid()) { ID3::Iterator *com = new ID3::Iterator(id3, "COM"); if (com->done()) { delete com; com = new ID3::Iterator(id3, "COMM"); } while (!com->done()) { String8 commentdesc; String8 commentvalue; com->getString(&commentdesc, &commentvalue); const char *desc = commentdesc.string(); const char *value = commentvalue.string(); // first 3 characters are the language, which we don't care about if (strlen(desc) > 3 && strcmp(desc + 3, "iTunSMPB") == 0) { int32_t delay, padding; if (sscanf(value, " %*x %x %x %*x", &delay, &padding) == 2) { mMeta->setInt32(kKeyEncoderDelay, delay); mMeta->setInt32(kKeyEncoderPadding, padding); } break; } com->next(); } delete com; com = NULL; } } status_t MtkAACExtractor::calculateAdtsAverageBitRate(const sp<DataSource> &source,off_t filePos,uint32_t header, uint32_t sampleFreqIndex,uint32_t *pBitRate) { //estimate duration AAC_EXTR_DBG("calculateAverageBitRate filePos %d header 0x%08x sampleFreqIndex %d",filePos,header,sampleFreqIndex); uint8_t tmp[7]; uint32_t frameNum = 0; uint32_t readedDataSize = 0; uint32_t frameSize; uint32_t frameNumPre = 0; uint32_t readedDataSizePre = 0; while (frameNum < 100) { if (source->readAt(filePos, tmp, 7) != 7) { break; } uint32_t headerTmp = U32_AT(tmp); if ((headerTmp & kMask) == (header & kMask)) { frameSize = ((tmp[3] & 0x03) << 11) | (tmp[4] << 3) | ((tmp[5] & 0xe0) >> 5); if (frameSize > 7) { readedDataSize += frameSize; frameNum++; filePos += frameSize; // fix me for the end frame is a bad frame if (30 == frameNum) { frameNumPre = frameNum; readedDataSizePre = readedDataSize; } } else { filePos ++; } } else { filePos++; } } if (frameNum == 100 && readedDataSize > readedDataSizePre) { frameNum -= frameNumPre; readedDataSize -= readedDataSizePre; } if (frameNum > 0 && readedDataSize > 0) { *pBitRate = (float)readedDataSize * 8 / frameNum / 1024 * AACSampleFreqTable[sampleFreqIndex]; } else { return BAD_VALUE; } return OK; } size_t MtkAACExtractor::countTracks() { return mInitCheck != OK ? 0 : 1; } sp<MediaSource> MtkAACExtractor::getTrack(size_t index) { if (mInitCheck != OK || index != 0) { return NULL; } return new MtkAACSource( mMeta, mDataSource, mFirstFramePos, mFixedHeader, mIsADTS); } sp<MetaData> MtkAACExtractor::getTrackMetaData(size_t index, uint32_t flags) { if (mInitCheck != OK || index != 0) { return NULL; } return mMeta; } uint32_t MtkAACExtractor::flags() const { if (mIsADTS) { return CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_PAUSE | CAN_SEEK; } else { #ifdef ENABLE_USE_TABLE_OF_CONTENT #ifdef ADIF_MANDATORY_SEEK return CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_PAUSE | CAN_SEEK; #endif #endif return CAN_PAUSE; } } sp<MetaData> MtkAACExtractor::MakeAACCodecSpecificData( unsigned profile, unsigned sampling_freq_index, unsigned channel_configuration) { sp<MetaData> meta = new MetaData; meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC); meta->setInt32(kKeySampleRate, AACSampleFreqTable[sampling_freq_index]); meta->setInt32(kKeyChannelCount, channel_configuration); static const uint8_t kStaticESDS[] = { 0x03, 22, 0x00, 0x00, // ES_ID 0x00, // streamDependenceFlag, URL_Flag, OCRstreamFlag 0x04, 17, 0x40, // Audio ISO/IEC 14496-3 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 2, // AudioSpecificInfo follows // oooo offf fccc c000 // o - audioObjectType // f - samplingFreqIndex // c - channelConfig }; sp<ABuffer> csd = new ABuffer(sizeof(kStaticESDS) + 2); memcpy(csd->data(), kStaticESDS, sizeof(kStaticESDS)); csd->data()[sizeof(kStaticESDS)] = ((profile + 1) << 3) | (sampling_freq_index >> 1); csd->data()[sizeof(kStaticESDS) + 1] = ((sampling_freq_index << 7) & 0x80) | (channel_configuration << 3); AAC_EXTR_DBG("AACExtractor::MakeAACCodecSpecificData--csd->data()[%d]=%x", sizeof(kStaticESDS), csd->data()[sizeof(kStaticESDS)]); AAC_EXTR_DBG("AACExtractor::MakeAACCodecSpecificData--csd->data()[%d]=%x", sizeof(kStaticESDS) + 1, csd->data()[sizeof(kStaticESDS) + 1]); meta->setData(kKeyESDS, 0, csd->data(), csd->size()); return meta; } //////////////////////////////////////////////////////////////////////////////// MtkAACSource::MtkAACSource( const sp<MetaData> &meta, const sp<DataSource> &source, off_t first_frame_pos, uint32_t fixed_header, bool isADTS) : mMeta(meta), mDataSource(source), mFirstFramePos(first_frame_pos), mFixedHeader(fixed_header), mCurrentPos(0), mCurrentTimeUs(0), mStarted(false), mGroup(NULL), mIsADTS(isADTS), mAACFrameLenDecoderPtr(NULL), // for aac seek table mObserver(NULL), mFrameDurationUs(0) { void *pAwe = NULL; meta->findPointer(kKeyDataSourceObserver, &pAwe); mObserver = (AwesomePlayer *) pAwe; } MtkAACSource::~MtkAACSource() { if (mStarted) { stop(); } } status_t MtkAACSource::start(MetaData *) { CHECK(!mStarted); #ifdef ENABLE_USE_TABLE_OF_CONTENT if (!mIsADTS) { mAACFrameLenDecoderPtr = new AACFrameLenDecoder(mMeta, mDataSource, mFirstFramePos); if (NULL == mAACFrameLenDecoderPtr) { return ERROR_UNSUPPORTED; } if (!mAACFrameLenDecoderPtr->initAACDec()) { //free(mAACFrameLenDecoderPtr); delete mAACFrameLenDecoderPtr; mAACFrameLenDecoderPtr = NULL; return ERROR_UNSUPPORTED; } AAC_EXTR_DBG("Mtk AACSource::start--ADIF initAACDec OK"); } int32_t nSampleRate; if (mMeta->findInt32(kKeySampleRate, &nSampleRate)) { mFrameDurationUs = 1024.0 / nSampleRate * 1000000.0; AAC_EXTR_DBG("Per Frame Duration =%d,First frame pos =%ld", mFrameDurationUs, mFirstFramePos); startTOCThread(mFirstFramePos); } #endif mGroup = new MediaBufferGroup; const size_t kMaxFrameSize = MEDIA_BUFFER_LEN; mGroup->add_buffer(new MediaBuffer(kMaxFrameSize)); mCurrentPos = mFirstFramePos; mCurrentTimeUs = 0; mStarted = true; return OK; } status_t MtkAACSource::stop() { CHECK(mStarted); // for AAC seek table ---> #ifdef ENABLE_USE_TABLE_OF_CONTENT //for seek table stopTOCThread(); if (NULL != mAACFrameLenDecoderPtr) { free(mAACFrameLenDecoderPtr); mAACFrameLenDecoderPtr = NULL; } #endif // <--- for AAC seek table delete mGroup; mGroup = NULL; mStarted = false; return OK; } sp<MetaData> MtkAACSource::getFormat() { return mMeta; } // for AAC seek table ---> status_t MtkAACSource::getNextFramePos(off_t *pCurPos, off_t *pNextPos, int64_t *frameTsUs) { off_t curPos = *pCurPos; if (mIsADTS) { uint8_t tmp[7]; size_t frame_size; for (;;) { ssize_t n = mDataSource->readAt(curPos, tmp, 7); if (n < 7) { return ERROR_END_OF_STREAM; } uint32_t header = U32_AT(tmp); if ((mFixedHeader & kMask) == (header & kMask)) { frame_size = ((tmp[3] & 0x03) << 11) | (tmp[4] << 3) | ((tmp[5] & 0xe0) >> 5); if (frame_size > 7) { *pCurPos = curPos; *pNextPos = curPos + frame_size; *frameTsUs = mFrameDurationUs; return OK; } } curPos++; } return ERROR_END_OF_STREAM; } else { *frameTsUs = mFrameDurationUs; return mAACFrameLenDecoderPtr->getNextFramePos(pCurPos, pNextPos); } } status_t MtkAACSource::sendDurationUpdateEvent(int64_t duration) { if (mObserver) { AAC_EXTR_DBG("AAC Seek Table duration %lld", duration); mObserver->postDurationUpdateEvent(duration); } return OK; } status_t MtkAACSource::read( MediaBuffer **out, const ReadOptions *options) { *out = NULL; if (mIsADTS) { int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options != NULL && options->getSeekTo(&seekTimeUs, &mode)) { #ifdef ENABLE_USE_TABLE_OF_CONTENT #ifdef ADTS_MANDATORY_SEEK status_t status = getFramePos(seekTimeUs, &mCurrentTimeUs, &mCurrentPos, true); #else status_t status = getFramePos(seekTimeUs, &mCurrentTimeUs, &mCurrentPos, false); #endif if (ERROR_END_OF_STREAM == status) { return ERROR_END_OF_STREAM; } else if (OK != status) { int32_t bitrate; if (!mMeta->findInt32(kKeyBitRate, &bitrate)) { // bitrate is in bits/sec. AAC_EXTR_INFO("no bitrate"); return ERROR_UNSUPPORTED; } mCurrentTimeUs = seekTimeUs; mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 8000000; // estimate duration } #else int32_t bitrate; if (!mMeta->findInt32(kKeyBitRate, &bitrate)) { // bitrate is in bits/sec. AAC_EXTR_INFO("no bitrate"); return ERROR_UNSUPPORTED; } mCurrentTimeUs = seekTimeUs; mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 8000000; // estimate duration #endif // for aac seek table AAC_EXTR_DBG("MtkAACSource::read--seek seekTimeUs = %dus", (int32_t)(seekTimeUs)); AAC_EXTR_DBG("MtkAACSource::read--seek mCurrentTimeUs = %dus", (int32_t)(mCurrentTimeUs)); AAC_EXTR_DBG("MtkAACSource::read--seek mCurrentPos = %d", mCurrentPos); } MediaBuffer *buffer; status_t err = mGroup->acquire_buffer(&buffer); if (err != OK) { return err; } size_t frame_size; for (;;) { ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), 7); if (n < 7) { buffer->release(); buffer = NULL; return ERROR_END_OF_STREAM; } uint32_t header = U32_AT((const uint8_t *)buffer->data()); const uint8_t *tmp = (const uint8_t *)buffer->data(); if ((mFixedHeader & kMask) == (header & kMask)) { frame_size = ((tmp[3] & 0x03) << 11) | (tmp[4] << 3) | ((tmp[5] & 0xe0) >> 5); if (frame_size > 9) { if (tmp[1] & 0x01) //no crc { frame_size -= 7; mCurrentPos += 7; } else { frame_size -= (7 + 2); mCurrentPos += (7 + 2); } break; } } mCurrentPos++; } CHECK(frame_size <= buffer->size()); ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), frame_size); if (n < (ssize_t)frame_size) { buffer->release(); buffer = NULL; return ERROR_END_OF_STREAM; } buffer->set_range(0, frame_size); buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs); mCurrentPos += frame_size; int32_t sample_rate; if (!mMeta->findInt32(kKeySampleRate, &sample_rate)) { // bitrate is in bits/sec. AAC_EXTR_WARN("no sample_rate"); return ERROR_UNSUPPORTED; } mCurrentTimeUs += 1024 * 1000000 / sample_rate; *out = buffer; } else { int64_t seekTimeUs = -1; ReadOptions::SeekMode mode; if (options != NULL && options->getSeekTo(&seekTimeUs, &mode)) { #ifdef ENABLE_USE_TABLE_OF_CONTENT #ifdef ADIF_MANDATORY_SEEK status_t status = getFramePos(seekTimeUs, &mCurrentTimeUs, &mCurrentPos, true); if (OK != status) { return status; } AAC_EXTR_DBG("MtkAACSource::read--seek seekTimeUs = %dus", (int32_t)(seekTimeUs)); AAC_EXTR_DBG("MtkAACSource::read--seek mCurrentTimeUs = %dus", (int32_t)(mCurrentTimeUs)); AAC_EXTR_DBG("MtkAACSource::read--seek mCurrentPos = %d", mCurrentPos); #else off_t currentPos; int64_t currentTimeUs; status_t status = getFramePos(seekTimeUs, &currentTimeUs, &currentPos, false); if (ERROR_END_OF_STREAM == status) { return ERROR_END_OF_STREAM; } else if (OK != status) { return ERROR_END_OF_STREAM; } else { mCurrentPos = currentPos; mCurrentTimeUs = currentTimeUs; } #endif #else //seekTimeUs = mCurrentTimeUs; seekTimeUs = 0; mCurrentPos = 0; #endif } else { seekTimeUs = -1; } MediaBuffer *buffer; status_t err = mGroup->acquire_buffer(&buffer); if (err != OK) { return err; } uint32_t nReadSize = ADIF_DEC_BUFFER_SIZE;//1536; CHECK(nReadSize <= buffer->size()); ssize_t n = mDataSource->readAt(mCurrentPos, ((uint8_t *)buffer->data()), nReadSize); if (n <= 0) { buffer->release(); buffer = NULL; return ERROR_END_OF_STREAM; } nReadSize = n; // for the end of the file buffer->set_range(0, nReadSize); if (seekTimeUs >= 0) { buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs); } mCurrentPos += nReadSize; *out = buffer; } return OK; } sp<MetaData> MtkAACExtractor::getMetaData() { sp<MetaData> meta = new MetaData; if (mInitCheck != OK) { return meta; } meta->setCString(kKeyMIMEType, "audio/aac"); ID3 id3(mDataSource); if (!id3.isValid()) { return meta; } struct Map { int key; const char *tag1; const char *tag2; }; static const Map kMap[] = { { kKeyAlbum, "TALB", "TAL" }, { kKeyArtist, "TPE1", "TP1" }, { kKeyAlbumArtist, "TPE2", "TP2" }, { kKeyComposer, "TCOM", "TCM" }, { kKeyGenre, "TCON", "TCO" }, { kKeyTitle, "TIT2", "TT2" }, { kKeyYear, "TYE", "TYER" }, { kKeyAuthor, "TXT", "TEXT" }, { kKeyCDTrackNumber, "TRK", "TRCK" }, { kKeyDiscNumber, "TPA", "TPOS" }, { kKeyCompilation, "TCP", "TCMP" }, }; static const size_t kNumMapEntries = sizeof(kMap) / sizeof(kMap[0]); for (size_t i = 0; i < kNumMapEntries; ++i) { ID3::Iterator *it = new ID3::Iterator(id3, kMap[i].tag1); if (it->done()) { delete it; it = new ID3::Iterator(id3, kMap[i].tag2); } if (it->done()) { delete it; continue; } String8 s; it->getString(&s); delete it; meta->setCString(kMap[i].key, s); } size_t dataSize; String8 mime; const void *data = id3.getAlbumArt(&dataSize, &mime); if (data) { meta->setData(kKeyAlbumArt, MetaData::TYPE_NONE, data, dataSize); meta->setCString(kKeyAlbumArtMIME, mime.string()); } return meta; } bool SniffMtkAAC( const sp<DataSource> &source, String8 *mimeType, float *confidence, sp<AMessage> *meta) { off_t pos = 0; uint32_t header; uint32_t nSampleFreqIndex; uint32_t nBitRate=0; uint32_t nProfile; uint32_t nChannelNum; int32_t bIsADIF; if (!getAACInfo(source, &pos, &header, &nSampleFreqIndex, &nBitRate, &nProfile, &nChannelNum, &bIsADIF)) { return false; } *meta = new AMessage; (*meta)->setInt64("offset", pos); (*meta)->setInt32("header", header); (*meta)->setInt32("samplefreqidx", nSampleFreqIndex); (*meta)->setInt32("bitrate", nBitRate); (*meta)->setInt32("profile", nProfile); (*meta)->setInt32("channelnum", nChannelNum); (*meta)->setInt32("isadif", bIsADIF); *mimeType = MEDIA_MIMETYPE_AUDIO_AAC; // not define new type *confidence = 0.3f; return true; } bool FastSniffAAC( const sp<DataSource> &source, String8 *mimeType, float *confidence, sp<AMessage> *meta) { off_t inout_pos = 0; int32_t bIsADIF = false; bool valid = false; off_t test_header; off_t pos = 0; if (inout_pos == 0) { // Skip an optional ID3 header if syncing at the very beginning // of the datasource. for (;;) { uint8_t id3header[10]; if (source->readAt(inout_pos, id3header, sizeof(id3header)) < (ssize_t)sizeof(id3header)) { return false; } if (memcmp("ID3", id3header, 3)) { break; } size_t len = ((id3header[6] & 0x7f) << 21) | ((id3header[7] & 0x7f) << 14) | ((id3header[8] & 0x7f) << 7) | (id3header[9] & 0x7f); len += 10; inout_pos += len; } } pos = inout_pos; uint8_t tmpBuf[4]; if (source->readAt(pos, tmpBuf, 4) != 4) { return false; } if (tmpBuf[0] == 0x41 && // 'A' tmpBuf[1] == 0x44 && // 'D' tmpBuf[2] == 0x49 && // 'I' tmpBuf[3] == 0x46) // 'F' { bIsADIF = true; valid = true; } else if (isAACADTSHeader(tmpBuf)) ///adts { uint32_t header = U32_AT(tmpBuf); uint8_t tmp[7]; if (source->readAt(pos, tmp, 7) != 7) { return false; } size_t frame_size = ((tmp[3] & 0x03) << 11) | (tmp[4] << 3) | ((tmp[5] & 0xe0) >> 5); if (frame_size <= 7) { return false; } off_t test_pos = pos + frame_size; valid = true; for (int j = 0; j < 3; ++j) { if (source->readAt(test_pos, tmp, 7) < 7) { valid = false; break; } test_header = U32_AT(tmp); if (header != 0 && (test_header & kMask) != (header & kMask)) // compare frame fixed header { valid = false; break; } size_t test_frame_size = ((tmp[3] & 0x03) << 11) | (tmp[4] << 3) | ((tmp[5] & 0xe0) >> 5); if (test_frame_size <= 7) // compare frame fixed header { valid = false; break; } test_pos += test_frame_size; } } if (valid == false) { return false; } *meta = new AMessage; (*meta)->setInt64("offset", pos); (*meta)->setInt32("header", test_header); (*meta)->setInt32("isadif", bIsADIF); *mimeType = MEDIA_MIMETYPE_AUDIO_AAC; // not define new type *confidence = 0.3f; return true; } } // namespace android
884c5aeb15cfaad64c70bcd07a795bbfaf611f5d
816917c3fbec3514a28a12e02742f9f1b7a7cde4
/Plugins/DungeonGeneratorPlugin/Source/DungeonGeneratorEditorMode/Public/DungeonGeneratorEditorMode.h
584fced8bdc12e379bd5d417fcef4c809a822952
[ "MIT" ]
permissive
liljohnak/DungeonGenerator
af60fbb0ef54cbfa2262304c053ebd09e2e681d9
52702d1df7a677cb39f39711765b2ac8f3aa87bf
refs/heads/main
2023-09-03T12:15:59.626213
2021-11-18T07:32:36
2021-11-18T07:32:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
402
h
DungeonGeneratorEditorMode.h
// Copyright (c) 2021 Orfeas Eleftheriou #pragma once #include "CoreMinimal.h" #include "Modules/ModuleManager.h" class FDungeonGeneratorEditorMode : public IModuleInterface { public: /* This will get called when the editor loads the module */ virtual void StartupModule() override; /* This will get called when the editor unloads the module */ virtual void ShutdownModule() override; };
018b14a4919758b092772cb0834fff947b9f0c62
165a3641f8cb76170dd074cfd25b9809ae2e5afc
/Faculty.cpp
328160362205b422777260d4dfb8ffdf2ac6d274
[]
no_license
JustinCalma/CECS-282-Project-1-Part-3-GITHUB-
1c35028ea012ee5ca3922244323ad62df49ae942
f90b7a41351c3b34221a1dc2dc8286ba093cb8bf
refs/heads/main
2023-01-12T22:05:17.030212
2020-11-19T06:24:30
2020-11-19T06:24:30
314,155,539
0
0
null
null
null
null
UTF-8
C++
false
false
2,724
cpp
Faculty.cpp
// Faculty Implemenation File #include "Faculty.h" #include <iostream> #include <string> using namespace std; // Default constructor Faculty::Faculty():Employee() { // Set the class attributes to be the default values level = AS; education = Education(); // Use the default constructor of class Education } // Argument Constructor Faculty::Faculty(string lName, string fName, string idNum, Sex gender, string bdate, Level lvl, Education edu):Employee(lName, fName, idNum, gender, bdate) { // Set the class attributes to be the passed in values level = lvl; education = edu; } // Getter for Level Level Faculty::getLevel() { // Return the level attribute return level; } // Getter for Education Education Faculty::getEducation() { // Return the Education object return education; } // Calculate the monthly salary based on the faculty's level float Faculty::monthlyEarning() { // If the Faculty level is Assistant Professor if (level == AS) { // Monthly Salary for Assistant Professor is equal to FACULTY_MONTHLY_SALARY return FACULTY_MONTHLY_SALARY; } else if (level == AO) { // If the Faculty level is Associate Professor // Monthly Salary for Associate Professor is equal to 1.2 * FACULTY_MONTHLY_SALARY return (1.2 * FACULTY_MONTHLY_SALARY); } else { // Else, the Faculty level is Professor // Monthly Salary for Professor is equal to 1.4 * FACULTY_MONTHLY_SALARY return (1.4 * FACULTY_MONTHLY_SALARY); } // Return the calculated monthly Earning return 0; } // Output the data of Faculty to the user void Faculty::putData() { // Call putData from Employee and override it Employee::putData(); // Output the levl of the professor and Monthly Salary // Use a switch case branch to check the level of the employee switch(level) { // If the level is Assistant Professor case AS: cout << "Assistant Professor" << endl; break; // If the level is Associate Professor case AO: cout << "Associate Professor" << endl; break; // If the level is Full Professor case FU: cout << "Full Professor" << endl; break; } cout << "Monthly Salary: " << monthlyEarning() << endl; } //-------------------------------------------------------------- PART 3 --------------------------------------------------------------// // Function to get the data of Faculty class void Faculty::getData() { // Create a temp variable for level int temp; // Call the getData() function from Employee to get the data of Employee Employee::getData(); // Get the level of the Faculty cout << "Enter the level: AS(0), AO(1), FU(2): "; cin >> temp; level = static_cast<Level>(temp); education.getEducation(); }
2aa693e4ff5cf025eab47e8ab01d6095177ec019
ec04bfee9757a686def18718dda318bbaa397e13
/libraries/protocol/include/achain/protocol/achain_operations.hpp
8373084cadd64c5d3c052b6701cb1480d81a4044
[]
no_license
alexeyqian/achain
c4b97b4081a6996c0d683eedfdba07c7b9d720a0
763fd765cad1ad333980500817fbdab5a43ce4a7
refs/heads/master
2020-03-29T06:48:33.117750
2018-12-26T15:56:04
2018-12-26T15:56:04
149,641,335
0
0
null
null
null
null
UTF-8
C++
false
false
3,646
hpp
achain_operations.hpp
#pragma once #include <achain/protocol/base.hpp> #include <achain/protocol/block_header.hpp> #include <achain/protocol/asset.hpp> #include <fc/utf8.hpp> #include <fc/crypto/equihash.hpp> #include <string> #include <vector> namespace achain{ namespace protocol { using std::string; using std::vector; using fc::optional; using fc::static_variant; inline void validate_account_name(const string& name){ FC_ASSERT(is_valid_account_name (name), "Account name ${n} is invalide", ("n", name)); } inline void validate_permlink(const string& permlink){ FC_ASSERT(permlink.size() < ACHAIN_MAX_PERMLINK_LENGTH, "Permlink is too long."); FC_ASSERT(fc::is_utf8(permlink), "Permlink is not formatted in UTF8"); } struct account_create_opration :public base_operation{ asset fee; account_name_type creator; account_name_type new_account_name; authority owner; authority active; authority posting; public_key_type memo_key; string json_metadata; void validate() const; void get_required_active_authorities(flat_set<account_name_type>& a) const{ a.insert(creator);} }; struct account_create_with_delegation_operation : public base_operation { asset fee; asset delegation; account_name_type creator; account_name_type new_account_name; authority owner; authority active; authority posting; public_key_type memo_key; string json_metadata; extensions_type extensions; void validate()const; void get_required_active_authorities( flat_set<account_name_type>& a )const{ a.insert(creator); } }; struct account_update_operation : public base_operation { account_name_type account; optional< authority > owner; optional< authority > active; optional< authority > posting; public_key_type memo_key; string json_metadata; void validate()const; void get_required_owner_authorities( flat_set<account_name_type>& a )const { if( owner ) a.insert( account ); } void get_required_active_authorities( flat_set<account_name_type>& a )const { if( !owner ) a.insert( account ); } }; struct comment_operation: public base_operation{ account_name_type parent_author; string parent_permlink; account_name_type author; string permlink; string title; string body; string json_metadata; void validte() const; void get_required_posting_authorities(flat_set<account_name_type>& a) const{a.insert(author);} }; struct beneficiary_route_type { beneficiary_route_type() {} beneficiary_route_type( const account_name_type& a, const uint16_t& w ) : account( a ), weight( w ){} account_name_type account; uint16_t weight; // For use by std::sort such that the route is sorted first by name (ascending) bool operator < ( const beneficiary_route_type& o )const { return account < o.account; } }; struct comment_payout_beneficiaries { vector< beneficiary_route_type > beneficiaries; void validate()const; }; typedef static_variant< comment_payout_beneficiaries > comment_options_extension; typedef flat_set< comment_options_extension > comment_options_extensions_type; }}
3a5e8c7b7e427c80360c0af920c657d836025954
cde3f5db477212df5286cad5ff254c4038f11103
/src/Qt_Ext/QGLZoomableImageViewer.cpp
88c7eab6cd6dc1740d925b8b1eb6f80903a310bb
[ "MIT" ]
permissive
RoLiLab/tracking_microscope
a82b72c5dfe868b468ce8301aeb4f4558f6afa4b
ec68a217d252244bb850f05ab13f344aa2fbd74a
refs/heads/master
2021-06-25T11:12:22.972389
2017-09-11T05:19:52
2017-09-11T05:22:01
103,092,605
6
2
null
null
null
null
UTF-8
C++
false
false
5,122
cpp
QGLZoomableImageViewer.cpp
/////////////////////////////////////////////////////////// // // QGLZoomableImageViewer.cpp // Copyright (c) 2013 - Kane Lab. All Rights Reserved // // Jeremy Todd // ////////////////////////////////////////////////////////////////////////////// #include "QGLZoomableImageViewer.h" #include "ZoomRect.h" namespace { const float WHEEL_ZOOM_SENSITIVITY= 1.0f/1000.0f; //!< The amount we scale our visible rect for each detent of a wheel mouse const int MIN_ZOOM_RECT_SIZE= 16; //!< Our zoom rect width/height can't get smaller than this } // end file-scope UI::QGLZoomableImageViewer::QGLZoomableImageViewer( QWidget* pParent/*= nullptr */ ) : QGLImageViewer(pParent) { } // end UI::QGLZoomableImageViewer::QGLZoomableImageViewer() void UI::QGLZoomableImageViewer::mousePressEvent( QMouseEvent* pEvent ) { // Ignore the event if we have no image if( !HasImage() ) { pEvent->ignore(); return; } // On right click, set our zoom in full size if( pEvent->buttons() & Qt::RightButton ) { if( GetZoomRect().isEmpty() || GetZoomRect().size() == GetImageSize() ) { // If we're zoomed out full, reset our zoom in full size m_sizeZoomInFull= checked_QSize(); } else { m_sizeZoomInFull= GetZoomRect().size(); } // end else not zoomed out full pEvent->accept(); return; } // end if right click // Start a drag at the current cursor location m_posDrag= pEvent->pos(); m_rectDragOriginal= GetZoomRect().isEmpty() ? QRect(QPoint(0,0), GetImageSize()) : GetZoomRect(); pEvent->accept(); // added by DH } // end UI::QGLZoomableImageViewer::mousePressEvent() void UI::QGLZoomableImageViewer::mouseDoubleClickEvent( QMouseEvent* pEvent ) { // Ignore the event if we have no image if( !HasImage() ) { pEvent->ignore(); return; } // Set a default zoom in full size if necessary if( !m_sizeZoomInFull.valid() ) m_sizeZoomInFull= GetImageSize() / 5; // Check whether we're zoomed in at or past our zoom in full size if( GetZoomRect().isValid() && GetZoomRect().width() <= m_sizeZoomInFull.cast().width() ) { // Zoom out full SetZoomRect( QRect(QPoint(0,0), GetImageSize()) ); } else { // Jump to our zoom in size float fScale= (float)(m_sizeZoomInFull.cast().width()) / GetImageSize().width(); zoom( pEvent->pos(), fScale ); } // end else zooming out full } // end UI::QGLZoomableImageViewer::mouseDoubleClickEvent() void UI::QGLZoomableImageViewer::mouseReleaseEvent( QMouseEvent* pEvent ) { // Ignore the event if we have no image, or if a drag isn't in progress if( !HasImage() || !m_posDrag.valid() ) { pEvent->ignore(); return; } // End our drag and accept the event m_posDrag= checked_QPoint(); m_rectDragOriginal= checked_QRect(); pEvent->accept(); } // end UI::QGLZoomableImageViewer::mouseReleaseEvent() void UI::QGLZoomableImageViewer::mouseMoveEvent( QMouseEvent* pEvent ) { // Ignore the event if we have no image, or if a drag isn't in progress if( !HasImage() || !m_posDrag.valid() ) { pEvent->ignore(); return; } // Compute our x and y delta in cursor units, then scale them to zoom rect units QRect rectZoom= m_rectDragOriginal; QPoint posCursorDelta= pEvent->pos() - m_posDrag; float fScaleX= (float)(rectZoom.width()) / GetDrawRect().width(), fScaleY= (float)(rectZoom.height()) / GetDrawRect().height(); QPoint posScaledDelta( (int)(roundf(fScaleX * posCursorDelta.x())), (int)(roundf(fScaleY * posCursorDelta.y())) ); // Now pan our zoom rect and trim to valid values int xAdjusted= rectZoom.x() - posScaledDelta.x(), yAdjusted= rectZoom.y() - posScaledDelta.y(); if( xAdjusted < 0 ) xAdjusted= 0; else if( xAdjusted > GetImageSize().width()-rectZoom.width() ) xAdjusted= GetImageSize().width()-rectZoom.width(); if( yAdjusted < 0 ) yAdjusted= 0; else if( yAdjusted > GetImageSize().height()-rectZoom.height() ) yAdjusted= GetImageSize().height()-rectZoom.height(); // Set our new zoom rect and accept the event QRect newWindow = QRect(QPoint(xAdjusted, yAdjusted), rectZoom.size()); curpos = newWindow.center(); SetZoomRect(newWindow); pEvent->accept(); } // end UI::QGLZoomableImageViewer::mouseMoveEvent() void UI::QGLZoomableImageViewer::wheelEvent( QWheelEvent* pEvent ) { // Ignore the event if we have no image if( !HasImage() ) { pEvent->ignore(); return; } // Determine our scaling factor and zoom float fScale= 1.0f / (1.0f + WHEEL_ZOOM_SENSITIVITY * abs(pEvent->angleDelta().y())); if( pEvent->angleDelta().y() < 0.0f ) fScale= 1.0f / fScale; zoom(curpos, fScale); // Accept this event since we handled it pEvent->accept(); } // end UI::QGLZoomableImageViewer::wheelEvent() void UI::QGLZoomableImageViewer::zoom( const QPoint& posCursor_, float fScale ) { // Compute our new zoom rect and set it QRect rectCurrent= GetZoomRect().isEmpty() ? QRect(QPoint(0,0), GetImageSize()) : GetZoomRect(); QPoint posCursor= posCursor_ - GetDrawRect().topLeft(); QRect rectScaled= Image::ScaledZoomRect( rectCurrent, GetImageSize(), GetDrawRect().size(), posCursor, fScale, MIN_ZOOM_RECT_SIZE ); curpos = rectScaled.center(); SetZoomRect( rectScaled ); } // end UI::QGLZoomableImageViewer::zoom()
13f0a4cf23d8e195b9681485fdd1bdf9e097ac62
270a5e9ac132cd088c0e52bbe7acd014494169ab
/rendering/Crosshair.cpp
4d144253f6fe5502fcc8ce205322c51302a9502c
[]
no_license
hegerdes/GalaxyFight
84bcf51775c456a4f721043b4e3e43b98971a74d
e0e2a82b699d507ffc46b86b00ab7f53c00157f4
refs/heads/master
2022-04-20T20:56:26.815955
2020-04-16T21:15:45
2020-04-16T21:15:45
178,596,537
0
0
null
null
null
null
UTF-8
C++
false
false
2,284
cpp
Crosshair.cpp
#include "Crosshair.hpp" namespace asteroids { Crosshair::Crosshair(float red, float green, float blue, int width, int height) { r = (red > 255) ? 255 : red; g = (green > 255) ? 255 : green; b = (blue > 255) ? 255 : blue; m_width = width; m_height = height; c_dimension1 = width/200; c_dimension2 = height/15 - height/30; offset = height/60; } void Crosshair::render() { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, m_width, 0, m_height, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor3f(r, g, b); glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); glBegin(GL_QUADS); glVertex3f(m_width/2 + c_dimension1, m_height/2 + offset, 0.0f); glVertex3f(m_width/2 + c_dimension1, m_height/2 + offset + c_dimension2, 0.0f); glVertex3f(m_width/2 - c_dimension1, m_height/2 + offset + c_dimension2, 0.0f); glVertex3f(m_width/2 - c_dimension1, m_height/2 + offset, 0.0f); glEnd(); glBegin(GL_QUADS); glVertex3f(m_width/2 + c_dimension1, m_height/2 - offset, 0.0f); glVertex3f(m_width/2 + c_dimension1, m_height/2 - (offset + c_dimension2), 0.0f); glVertex3f(m_width/2 - c_dimension1, m_height/2 - (offset + c_dimension2), 0.0f); glVertex3f(m_width/2 - c_dimension1, m_height/2 - offset, 0.0f); glEnd(); glBegin(GL_QUADS); glVertex3f(m_width/2 + offset, m_height/2 + c_dimension1, 0.0f); glVertex3f(m_width/2 + offset + c_dimension2, m_height/2 + c_dimension1, 0.0f); glVertex3f(m_width/2 + offset + c_dimension2, m_height/2 - c_dimension1, 0.0f); glVertex3f(m_width/2 + offset, m_height/2 - c_dimension1, 0.0f); glEnd(); glBegin(GL_QUADS); glVertex3f(m_width/2 - offset, m_height/2 + c_dimension1, 0.0f); glVertex3f(m_width/2 - (offset + c_dimension2), m_height/2 + c_dimension1, 0.0f); glVertex3f(m_width/2 - (offset + c_dimension2), m_height/2 - c_dimension1, 0.0f); glVertex3f(m_width/2 - offset, m_height/2 - c_dimension1, 0.0f); glEnd(); glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } }
4a779228ae526d5b2a639bd99faa6dc0c030e833
569d64661f9e6557022cc45428b89eefad9a6984
/code/gameholder/buff_func_stun.h
fc1f10ccf52c8d2f3cd5b865cfb75a3db368d420
[]
no_license
dgkang/ROG
a2a3c8233c903fa416df81a8261aab2d8d9ac449
115d8d952a32cca7fb7ff01b63939769b7bfb984
refs/heads/master
2020-05-25T02:44:44.555599
2019-05-20T08:33:51
2019-05-20T08:33:51
187,584,950
0
1
null
2019-05-20T06:59:06
2019-05-20T06:59:05
null
UTF-8
C++
false
false
364
h
buff_func_stun.h
#ifndef buff_func_stun_h__ #define buff_func_stun_h__ #include "buff_func_base.h" /* * 眩晕功能 */ class BuffFuncStun : public BuffFuncBase { public: BuffFuncStun(); virtual ~BuffFuncStun(); virtual void Start(); virtual void ResetLifeTime(int32 lifeTime); private: void EnterStun(int32 time); }; #endif // buff_func_stun_h__
98df78f13f9f5c02a863754f224ce89cf074a221
80bfb83dd1d8a69a030a1150d3e415dbb2183cac
/PA2TransformationMatrix/main.cpp
f87f2e35bf42179773d372664046f4e159340040
[]
no_license
eeeerin/TransformationMatrix
d8280d6d0a27535d0dfa08af20be02cef4ac741a
90c82d51b553f9a3e339293a8740345416400c07
refs/heads/master
2020-03-09T06:11:25.137760
2018-04-08T12:00:34
2018-04-08T12:00:34
128,632,343
0
0
null
null
null
null
UTF-8
C++
false
false
1,951
cpp
main.cpp
//设T1为世界坐标系到一号自身坐标系的欧氏变换矩阵,T2为世界坐标系到二号自身坐标系的欧氏变换矩阵;p为该点在世界坐标系中的坐标,p2为该点在二号自身坐标系中的坐标。则: //p=T1^-1 p1 (为了书写方便,实为齐次坐标变换) //p2=T2 p // // 故欲求p2只需求得T1 T2 // 而已知旋转四元数和平移矩阵求欧氏变换矩阵只需将四元数转换成旋转向量,然后由旋转向量和平移矩阵求得欧氏变换矩阵即可 #include <iostream> #include <cmath> using namespace std; #include <Eigen/Core> #include <Eigen/Geometry> int main( int argc, char** argv ) { // normalize // magnitude = sqrt(w2 + x2 + y2 + z2) // w = w / magnitude // x = x / magnitude // y = y / magnitude // z = z / magnitude //定义两个四元数 Eigen::Quaterniond q1( 0.55,0.3,0.2,0.2 ); Eigen::Quaterniond q2( -0.1,0.3,-0.7,0.2 ); q1=q1.normalized(); q2=q2.normalized(); //将四元数转换成旋转矩阵 Eigen::AngleAxisd rotation_vector1 = Eigen::AngleAxisd ( q1 ); Eigen::Isometry3d T1 = Eigen::Isometry3d::Identity(); T1.rotate( rotation_vector1 ); T1.pretranslate( Eigen::Vector3d ( 0.7,1.1,0.2 ) ); cout << "Transform matrix1 = \n " << T1.matrix() <<endl; //同上求出欧式变换矩阵T2 Eigen::AngleAxisd rotation_vector2 = Eigen::AngleAxisd ( q2 ); Eigen::Isometry3d T2 = Eigen::Isometry3d::Identity(); T2.rotate( rotation_vector2 ); T2.pretranslate( Eigen::Vector3d ( -0.1,0.4,0.8 ) ); cout << "Transform matrix2 = \n " << T2.matrix() <<endl; //计算该点在一号自身坐标系的坐标 Eigen::Vector4d p1 ( 0.5,-0.1,0.2,1 ); //计算p Eigen::Vector4d p = T1.inverse() * p1; cout << "p = \n " << p.transpose() << endl; Eigen::Vector4d p2 = T2 * p; cout << " p2 = \n " << p2.transpose() << endl; return 0; }
e2f06730ecf838933210ca4b212362fb7621bca6
43b8a53b70321de941b9804585c059a211f82081
/src/common.hpp
92a4dbafbbefb129f0abaa835ee95d7e5e83d38a
[ "MIT" ]
permissive
theNded/MinkowskiEngine
d958599256375cffd0cbc64246743111566c4676
ba646df4f2408ea449d7c4e05b3cf10fe4d452cb
refs/heads/master
2020-06-17T09:34:53.256842
2019-07-07T04:19:15
2019-07-07T04:19:15
195,882,557
2
0
MIT
2019-07-08T20:35:17
2019-07-08T20:35:16
null
UTF-8
C++
false
false
4,543
hpp
common.hpp
/* Copyright (c) Chris Choy (chrischoy@ai.stanford.edu). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * Please cite "4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural * Networks", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part * of the code. */ #ifndef COMMON #define COMMON #include <array> #include <iostream> #include <string> #include <vector> #include <torch/extension.h> #include "coords_manager.hpp" #include "instantiation.hpp" #include "thread_pool.hpp" #include "types.hpp" #include "utils.hpp" #ifndef CPU_ONLY #include <cublas_v2.h> #include <cuda.h> #include <cuda_runtime.h> #include <curand.h> #include <cusparse_v2.h> #include <driver_types.h> // cuda driver types #include <THC/THCBlas.h> #include <thrust/device_vector.h> #include "gpu.cuh" #include "gpu_memory_manager.hpp" #endif template <typename T> std::string ArrToString(T arr) { std::string buf = "["; for (size_t i = 0; i < arr.size(); i++) { buf += (i ? ", " : "") + std::to_string(arr[i]); } buf += "]"; return buf; } template <typename Dtype, typename Itype> int dtypeMultiplier() { // if larger, return ceil of sizeof(Dtype) / sizeof(Itype) return sizeof(Dtype) > sizeof(Itype) ? (sizeof(Dtype) + sizeof(Itype) - 1) / sizeof(Itype) : 1; } template <typename T> void PyPrintArr(T arr) { py::print(ArrToString(arr)); } template <uint8_t D> std::vector<int> computeOutTensorStride(const Arr<D, int> &tensor_strides, const Arr<D, int> &strides, bool is_transpose) { std::vector<int> out_tensor_strides; for (int i = 0; i < D; i++) { if (is_transpose) { if (tensor_strides[i] % strides[i] > 0) throw std::invalid_argument( Formatter() << "The output tensor stride is not divisible by " "up_strides. tensor stride: " << ArrToString(tensor_strides) << ", up_strides: " << ArrToString(strides)); out_tensor_strides.push_back(tensor_strides[i] / strides[i]); } else out_tensor_strides.push_back(tensor_strides[i] * strides[i]); } return out_tensor_strides; } template <uint8_t D> long ComputeKernelVolume(int region_type, const Arr<D, int> &kernel_size, int n_offset) { int kernel_volume; if (region_type == 0) { // Hypercube kernel_volume = 1; for (auto k : kernel_size) kernel_volume *= k; } else if (region_type == 1) { // Hypercross kernel_volume = 1; for (auto k : kernel_size) kernel_volume += k - 1; } else if (region_type == 2) { kernel_volume = n_offset; } else { throw std::invalid_argument("Invalid region type"); } return kernel_volume; } // Will be exported to python for lazy key initialization. // For instance, ConvModule.out_coords_key can be used for other layers before // feedforward template <uint8_t D> class PyCoordsKey { private: uint64_t key_; // Use the key_ for all coordshashmap query. Lazily set public: bool key_set = false; Arr<D, int> tensor_strides_; PyCoordsKey() { reset(); } void reset(); void copy(py::object ohter); void setKey(uint64_t key); uint64_t getKey(); void setTensorStride(const Arr<D, int> &tensor_strides); void stride(const Arr<D, int> &strides); void up_stride(const Arr<D, int> &strides); Arr<D, int> getTensorStride() { return tensor_strides_; }; std::string toString() const; }; #endif
36f0110d9d27b76ca12dd9cb97200db973a6c3a3
e51d009c6c6a1633c2c11ea4e89f289ea294ec7e
/xr2-dsgn/sources/xray/editor/world/sources/solid_visual_tool_tab.h
4b4b0867eb36351c7aecdc7692996df63b1835e3
[]
no_license
avmal0-Cor/xr2-dsgn
a0c726a4d54a2ac8147a36549bc79620fead0090
14e9203ee26be7a3cb5ca5da7056ecb53c558c72
refs/heads/master
2023-07-03T02:05:00.566892
2021-08-06T03:10:53
2021-08-06T03:10:53
389,939,196
3
2
null
null
null
null
UTF-8
C++
false
false
3,334
h
solid_visual_tool_tab.h
//////////////////////////////////////////////////////////////////////////// // Created : 12.07.2011 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2011 //////////////////////////////////////////////////////////////////////////// #ifndef SOLID_VISUAL_TOOL_TAB_H_INCLUDED #define SOLID_VISUAL_TOOL_TAB_H_INCLUDED using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Data; #include "tool_tab.h" namespace xray { namespace editor { ref class tool_base; ref class library_objects_tree; ref struct lib_item_base; /// <summary> /// Summary for solid_visual_tool_tab /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public ref class solid_visual_tool_tab : public System::Windows::Forms::UserControl, public tool_tab { public: solid_visual_tool_tab(tool_base^ tool):m_tool(tool) { InitializeComponent ( ); post_constructor ( ); // //TODO: Add the constructor code here // } private: System::Windows::Forms::Panel^ objects_tree_place; public: public: private: private: private: public: tool_base^ m_tool; protected: /// <summary> /// Clean up any resources being used. /// </summary> ~solid_visual_tool_tab() { if (components) { delete components; } } private: System::ComponentModel::IContainer^ components; protected: private: /// <summary> /// Required designer variable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->objects_tree_place = (gcnew System::Windows::Forms::Panel()); this->SuspendLayout(); // // objects_tree_place // this->objects_tree_place->Dock = System::Windows::Forms::DockStyle::Fill; this->objects_tree_place->Location = System::Drawing::Point(0, 0); this->objects_tree_place->Name = L"objects_tree_place"; this->objects_tree_place->Size = System::Drawing::Size(242, 385); this->objects_tree_place->TabIndex = 0; // // solid_visual_tool_tab // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->Controls->Add(this->objects_tree_place); this->Name = L"solid_visual_tool_tab"; this->Size = System::Drawing::Size(242, 385); this->ResumeLayout(false); } #pragma endregion protected: void post_constructor ( ); library_objects_tree^ m_library_objects_tree; public: void fill_objects_list ( System::String^ initial ); void item_double_clicked ( lib_item_base^ item ); virtual System::Windows::Forms::UserControl^ frame ( ) {return this;} virtual void on_activate ( ); virtual void on_deactivate ( ); }; } // namespace editor } // namespace xray #endif // #ifndef SOLID_VISUAL_TOOL_TAB_H_INCLUDED
e8b8498fb5b28699a5812baa4fb87d1c4ff5be55
13e65f3f6dc5541e6aab1cb39c2df8a70b822a62
/Arboles/src/arbol.cpp
9d431ddb495a3b6359a38d91b29134ae6859250f
[]
no_license
Nicolas3094/InteligenciaArtificial
d513c933fa0ea9cbae4c8ae3a13c4b832f5822f9
c31bf48d7f9b6f0c16b447be1f4615d282ab7c45
refs/heads/master
2023-04-22T07:23:44.755140
2021-05-04T06:48:51
2021-05-04T06:48:51
357,428,705
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
arbol.cpp
#include "../headers/arbol.hpp" template<typename T> Arbol<T>::Arbol() { } template<typename T> Arbol<T>::~Arbol(){} // A B D E H I C F G J template<typename T> void Arbol<T>::preOrden(Nodo<T> *raiz, const function<void(Nodo<T>*)> &func) { if (raiz != nullptr) { func(raiz); preOrden(raiz->Izq, func); preOrden(raiz->Der, func); } } // D B H E I A F C J G template<typename T> void Arbol<T>::inOrden(Nodo<T> *raiz, const function<void(Nodo<T>*)> &func) { if (raiz != nullptr) { inOrden(raiz->Izq, func); func(raiz); inOrden(raiz->Der, func); } } // D H I E B F J G C A template<typename T> void Arbol<T>::postOrden(Nodo<T> *raiz, const function<void(Nodo<T>*)> &func) { if (raiz != nullptr) { postOrden(raiz->Izq, func); postOrden(raiz->Der, func); func(raiz); } } template class Arbol<int>;
977336cd31ca9e77af525080e01c9a8bd6c59a5a
96612942afd34fff98ddf5fb4035ea8c1c4b40d4
/23-C++ClassesOrObjects/tutorial.cpp
dfe7eb412bfdd10a95d1d76da9276aae99850e95
[]
no_license
redoy1102/Cpp-Bangla-Tutorial-Shikkhangon-BD-
99dbc87069bd6d40ea9114c137647fbbd1d49c93
d1dc25356d527d10c7aea62708a4cc78204fdec9
refs/heads/main
2023-08-14T04:31:51.670480
2021-10-11T12:37:18
2021-10-11T12:37:18
375,913,298
8
3
null
null
null
null
UTF-8
C++
false
false
972
cpp
tutorial.cpp
#include<iostream> using namespace std; class Car{ public: string brand; int totalCar, manPower; }; int main(){ //object - 01 Car obj1; obj1.brand = "Toyota"; obj1.totalCar = 10000; obj1.manPower = 50000; cout<<"Object one details---;"<<endl; cout<<"Brand name = "<<obj1.brand<<endl; cout<<"Total Car = "<<obj1.totalCar<<endl; cout<<"Man Power = "<<obj1.manPower<<endl<<endl; //object - 02 Car obj2; obj2.brand = "Volvo"; obj2.totalCar = 20000; obj2.manPower = 60000; cout<<"Object two details---;"<<endl; cout<<"Brand name = "<<obj2.brand<<endl; cout<<"Total Car = "<<obj2.totalCar<<endl; cout<<"Man Power = "<<obj2.manPower<<endl<<endl; //object - 03 Car obj3; obj3.brand = "Tesla"; obj3.totalCar = 30000; obj3.manPower = 70000; cout<<"Object three details---;"<<endl; cout<<"Brand name = "<<obj3.brand<<endl; cout<<"Total Car = "<<obj3.totalCar<<endl; cout<<"Man Power = "<<obj3.manPower<<endl; }
5c121edc2015629bdf01d5c314981d5810590c85
71b33ec9e22b1c9d241f9b27295037653cb4df75
/src/tunitas/server/exception/Aspect.xcpp
377c2861a846cdaa48ff1b767d0614d523008f75
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
yahoo/tunitas-basics
c53cdd96245262f05836fb0affa77fa5b5de28e1
5d1bd99b73d483d8f157ce1c233fd35588f68e0f
refs/heads/master
2023-08-25T00:03:26.534521
2023-08-14T12:07:55
2023-08-14T12:07:55
191,480,785
4
5
Apache-2.0
2023-03-18T15:17:31
2019-06-12T02:13:32
C++
UTF-8
C++
false
false
1,823
xcpp
Aspect.xcpp
// This is -*- c++ -*- nearly C++23 with Modules TS but in the S.C.O.L.D. stylings that are so popular these days. // Copyright Yahoo Inc. 2021. // Licensed under the terms of the Apache-2.0 license. // For terms, see the LICENSE file at https://github.com/yahoo/tunitas-basics/blob/master/LICENSE // For terms, see the LICENSE file at https://git.tunitas.technology/all/components/basics/tree/LICENSE #divert <fpp> namespace tunitas::server::exception { // // The generic server exception aspect // Descendants only. // Set up as an Ancestor to the mixin tree so that STL exceptions can be mixed in as well. // // These are wholly distinct from the tunitas::app::exceptions which have a // text user interface aspect to them. The server exceptions are not expected // to escape from the thread whence they came. These are expected to have terse, // rudimentary expressions in 'what()' // // Usage: // // class my::server::Problem : public tunitas::server::exception::Aspect, // public std::runtime_error { // ... // }; // class my::server::Difficulty : public tunitas::server::exception::Aspect, // public std::logic_error { // ... // }; // // try { // ... // throw my::Problem{...}; // throw my::Difficulty{...}; // ... // } catch (exception::Aspect const &g) { // ... fix it... // } // class Aspect; } #endiv #divert <hpp> class tunitas::server::exception::Aspect { protected: virtual ~Aspect() = default; Aspect() = default; // The other side of the mixin must provide the messaging // c.f. tunitas::exception::feature::Messaging if you want to throw string messages public: virtual auto what() const noexcept -> char const * = 0; }; #endiv
bf2803fff1c1f9a22e47e2b604bb179026fda12a
f63ecee08c3cb828f5afb1c7ed26b93a6bf7c37a
/Lab4/lab4.cpp
35ab6db9bfdabfd90b42713bbb6e409bc85da563
[]
no_license
bfigueroa9/brandonfigueroa-CSCI-20-Fall2016
3724893975c2a2c3f8e274bdbd9d409d51b75d9a
a2a5f11b06216d0fe1493519b6f9bbc5b0213252
refs/heads/master
2020-09-21T11:58:07.916183
2016-08-31T20:30:39
2016-08-31T20:30:39
66,295,258
0
0
null
null
null
null
UTF-8
C++
false
false
1,562
cpp
lab4.cpp
#include <iostream> #include <string> using namespace std; int main() { string name1; string adjective1; string country1; int number1 = 0; string adjective2; float numDecimals; string politician1; string adjective3; string verb1; cout << "Enter your name" << endl; cin >> name1; cout << "Enter an adjective" << endl; cin >> adjective1; cout << "Enter a country" << endl; cin >> country1; cout << "Enter a number" << endl; cin >> number1; cout << "Enter an adjective" << endl; cin >> adjective2; cout << "Enter a number with a decimal" <<endl; cin >> numDecimals; cout << "Enter a politician" << endl; cin >> politician1; cout << "Enter an adjective" << endl; cin >> adjective3; cout << "Enter a verb" << endl; cin >> verb1; cout << endl; cout << name1 << " is on thier way to the " << adjective1 << " bus stop." << endl; cout << name1 << " is going to " << country1 << " to fight " << number1 << " "<< adjective2 << " ninjas!" << endl; cout << "The ninjas were set in the " << numDecimals << " eagle-eye formation." << endl; cout << name1 << " began to cry and called for back up. Thats when " << politician1 << " appeared and " << verb1 << " around the " << adjective3 << " ninjas." << endl; cout << name1 << " and " << politician1 << " defeated the ninjas with thier fame and curruption super powers." << endl; }
2fb05a39192016d3d3c013282e78dc4aeb13e3d9
3d7aafcdd93f706580ddefd7621d36c2b89a39da
/Assignment2/Mission.h
793b1902995305b449c96e4b574060349969728f
[]
no_license
ahmetfurkankavraz/Object-Oriented-Programming
8c39ca7d6b04d0e7f00678de063c9e3d8ddea38f
7d47ad9487d922f96ed4b9d7128c1cb18fcd8c50
refs/heads/main
2023-06-12T11:36:11.263354
2021-07-11T16:37:44
2021-07-11T16:37:44
384,878,305
0
0
null
null
null
null
UTF-8
C++
false
false
1,891
h
Mission.h
/*@AuthorStudent Name: Ahmet Furkan Kavraz Student ID: 150190024 Date: 29.04.2021 */ #pragma once #include <iostream> #include <cstdlib> #include "Person.h" using namespace std; class Mission{ static int numMissions; string name; int missionNumber; int cost; int faultProbability; bool completed = false; Passenger* passengers = NULL; int passengersSize = 0; Astronaut* crew = NULL; int crewSize = 0; Mission* next = NULL; public: Mission(string, int, int); Mission(const Mission&); ~Mission(); Mission* operator+=(Passenger*); Mission* operator+=(Astronaut*); bool executeMission(); int calculateProfit(int); void addPassenger(Passenger); void addAstronaut(Astronaut); void printPassengers(); void printCrew(); string getName(){return this->name;} void setName(string); bool properName(string); int getCost(){return cost;} void setCost(int cost){this->cost = cost;} int getMissionNumber(){return missionNumber;} void setMissionNumber(int missionNumber){this->missionNumber = missionNumber;} int getFaultProbability(){return faultProbability;} void setFaultProbability(int faultProbability){this->faultProbability = faultProbability;} Astronaut* getCrew(){return crew;} void setCrew(Astronaut* crew){this->crew = crew;} int getCrewSize(){return this->crewSize;} void setCrewSize(int crewSize){this->crewSize = crewSize;} Passenger* getPassengers(){return passengers;} void setPassengers(Passenger* passengers){this->passengers = passengers;} Mission* getNext(){return this->next;} void setNext(Mission* next){this->next = next;} };
bb97d0c50110ec48c09c6b57a71c85c669001f21
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/CodeJamData/08/91/20.cpp
931823c408a042b9ca3240fe60cecb86d0b55837
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,455
cpp
20.cpp
#define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:60000000") #include <iostream> #include <sstream> #include <cassert> #include <cmath> #include <ctime> #include <map> #include <set> #include <bitset> #include <queue> using namespace std; typedef long long int64; #define forn(i, n) for(int i = 0; i < (int)(n); ++i) #define ford(i, n) for(int i = (int)(n) - 1; i >= 0; --i) #define pb push_back #define mp make_pair #define fs first #define sc second #define all(a) a.begin(), a.end() const int INF = INT_MAX >> 1; const double EPS = 1E-8; const double PI = 3.1415926535897932384626433832795; #define N 6000 int a[N], b[N], c[N], n; int main() { freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); int tk; scanf("%d\n", &tk); set<int> s1, s2; for(int tc = 1; tc <= tk; ++tc) { cin >> n; for(int i = 0; i < n; ++i) scanf("%d %d %d", &a[i], &b[i], &c[i]); int ans = 0; forn(l, n) { vector<pair<int, int> > v; forn(i, n) if (a[i] <= a[l]) v.pb(mp(b[i], c[i])); sort(all(v)); int p = 0; priority_queue<int> q; forn(i, v.size()) { while (p < (int)v.size() && v[p].fs <= v[i].fs) { q.push(v[p++].sc); } int z = 10000 - a[l] - v[i].fs; while (!q.empty() && q.top() > z) q.pop(); ans = max(ans, (int)q.size()); } } printf("Case #%d: %d\n", tc, ans); } return 0; }
a84a11d7135a7c4377e51353341f810515c5069b
079fc19ac0394a2d230f39866e4f127344090a1d
/FileManager/FileManager.cpp
ff66e8b4bb7275ae3c43a6073131a20909ae45b0
[]
no_license
gautamperi2/FileCatalogue
f1ea961ef4b6cebf4c5d7111f30008f527630f15
2e0a8241cf2433417edfc009207ec0b8d0c5935a
refs/heads/master
2021-01-19T05:26:24.123697
2015-05-19T21:25:59
2015-05-19T21:25:59
35,909,391
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,267
cpp
FileManager.cpp
///////////////////////////////////////////////////////////////////////////// // FileManager.cpp - Collects file specifications from directory tree // // and search for a given text from a given file // // ver 2.2 // // ----------------------------------------------------------------------- // // copyright © Jim Fawcett, 2012 // // All rights granted provided that this notice is retained // // ----------------------------------------------------------------------- // // Language: Visual C++, Visual Studio 2013 // // Platform: ASUS Q550L, Core i7, Windows 8.1 // // Application: Summer Projects, 2012 // // Author: Gautam Peri, CST 4-284, Syracuse University // // (315) 484-6562, nperi@syr.edu // ///////////////////////////////////////////////////////////////////////////// #include "FileManager.h" #include <iostream> #include <string> #include <fstream> #include <regex> //Searches all the file to get files void FileManager::search(bool IsRecursive) { findFiles(path_, IsRecursive); } //Finds all the files form given path recursively void FileManager::findFiles(const std::string& path, bool IsRecursive) { for (auto patt : patterns_) { std::string fullPath = FileSystem::Path::getFullFileSpec(path); std::vector<std::string> files = FileSystem::Directory::getFiles(fullPath, patt); for (auto f : files) { store_.save(f, fullPath); } std::vector<std::string> dirs = FileSystem::Directory::getDirectories(fullPath); auto iter = std::find(std::begin(dirs), std::end(dirs), "."); if (iter != std::end(dirs)) { dirs.erase(iter); } iter = std::find(std::begin(dirs), std::end(dirs), ".."); if (iter != std::end(dirs)) { dirs.erase(iter); } if (IsRecursive) { for (auto d : dirs) { std::string dirPath = fullPath + "\\" + d; findFiles(dirPath, IsRecursive); } } } } //searches the data store catalogue with given search text void FileManager::TextSearch(DataStore& store, std::string searchText) { DataStore::iterator iter; store.ClearSearchList(); for (iter = store.begin(); iter != store.end(); iter++) { std::string file = iter->first; DataStore::ListOfPaths lstPaths = iter->second; for (auto filePathList : lstPaths) { std::string path = (*filePathList).c_str(); std::string filePath = path + "\\" + file; std::string line; std::ifstream fileInput; fileInput.open(filePath); if (fileInput.is_open()) { while (std::getline(fileInput, line)) { if (line.find(searchText, 0) != std::string::npos) { store.AddToSearchList(filePath); break; } } } } } } //Converts a Given pattern to Regular expression void FileManager::ConvertToRegex(std::string& patt) { ChangeString(patt, "*", "(.*)"); ChangeString(patt, "?", "(.?)"); } //Changes a given string of one form to another by given modification void FileManager::ChangeString(std::string& str, const std::string& from, const std::string& to) { if (from.empty()) return; size_t start_in = 0; while ((start_in = str.find(from, start_in)) != std::string::npos) { str.replace(start_in, from.length(), to); start_in += to.length(); } } //Searches for the given pattern files from the catalogue and search text from the DataStore void FileManager::PatternTextSearch(DataStore& store, std::string searchText) { DataStore::iterator iter; store.ClearSearchList(); for (iter = store.begin(); iter != store.end(); iter++) { std::string file = iter->first; DataStore::ListOfPaths lstPaths = iter->second; for (auto filePathList : lstPaths) { std::string path = (*filePathList).c_str(); std::string filePath = path + "\\" + file; for (auto patt : patterns_) { ConvertToRegex(patt); std::regex e(patt); if (std::regex_match(file, e)) { std::string line; std::ifstream fileInput; fileInput.open(filePath); if (fileInput.is_open()) { while (std::getline(fileInput, line)) { if (line.find(searchText, 0) != std::string::npos) { store.AddToSearchList(filePath); break; } } } } } } } } #ifdef TEST_FILEMANAGER int main() { std::cout << "\n Testing FileManager class"; std::cout << "\n =======================\n"; DataStore ds; FileManager fm(".", ds); fm.addPattern("*.*"); fm.search(); std::string sText = "Search"; fm.TextSearch(ds, sText); std::string sPatt = "*.cpp"; fm.ConvertToRegex(sText); fm.ChangeString(sPatt, "*", "(.*)"); fm.PatternTextSearch(ds, sPatt); DataStore::iterator iter; for (iter = ds.begin(); iter != ds.end(); iter++) { std::string file = iter->first; std::cout << "\n FileName: \n" << file << "\n"; DataStore::ListOfPaths lstPaths = iter->second; DataStore::ListOfPaths::iterator lstIter; for (auto filePathList : lstPaths) std::cout << (*filePathList).c_str() << "\n" << "\t"; } std::cout << "\n\n"; getchar(); std::cout << "\n\n"; return 0; } #endif
c727c675c91235259d8ae81ca3df4e6c1671366e
d6ab38714f7a5f0dc6d7446ec20626f8f539406a
/backend/collecting/collectedFiles/C++/edited/musescoreMuseScoreblob5c13a28d62d8df3f7b06f2d3ed86501e3534d566mscoretimedialog.cpp
d2ad59aa80432b55d70ce16a696e4590c7b8a0a7
[ "BSL-1.0" ]
permissive
haditabatabaei/webproject
8db7178affaca835b5d66daa7d47c28443b53c3d
86b3f253e894f4368a517711bbfbe257be0259fd
refs/heads/master
2020-04-10T09:26:25.819406
2018-12-08T12:21:52
2018-12-08T12:21:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,621
cpp
musescoreMuseScoreblob5c13a28d62d8df3f7b06f2d3ed86501e3534d566mscoretimedialog.cpp
#include "timedialog.h" #include "libmscore/timesig.h" #include "palette.h" #include "musescore.h" #include "libmscore/score.h" #include "libmscore/mcursor.h" #include "libmscore/chord.h" #include "libmscore/part.h" namespace Ms { extern bool useFactorySettings; TimeDialog::TimeDialog(QWidget* parent) : QWidget(parent, Qt::WindowFlags(Qt::Dialog | Qt::Window)) { setupUi(this); setWindowTitle(tr("Time Signatures")); QLayout* l = new QVBoxLayout(); l->setContentsMargins(0, 0, 0, 0); frame->setLayout(l); sp = MuseScore::newTimePalette(); sp->setReadOnly(false); sp->setSelectable(true); connect(zNominal, SIGNAL(valueChanged(int)), SLOT(zChanged(int))); connect(nNominal, SIGNAL(currentIndexChanged(int)), SLOT(nChanged(int))); connect(sp, SIGNAL(boxClicked(int)), SLOT(paletteChanged(int))); connect(sp, SIGNAL(changed()), SLOT(setDirty())); connect(addButton, SIGNAL(clicked()), SLOT(addClicked())); _timePalette = new PaletteScrollArea(sp); QSizePolicy policy(QSizePolicy::Expanding, QSizePolicy::Expanding); _timePalette->setSizePolicy(policy); _timePalette->setRestrictHeight(false); l->addWidget(_timePalette); _dirty = false; if (useFactorySettings || !sp->read(dataPath + "/timesigs")) { Fraction sig(4,4); groups->setSig(sig, Groups::endings(sig)); } for (int i = 0; i < sp->size(); ++i) sp->setCellReadOnly(i, false); sp->element(2)->layout(); sp->setSelected(2); paletteChanged(2); } void TimeDialog::addClicked() { TimeSig* ts = new TimeSig(gscore); ts->setSig(Fraction(zNominal->value(), denominator())); ts->setGroups(groups->groups()); if ((QString("%1").arg(zNominal->value()) != zText->text()) || (QString("%1").arg(denominator()) != nText->text())) { ts->setNumeratorString(zText->text()); ts->setDenominatorString(nText->text()); } sp->append(ts, ""); sp->setSelected(sp->size() - 1); _dirty = true; } void TimeDialog::save() { QDir dir; dir.mkpath(dataPath); sp->write(dataPath + "/timesigs"); qDebug("TimeDialog::save(): %s", qPrintable(dataPath+"/timesigs")); } void TimeDialog::zChanged(int val) { zText->setText(QString("%1").arg(val)); Fraction sig(zNominal->value(), denominator()); groups->setSig(sig, Groups::endings(sig)); } void TimeDialog::nChanged(int ) { nText->setText(QString("%1").arg(denominator())); Fraction sig(zNominal->value(), denominator()); groups->setSig(sig, Groups::endings(sig)); } int TimeDialog::denominator2Idx(int denominator) const { int val = 4; switch (denominator) { case 1: val = 0; break; case 2: val = 1; break; case 4: val = 2; break; case 8: val = 3; break; case 16: val = 4; break; case 32: val = 5; break; case 64: val = 6; break; } return val; } int TimeDialog::denominator() const { int val = 4; switch (nNominal->currentIndex()) { case 0: val = 1; break; case 1: val = 2; break; case 2: val = 4; break; case 3: val = 8; break; case 4: val = 16; break; case 5: val = 32; break; case 6: val = 64; break; } return val; } void TimeDialog::paletteChanged(int idx) { TimeSig* e = static_cast<TimeSig*>(sp->element(idx)); if (!e || e->type() != ElementType::TIMESIG) { zNominal->setEnabled(false); nNominal->setEnabled(false); zText->setEnabled(false); nText->setEnabled(false); groups->setEnabled(false); addButton->setEnabled(false); return; } zNominal->setEnabled(true); nNominal->setEnabled(true); zText->setEnabled(true); nText->setEnabled(true); groups->setEnabled(true); addButton->setEnabled(true); Fraction sig(e->sig()); Groups g = e->groups(); if (g.empty()) g = Groups::endings(sig); zNominal->setValue(sig.numerator()); nNominal->setCurrentIndex(denominator2Idx(sig.denominator())); zText->setText(e->numeratorString()); nText->setText(e->denominatorString()); groups->setSig(sig, g); } }
f657f11384dc29663cd8cc7445cec098f9f264fc
5b5d53dd0d1593f2c2475d493f664d34e4858ee2
/Eigen/Advanced Initialization/ozelMatrisveDiziler/Eigen/Eigen.cpp
44fdeea832d50ebcb25acfbec04418abf28054c6
[]
no_license
yapbenzet/Modern_Cpp_WebSite
bf51a84ec6587631d1cee80354989759f200ec8e
526d558490a8676d13330b80f34ec872d779f7d4
refs/heads/master
2023-04-04T17:30:17.150606
2023-03-22T06:34:43
2023-03-22T06:34:43
98,210,300
6
5
null
null
null
null
UTF-8
C++
false
false
475
cpp
Eigen.cpp
// Eigen.cpp : Defines the entry point for the console application. // // #include <Eigen/Dense> #include <iostream> using namespace Eigen; using namespace std; int main() { cout << "Sabit boyutlu dizi:\n"; Array33f a1 = Array33f::Zero(); cout << a1 << "\n\n"; cout << "Dinamik tek boyutlu dizi:\n"; ArrayXf a2 = ArrayXf::Zero(3); cout << a2 << "\n\n"; cout << "Dinamik iki boyutlu dizi:\n"; ArrayXXf a3 = ArrayXXf::Zero(3, 4); cout << a3 << "\n"; return 0; }
8f009274a672fc8e45d3696f16ff83a2e856b72f
e7861d322a56f7228af30b15a742f9c7ab873069
/114-10/1140.cpp
25ca5598175cefa18bdaf9d92906d834aa0da5ea
[]
no_license
huangbin5/PAT_Advanced
97a137e3b1e999122c48636e995c6b1dd17f92a1
f4abff99578b14f445030008443217ca20cdba1a
refs/heads/master
2023-03-17T13:48:31.919142
2021-03-26T15:26:49
2021-03-26T15:26:49
351,806,802
0
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
1140.cpp
#include <algorithm> #include <cstring> #include <iostream> using namespace std; // #define DEBUG const int maxn = 100000; char s1[maxn], s2[maxn]; int main() { #ifdef DEBUG freopen("d:\\input.txt", "r", stdin); freopen("d:\\output.txt", "w", stdout); #endif int n; scanf("%s%d", &s1, &n); char *p1 = s1, *p2 = s2; for (int i = 2; i <= n; ++i) { swap(p1, p2); // p1的下标 int idx = 0, len = strlen(p2); for (int j = 0; j < len; ++j) { int cnt = 1; while (j < len - 1 && p2[j] == p2[j + 1]) { ++j; ++cnt; } p1[idx++] = p2[j]; p1[idx++] = cnt + '0'; } p1[idx] = '\0'; } printf("%s", p1); return 0; }
6b7f47a3b4e6a58abd5a320c2d4b04ffa2d6feb3
e5a0def29da1012c1fcb9ccb4f16c95b3e213dbc
/색종이_baekjoon2563.cpp
a9da1a4e3da414130156b25a05cb424cba233b51
[]
no_license
hyeseonko/Algorithm-Baekjoon
561f641551451635cca6b9252b924643647dc7f0
99f819d05d5f90c60b38406a9f4a73cd1ba0c6b6
refs/heads/master
2021-12-14T03:04:09.183045
2021-12-05T13:45:23
2021-12-05T13:45:23
87,627,277
0
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
색종이_baekjoon2563.cpp
/* TITLE: COLORED PAPER BAEKJOON 2563 Olympiad > KOI 2007 > ELEMENTARY #02 CATEGORY: SIMULATION DATE: 2017-07-13 */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> bool visited[100][100]; int main() { int N; scanf("%d", &N); int MAX1 = 0; int MAX2 = 0; while (N--) { int temp1, temp2; scanf("%d %d", &temp1, &temp2); if (temp2 > MAX1) MAX1 = temp2; if (temp1 > MAX2) MAX2 = temp1; for (int i = temp2 - 1; i < temp2 + 9; i++) for (int j = temp1 - 1; j < temp1 + 9; j++) visited[i][j] = true; } int ans = 0; for (int i = 0; i < MAX1+10; i++) for (int j = 0; j < MAX2+10; j++) if (visited[i][j]) ans++; printf("%d\n", ans); return 0; }
f4e287cc49b1f388c6befbdb3c58c1a292abc959
971e5f98f0542a2b21d0c8618f934d9cd1fd8ef8
/lib/Utils.cpp
6d50da53e2384c81502d72341e7a9e080abb36f7
[]
no_license
darthsaderr/solarSystem
74961b5b6891bb373bd3c694f45b00d0103a2883
323ba1d5b085f644a60d8d3798a2fb3ea3e124d0
refs/heads/master
2021-03-22T04:43:49.445063
2018-02-14T04:44:41
2018-02-14T04:44:41
121,470,022
0
0
null
null
null
null
UTF-8
C++
false
false
808
cpp
Utils.cpp
#if defined(WIN32) #include <windows.h> #endif #if defined(__APPLE__) #include <OpenGl/gl.h> #include <OpenGl/glu.h> #include <GLUT/glut.h> #else #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #endif #include <fstream> #include <ctime> #include "Utils.h" using namespace std; void setWorldWin(GLdouble left,GLdouble right,GLdouble bottom,GLdouble top){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(left,right,bottom,top); } void setViewPort(GLint left,GLint right,GLint bottom,GLint top){ glViewport(left,bottom,right-left,top-bottom); } // this is a wrapper to nanosleep which sleeps for a certain // number of milliseconds void delay(int ms) { struct timespec ts; ts.tv_sec = ms/1000; ts.tv_nsec = 1000000 * (ms%1000); nanosleep(&ts,NULL); }
003de918b0f2722cc947837feec948f9df0adbf6
5353ad799a5795470c2dcbeb4f10467d34fecd5b
/rm_localization/src/keyframe.cpp
75dc74724f7f3e5a5196703f08d305f8481c0e8c
[]
no_license
Aharobot/rapyuta-mapping
05dd6ec46e5e6d46b1b51f2dc44dbbb8b30bee97
c69a3ec7c19f05fdaa8d624b6ab5fdd6f28c8706
refs/heads/master
2020-12-25T01:05:59.455528
2014-01-22T11:04:42
2014-01-22T11:04:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,060
cpp
keyframe.cpp
#include <keyframe.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <tbb/parallel_for.h> keyframe::keyframe(const cv::Mat & yuv, const cv::Mat & depth, const Sophus::SE3f & position, const Eigen::Vector3f & intrinsics, int max_level) : frame(yuv, depth, position, intrinsics, max_level) { intencity_pyr_dx = new int16_t *[max_level]; intencity_pyr_dy = new int16_t *[max_level]; for (int level = 0; level < max_level; level++) { intencity_pyr_dx[level] = new int16_t[cols * rows / (1 << 2 * level)]; intencity_pyr_dy[level] = new int16_t[cols * rows / (1 << 2 * level)]; } clouds.resize(max_level); for (int level = 0; level < max_level; level++) { int c = cols >> level; int r = rows >> level; Eigen::Vector3f intrinsics = get_intrinsics(level); clouds[level].setZero(4, c * r); convert_depth_to_pointcloud sub(intencity_pyr[level], depth_pyr[level], intrinsics, c, r, clouds[level], intencity_pyr_dx[level], intencity_pyr_dy[level]); tbb::parallel_for(tbb::blocked_range<int>(0, c * r), sub); } /* cv::imshow("intencity_pyr", intencity_pyr); cv::imshow("depth_pyr", depth_pyr); cv::imshow("intencity_pyr_dx", intencity_pyr_dx); cv::imshow("intencity_pyr_dy", intencity_pyr_dy); cv::waitKey(); */ } keyframe::~keyframe() { for (int level = 0; level < max_level; level++) { delete[] intencity_pyr_dx[level]; delete[] intencity_pyr_dy[level]; } delete[] intencity_pyr_dx; delete[] intencity_pyr_dy; } bool keyframe::estimate_position(frame & f) { Sophus::SE3f Mrc; bool res = estimate_relative_position(f, Mrc); if (res) { f.position = position * Mrc; } return res; } bool keyframe::estimate_relative_position(frame & f, Sophus::SE3f & Mrc) { int level_iterations[] = { 2, 4, 6 }; Mrc = position.inverse() * f.position; for (int level = 2; level >= 0; level--) { for (int iteration = 0; iteration < level_iterations[level]; iteration++) { cv::Mat intencity = get_i(level), depth = get_d(level), intencity_dx = get_i_dx(level), intencity_dy = get_i_dy( level); cv::Mat intencity_warped(intencity.rows, intencity.cols, CV_32F), depth_warped(depth.rows, depth.cols, CV_32F); int c = cols >> level; int r = rows >> level; f.warp(clouds[level], Mrc.inverse(), level, intencity_warped, depth_warped); reduce_jacobian rj(intencity_pyr[level], intencity_pyr_dx[level], intencity_pyr_dy[level], (float *) intencity_warped.data, (float *) depth_warped.data, intrinsics, clouds[level], c, r); tbb::parallel_reduce( tbb::blocked_range<int>(0, intencity.cols * intencity.rows), rj); //rj(tbb::blocked_range<int>(0, intencity.cols * intencity.rows)); if (level == 0 && iteration == level_iterations[level]-1 && (float) rj.num_points / (c * r) < 0.1) { return false; } //ROS_INFO("Mean error %f with %f\% valid points", std::sqrt(rj.error_sum)/rj.num_points, (float)rj.num_points / (c*r)); Sophus::Vector6f update = -rj.JtJ.ldlt().solve(rj.Jte); //std::cerr << "update " << std::endl << update << std::endl; Mrc = Sophus::SE3f::exp(update) * Mrc; //std::cerr << "Transform " << std::endl << f.position.matrix() // << std::endl; //if(level == 0) { // cv::imshow("intencity_warped", intencity_warped); // cv::imshow("intencity", intencity); // cv::waitKey(3); //} } } return true; } void keyframe::update_intrinsics(const Eigen::Vector3f & intrinsics) { this->intrinsics = intrinsics; for (int level = 0; level < max_level; level++) { int c = cols >> level; int r = rows >> level; Eigen::Vector3f intrinsics = get_intrinsics(level); clouds[level].setZero(4, c * r); convert_depth_to_pointcloud sub(intencity_pyr[level], depth_pyr[level], intrinsics, c, r, clouds[level], intencity_pyr_dx[level], intencity_pyr_dy[level]); tbb::parallel_for(tbb::blocked_range<int>(0, c * r), sub); } } rm_localization::Keyframe::Ptr keyframe::to_msg( const cv_bridge::CvImageConstPtr & yuv2, int idx) { rm_localization::Keyframe::Ptr k(new rm_localization::Keyframe); cv::Mat rgb; if (yuv2->image.channels() == 3) { rgb = yuv2->image; } else { cv::cvtColor(yuv2->image, rgb, CV_YUV2RGB_UYVY); } cv::imencode(".png", rgb, k->rgb_png_data); cv::imencode(".png", get_d(0), k->depth_png_data); k->header.frame_id = yuv2->header.frame_id; k->header.stamp = yuv2->header.stamp; k->intrinsics[0] = intrinsics[0]; k->intrinsics[1] = intrinsics[1]; k->intrinsics[2] = intrinsics[2]; k->transform.unit_quaternion[0] = position.unit_quaternion().coeffs()[0]; k->transform.unit_quaternion[1] = position.unit_quaternion().coeffs()[1]; k->transform.unit_quaternion[2] = position.unit_quaternion().coeffs()[2]; k->transform.unit_quaternion[3] = position.unit_quaternion().coeffs()[3]; k->transform.position[0] = position.translation()[0]; k->transform.position[1] = position.translation()[1]; k->transform.position[2] = position.translation()[2]; k->idx = idx; return k; }
616108ff15343f7b94b2891d62353d85dd4f2587
b57d949784e6b1e7d87f8a35c561694ac7d9fc0a
/0-99/96. Unique Binary Search Trees.cpp
7f50a7e486eef2d097ad56605278414d4c8aa65e
[]
no_license
CandiceD17/Leetcode-Everyday
21745dbe0120c9dbd4e023a840b555cc31168686
2e4bc7d0126997ef7695bda3daa26906bbafd7b8
refs/heads/master
2023-08-05T06:11:08.709065
2023-07-31T07:59:45
2023-07-31T07:59:45
195,782,272
1
0
null
null
null
null
UTF-8
C++
false
false
465
cpp
96. Unique Binary Search Trees.cpp
class Solution { public: int catalan(int n){ double res = 1; for(int i=0; i<n; i++){ res*= (2*n-i); res/= n-i; } res/=n+1; int result = res; if(res-result>=0.5) return result+1; return result; } int numTrees(int n) { //the catalan number //n = n vertices // num trees = C(2n,n)/(n+1) return catalan(n); } }; 2019.08.06
fa095d7b3b2b00131e71a367bef612ddc3090866
0f912d21e5b571e6c4cb64ca9b4f3643b6c7b96e
/Gamecraft2019/Game.h
0b1ccf406c6f0efe45af596d1dbe19aa3a184fdf
[]
no_license
Dylaann/GameCraft
64f9324604b06a5e7b9c86c62666fe00637c2e58
b8fd4aa5955fdd00dcb0dfb73f654a71163f1b40
refs/heads/master
2021-10-24T23:25:15.340513
2019-03-29T18:33:50
2019-03-29T18:33:50
177,134,283
1
0
null
2019-03-29T18:33:51
2019-03-22T12:15:04
C++
UTF-8
C++
false
false
741
h
Game.h
#ifndef GAME_H #define GAME_H #include <iostream> #include <SDL.h> #include <SDL_ttf.h> #include <SDL_image.h> #include <SDL_mixer.h> #include "Resource Manager\ResourceManager.h" #include <vector> #include "MenuManager.h" #include "ThreadPool.h" using namespace std; const float FRAMES_PER_SECOND = 60; class Game { public: // Public Functions Game(); ~Game(); void run(); private: void processEvents(); void update(); void render(); void setUpFont(); // SDL Window SDL_Window * p_window; SDL_Renderer *m_renderer; int m_windowWidth = 375; int m_windowHeight = 667; bool m_exitGame = false; TTF_Font* Arial; MenuManager m_mManager; ThreadPool m_threadPool; ResourceManager * m_resourceManager; }; #endif // !GAME_H
729952f30388dd989bd30fbc170ac0348b7f2a2f
5a155f8741c46f168b0ce1eac90f6d1d673fdf07
/PreviousProjects/C++Project/接口类/FighterPlane.h
a3e1a75f83925c60854a1f1fb455770e1bcfba5b
[]
no_license
gitjinyubao/MyProject
10b308948597ef726af858260b8622814ddd5b25
ed71b23f82ff272f6c90f0513f0e94a9accd0849
refs/heads/master
2021-09-04T01:28:08.560749
2018-01-14T02:40:15
2018-01-14T02:40:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
209
h
FighterPlane.h
#ifndef FIGHTERPLANE_H #define FIGHTERPLANE_H #include"Flyable.h" #include"Plane.h" class FighterPlane:public Plane,public Flyable { public: FighterPlane(int cod); void takeoff(); void land(); }; #endif
51c0cbbebfae2899cc99ee9b014eb939246ab5a8
0fe27e6c63a755fe7df003f36acc079490a338f3
/src/cpp/Pancake-Sorting.cpp
275b24fa0bab13e586d3b6a46d2e10464f95df71
[]
no_license
Finalcheat/leetcode
83f9ceb7bd10783554133434347803a41260a713
985deb6142c6841aa7025c9b582010b33f694e6c
refs/heads/master
2022-11-11T22:51:42.666150
2022-11-05T03:07:31
2022-11-05T03:07:31
53,241,690
2
1
null
null
null
null
UTF-8
C++
false
false
2,261
cpp
Pancake-Sorting.cpp
/** * @file Pancake-Sorting.cpp * @brief 煎饼排序(https://leetcode.com/problems/pancake-sorting/) * @author Finalcheat * @date 2019-02-18 */ /** * Given an array A, we can perform a pancake flip: We choose some positive integer k <= A.length, then reverse the order of the first k elements of A. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A. * Return the k-values corresponding to a sequence of pancake flips that sort A. Any valid answer that sorts the array within 10 * A.length flips will be judged as correct. * Example 1: * Input: [3,2,4,1] * Output: [4,2,4,3] * Explanation: * We perform 4 pancake flips, with k values 4, 2, 4, and 3. * Starting state: A = [3, 2, 4, 1] * After 1st flip (k=4): A = [1, 4, 2, 3] * After 2nd flip (k=2): A = [4, 1, 2, 3] * After 3rd flip (k=4): A = [3, 2, 1, 4] * After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted. * Example 2: * Input: [1,2,3] * Output: [] * Explanation: The input is already sorted, so there is no need to flip anything. * Note that other answers, such as [3, 3], would also be accepted. */ /** * 煎饼排序,最简单的方法每次找出当前最大的值翻转到最前面后再翻转一次移到后面。 */ class Solution { public: vector<int> pancakeSort(vector<int>& A) { vector<int> aCopy(A); std::sort(aCopy.begin(), aCopy.end()); vector<int> result; for (int n = A.size() - 1; n > 0; --n) { int curMax = aCopy[n]; vector<int>::iterator iter = std::find(A.begin(), A.begin() + n, curMax); assert(iter != A.end()); if (iter == A.begin()) { result.push_back(n + 1); std::reverse(A.begin(), A.begin() + n + 1); continue; } ++iter; if (iter == A.end()) { continue; } result.push_back(iter - A.begin()); std::reverse(A.begin(), iter); result.push_back(n + 1); std::reverse(A.begin(), A.begin() + n + 1); } return result; } };
101bfc0d56457900a6a07679d666fee4ae7bd71b
494a70b14ea7689fec132e7859585263482b4aea
/prictice/1015. 德才论.cpp
15ead8d1fabcf3c3ab6a9c1059f4cd24e2708053
[]
no_license
LiBingtao/prictice-for-pat
2181a8f8eb055244c6bed5011adc42240e7780e2
cebaa4c440d25df0191b34ed9ca981d1710279d3
refs/heads/master
2021-06-04T13:51:45.182136
2019-06-20T03:01:21
2019-06-20T03:01:21
96,432,832
0
0
null
null
null
null
UTF-8
C++
false
false
1,383
cpp
1015. 德才论.cpp
#include<iostream> #include<vector> #include <algorithm> using namespace std; struct student { int id; int d; int c; bool operator < (const student &A) const { if (d + c != A.d + A.c) { return d + c > A.d + A.c; } else if (d != A.d) { return d > A.d; } else { return id < A.id; } } }; int main() { int n, l, h; int count=0; vector<student> s1, s2, s3, s4; cin >> n >> l >> h; student tmp; for (int i = 0; i < n; i++) { int a, b, c; cin >> a >> b >> c; tmp.id = a; tmp.d = b; tmp.c = c; if (b >= l &&c >= l) { count++; if (b >= h && c >= h) { s1.push_back(tmp); } else if (b >= h) { s2.push_back(tmp); } else if (b >= c) { s3.push_back(tmp); } else { s4.push_back(tmp); } } } sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); sort(s3.begin(), s3.end()); sort(s4.begin(), s4.end()); cout << count << endl; vector<student>::iterator itr; for (itr = s1.begin(); itr != s1.end(); ++itr) { printf("%d %d %d\n", itr->id, itr->d, itr->c); } for (itr = s2.begin(); itr != s2.end(); ++itr) { printf("%d %d %d\n", itr->id, itr->d, itr->c); } for (itr = s3.begin(); itr != s3.end(); ++itr) { printf("%d %d %d\n", itr->id, itr->d, itr->c); } for (itr = s4.begin(); itr != s4.end(); ++itr) { printf("%d %d %d\n", itr->id, itr->d, itr->c); } cin.get(); cin.get(); return 0; }
3a8f93818794ebbb9d32e9953ab54ddbf010015f
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/boost/metamath/double/integral_to_double.hpp
b75c9cfe5c5a612ba41391449c9cf012c409987e
[ "BSL-1.0" ]
permissive
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
2,219
hpp
integral_to_double.hpp
// Copyright (C) 2005 Peder Holt // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_METAMATH_DOUBLE_INTEGRAL_TO_DOUBLE_HPP #define BOOST_METAMATH_DOUBLE_INTEGRAL_TO_DOUBLE_HPP #include <boost/metamath/double/double.hpp> #include <boost/metamath/double/detail/shift.hpp> #include <boost/metamath/double/detail/mantissa.hpp> namespace boost { namespace metamath { namespace detail { template<typename T,T Number> struct integral_exp { BOOST_STATIC_CONSTANT(int32_t,sign=(Number<0?-1:1)); BOOST_STATIC_CONSTANT(uint32_t,number=sign*Number); BOOST_STATIC_CONSTANT(int16_t,exp16=(number/65536ul)>=1?16:0); BOOST_STATIC_CONSTANT(int16_t,exp8=(number/((1<<exp16)*256ul))>=1?8:0); BOOST_STATIC_CONSTANT(int16_t,exp4=(number/((1<<(exp16+exp8))*16ul))>=1?4:0); BOOST_STATIC_CONSTANT(int16_t,exp2=(number/((1<<(exp16+exp8+exp4))*4ul))>=1?2:0); BOOST_STATIC_CONSTANT(int16_t,exp1=(number/((1<<(exp16+exp8+exp4+exp2))*2ul))>=1?1:0); BOOST_STATIC_CONSTANT(int16_t,value=exp16+exp8+exp4+exp2+exp1); }; } //namespace detail template<typename T,T Value> struct integral_c_to_double { BOOST_STATIC_CONSTANT(bool,sign=Value<0); BOOST_STATIC_CONSTANT(T,unsigned_number=(Value*(sign?-1:1))); BOOST_STATIC_CONSTANT(int16_t,exponent=(detail::integral_exp<T,unsigned_number>::value)); BOOST_STATIC_CONSTANT(uint32_t,part1=(detail::shift_integral<uint32_t,unsigned_number,30-exponent>::value)); BOOST_STATIC_CONSTANT(uint32_t,part2=(detail::shift_integral<uint32_t,unsigned_number,61-exponent>::value)); BOOST_STATIC_CONSTANT(int16_t,exponent_adjusted=(exponent==0 && part1==0 && part2==0)?-1023:exponent); typedef double_<detail::mantissa<part1,part2>,exponent_adjusted,sign> type; }; template<long Value> struct long_to_double : integral_c_to_double<long,Value>::type {}; template<typename T> struct integral_to_double : integral_c_to_double<typename T::value_type,T::value>::type {}; }}//namespace boost::metamath #endif
7a004a476620978068a71fac0cdc253c96e09295
ebe102bfe83cea2eac110058bdc6ea5170a19899
/src/GameObject.h
d80ac9c9214bf9854988c9cf0e7dac7e86b82b58
[]
no_license
DanielJamesCollier/GameCreatorEngine
6c673a4f1a75247c1ba2ddafc20baf21a03201c1
8580330a32d37711fe639db860618a380a628efa
refs/heads/master
2016-09-06T16:45:13.430420
2014-11-19T15:20:54
2014-11-19T15:20:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,352
h
GameObject.h
#pragma once #ifndef GAMEOBJECT_H #define GAMEOBJECT_H #include "Transform.h" #include <string> #include <vector> class WindowEngine; class RenderingEngine; class ShaderProgram; class GameObject : public Transform { public: GameObject(const std::string& name); GameObject(const std::string& name, bool active); GameObject(); virtual ~GameObject(); // setters void setRenderingEngine(RenderingEngine* renderer); void setName(const std::string& name); void setActive(bool active); void setParent(GameObject *parent); void addChild(GameObject *child); void removeChild(GameObject *child); //getters std::string getName(void); GameObject* getParent(void) const; GameObject* getChild(unsigned int i); bool isActive(void); unsigned int getChildCount(void); // virtual functions virtual void render(); virtual void update(WindowEngine* window); virtual void render(ShaderProgram* program, RenderingEngine* render); virtual unsigned int& getVerticesCount(void); virtual unsigned int& getIndicesCount(void); virtual unsigned int& getFacesCount(void); private: GameObject* m_Parent; std::string m_Name; std::vector<GameObject*> m_Children; int m_ChildCount; bool m_Active; unsigned int vertices_count; unsigned int indices_count; unsigned int faces_count; protected: static RenderingEngine* renderer; }; #endif
1d443c7eecc994452b7495e680e9659b38b5ec94
928875667ad05ff415c5d256c9cc246f0d90e6b5
/pf4_1.cpp
b81fc7f6d8eabfc0e8a88eb09387f5bb4f45e743
[]
no_license
ritaxtii/PF1
403df7b800f49e0a15ece0b32b18486142bbdb9c
308f66947a4d32854851d0697d750cb240764fde
refs/heads/master
2023-07-13T02:48:11.839377
2021-08-08T11:39:39
2021-08-08T11:39:39
393,337,301
1
0
null
2021-08-08T11:42:49
2021-08-06T10:09:03
C++
UTF-8
C++
false
false
4,787
cpp
pf4_1.cpp
#include <bits/stdc++.h> using namespace std; int game[6][6] = {}; void L() { for (int i = 1; i <=4; i++) { for (int j = 1; j <=4; j++) { if (game[i][j] != 0) { int now = game[i][j]; for (int k = j-1; k >= 0; k--) { if (game[i][k] != 0) { if (game[i][k] != now) { game[i][j] = 0; game[i][k+1] = now; break; } else { game[i][j] = 0; game[i][k] = now*2; break; } } else if (k == 0) { game[i][j] = 0; game[i][k+1] = now; } } } } } } void R() { for (int i = 1; i <= 4; i++) { for (int j = 4; j >= 1; j--) { if (game[i][j] != 0) { int now = game[i][j]; for (int k = j + 1; k <= 5; k++) { if (game[i][k] != 0) { if (game[i][k] != now) { game[i][j] = 0; game[i][k - 1] = now; break; } else { game[i][j] = 0; game[i][k] = now*2; break; } } else if (k == 5) { game[i][j] = 0; game[i][k - 1] = now; } } } } } } void U() { for (int j = 1; j <= 4; j++) { for (int i = 1; i <= 4; i++) { if (game[i][j] != 0) { int now = game[i][j]; for (int k = i - 1; k >= 0; k--) { if (game[k][j] != 0) { if (game[k][j] != now) { game[i][j] = 0; game[k + 1][j] = now; break; } else { game[i][j] = 0; game[k][j] = now * 2; break; } } else if (k == 0) { game[i][j] = 0; game[k + 1][j] = now; } } } } } } void D() { for (int j = 1; j <= 4; j++) { for (int i = 4; i >= 1; i--) { if (game[i][j] != 0) { int now = game[i][j]; for (int k = i + 1 ; k<=5; k++) { if (game[k][j] != 0) { if (game[k][j] != now) { game[i][j] = 0; game[k - 1][j] = now; break; } else { game[i][j] = 0; game[k][j] = now*2; break; } } else if (k == 5) { game[i][j] = 0; game[k - 1][j] = now; } } } } } } int main() { for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { cin >> game[i][j]; } } string s; cin.ignore(); getline(cin, s); for (int i = 0; i < s.size(); i += 2) { if (s[i] == 'L') L(); if (s[i] == 'R') R(); if (s[i] == 'U') U(); if (s[i] == 'D') D(); } for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { cout << game[i][j]<<" "; } cout << endl; } }
0191af29a76ca8f8d6608eab0bfcbdc05fd85f4d
c13c121d96fdd8682982854f43e50be011863aa1
/Code/Engine/core-AppFlow/Application.cpp
6f932f765b8c6e2d02d51f3f5890277425ea7253
[]
no_license
paksas/Tamy
14fe8e2ff5633ced9b24c855c6e06776bf221c10
6e4bd2f14d54cc718ed12734a3ae0ad52337cf40
refs/heads/master
2020-06-03T08:06:09.511028
2015-03-21T20:37:03
2015-03-21T20:37:03
25,319,755
0
1
null
null
null
null
UTF-8
C++
false
false
690
cpp
Application.cpp
#include "core-AppFlow\Application.h" /////////////////////////////////////////////////////////////////////////////// Application::Application(const std::string& name) : m_name(name), m_context(NULL), m_timeController(new TimeController()) { } /////////////////////////////////////////////////////////////////////////////// Application::~Application() { delete m_timeController; m_timeController = NULL; } /////////////////////////////////////////////////////////////////////////////// void Application::update(float timeElapsed) { m_timeController->update(timeElapsed); } ///////////////////////////////////////////////////////////////////////////////
19c1e383cba35d15af1eee115561b067c1a89366
5b5303bcea534917b64390bda78ddfb9ea56e39e
/number/miller-rabin.inc.cpp
87b9938951cbceab52ea79dd3c0819c6758f7655
[ "MIT" ]
permissive
Mohammad-Yasser/competitive-programming-library
d60aa606bcb79fbc6946aa368bb838a8b1eb80f3
4656ac0d625abce98b901965c7607c1b908b093f
refs/heads/master
2020-12-03T16:52:52.677115
2019-12-30T18:45:08
2019-12-30T18:45:08
231,397,316
3
0
MIT
2020-01-02T14:24:42
2020-01-02T14:24:42
null
UTF-8
C++
false
false
839
cpp
miller-rabin.inc.cpp
// https://kimiyuki.net/blog/2016/02/01/cf-gym-100753/ template <class Generator> bool is_prime(ll n, int iteration, Generator & gen) { // miller-rabin primality test, O(k log n) assert (0 <= n); if (n == 2) return true; if (n == 1 or n % 2 == 0) return false; const ll d = (n-1) >> __builtin_ctzll(n-1); // remove trailing zeros uniform_int_distribution<ll> dist(1, n-2); // [l, r] repeat (dummy, iteration) { ll a = dist(gen); ll t = d; ll y = powmod(a, t, n); while (t != n-1 and y != 1 and y != n-1) { y = y * y % n; t *= 2; } if (y != n-1 and t % 2 == 0) return false; } return true; } bool is_prime(ll n) { static default_random_engine engine = default_random_engine(random_device()()); return is_prime(n, 20, engine); }
ca89caec7e59fd62c421b024a5fb0db923c1ec7b
b9432d03b21d6e72e34d4697b58c240210d2d4a0
/service_apis/youtube/google/youtube_api/live_chat_message_snippet.h
21401cdf2338c2bfbebcc88d5d62bbed663995b1
[ "Apache-2.0" ]
permissive
harshapat/google-api-cpp-client
f5edbf7674459c30e894430cda199d4a3b9788fb
7fb12b4bbb9db27fffede054149cf77c8e1c307f
refs/heads/master
2021-01-19T13:19:36.475387
2017-02-18T12:25:02
2017-02-18T12:25:02
82,384,775
0
0
null
2017-02-18T12:21:54
2017-02-18T12:21:54
null
UTF-8
C++
false
false
11,006
h
live_chat_message_snippet.h
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // C++ generator version: 0.1.3 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.3 #ifndef GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/live_chat_fan_funding_event_details.h" #include "google/youtube_api/live_chat_text_message_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveChatMessageSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveChatMessageSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatMessageSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatMessageSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveChatMessageSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveChatMessageSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveChatMessageSnippet"); } /** * Determine if the '<code>authorChannelId</code>' attribute was set. * * @return true if the '<code>authorChannelId</code>' attribute was set. */ bool has_author_channel_id() const { return Storage().isMember("authorChannelId"); } /** * Clears the '<code>authorChannelId</code>' attribute. */ void clear_author_channel_id() { MutableStorage()->removeMember("authorChannelId"); } /** * Get the value of the '<code>authorChannelId</code>' attribute. */ const StringPiece get_author_channel_id() const { const Json::Value& v = Storage("authorChannelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>authorChannelId</code>' attribute. * * The ID of the user that authored this message, this field is not always * filled. textMessageEvent - the user that wrote the message fanFundingEvent * - the user that funded the broadcast newSponsorEvent - the user that just * became a sponsor. * * @param[in] value The new value. */ void set_author_channel_id(const StringPiece& value) { *MutableStorage("authorChannelId") = value.data(); } /** * Determine if the '<code>displayMessage</code>' attribute was set. * * @return true if the '<code>displayMessage</code>' attribute was set. */ bool has_display_message() const { return Storage().isMember("displayMessage"); } /** * Clears the '<code>displayMessage</code>' attribute. */ void clear_display_message() { MutableStorage()->removeMember("displayMessage"); } /** * Get the value of the '<code>displayMessage</code>' attribute. */ const StringPiece get_display_message() const { const Json::Value& v = Storage("displayMessage"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>displayMessage</code>' attribute. * * Contains a string that can be displayed to the user. If this field is not * present the message is silent, at the moment only messages of type * TOMBSTONE and CHAT_ENDED_EVENT are silent. * * @param[in] value The new value. */ void set_display_message(const StringPiece& value) { *MutableStorage("displayMessage") = value.data(); } /** * Determine if the '<code>fanFundingEventDetails</code>' attribute was set. * * @return true if the '<code>fanFundingEventDetails</code>' attribute was * set. */ bool has_fan_funding_event_details() const { return Storage().isMember("fanFundingEventDetails"); } /** * Clears the '<code>fanFundingEventDetails</code>' attribute. */ void clear_fan_funding_event_details() { MutableStorage()->removeMember("fanFundingEventDetails"); } /** * Get a reference to the value of the '<code>fanFundingEventDetails</code>' * attribute. */ const LiveChatFanFundingEventDetails get_fan_funding_event_details() const; /** * Gets a reference to a mutable value of the * '<code>fanFundingEventDetails</code>' property. * * Details about the funding event, this is only set if the type is * 'fanFundingEvent'. * * @return The result can be modified to change the attribute value. */ LiveChatFanFundingEventDetails mutable_fanFundingEventDetails(); /** * Determine if the '<code>hasDisplayContent</code>' attribute was set. * * @return true if the '<code>hasDisplayContent</code>' attribute was set. */ bool has_has_display_content() const { return Storage().isMember("hasDisplayContent"); } /** * Clears the '<code>hasDisplayContent</code>' attribute. */ void clear_has_display_content() { MutableStorage()->removeMember("hasDisplayContent"); } /** * Get the value of the '<code>hasDisplayContent</code>' attribute. */ bool get_has_display_content() const { const Json::Value& storage = Storage("hasDisplayContent"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hasDisplayContent</code>' attribute. * * Whether the message has display content that should be displayed to users. * * @param[in] value The new value. */ void set_has_display_content(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hasDisplayContent")); } /** * Determine if the '<code>liveChatId</code>' attribute was set. * * @return true if the '<code>liveChatId</code>' attribute was set. */ bool has_live_chat_id() const { return Storage().isMember("liveChatId"); } /** * Clears the '<code>liveChatId</code>' attribute. */ void clear_live_chat_id() { MutableStorage()->removeMember("liveChatId"); } /** * Get the value of the '<code>liveChatId</code>' attribute. */ const StringPiece get_live_chat_id() const { const Json::Value& v = Storage("liveChatId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>liveChatId</code>' attribute. * @param[in] value The new value. */ void set_live_chat_id(const StringPiece& value) { *MutableStorage("liveChatId") = value.data(); } /** * Determine if the '<code>publishedAt</code>' attribute was set. * * @return true if the '<code>publishedAt</code>' attribute was set. */ bool has_published_at() const { return Storage().isMember("publishedAt"); } /** * Clears the '<code>publishedAt</code>' attribute. */ void clear_published_at() { MutableStorage()->removeMember("publishedAt"); } /** * Get the value of the '<code>publishedAt</code>' attribute. */ client::DateTime get_published_at() const { const Json::Value& storage = Storage("publishedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishedAt</code>' attribute. * * The date and time when the message was orignally published. The value is * specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_published_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishedAt")); } /** * Determine if the '<code>textMessageDetails</code>' attribute was set. * * @return true if the '<code>textMessageDetails</code>' attribute was set. */ bool has_text_message_details() const { return Storage().isMember("textMessageDetails"); } /** * Clears the '<code>textMessageDetails</code>' attribute. */ void clear_text_message_details() { MutableStorage()->removeMember("textMessageDetails"); } /** * Get a reference to the value of the '<code>textMessageDetails</code>' * attribute. */ const LiveChatTextMessageDetails get_text_message_details() const; /** * Gets a reference to a mutable value of the * '<code>textMessageDetails</code>' property. * * Details about the text message, this is only set if the type is * 'textMessageEvent'. * * @return The result can be modified to change the attribute value. */ LiveChatTextMessageDetails mutable_textMessageDetails(); /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The type of message, this will always be present, it determines the * contents of the message as well as which fields will be present. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const LiveChatMessageSnippet&); }; // LiveChatMessageSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_SNIPPET_H_
2d9110784b55dd697159c30f0534e229843cd2b3
3ad9b096e235bebec814e9d6bd0bea9473a24f2d
/src/plots/Molecule/MoleculeAttributes.h
e163a49c06f65c0135d6db93f99da2af391bd26a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
larrycameron80/visit
bca20089d4642fc9e40f605404bc5408ef4c465f
e20e2ddbec3b0ceb611a0588898f652432165a24
refs/heads/develop
2020-06-05T09:28:16.704247
2019-06-14T22:02:59
2019-06-14T22:02:59
192,389,674
0
0
BSD-3-Clause
2019-09-17T07:05:10
2019-06-17T17:23:31
C
UTF-8
C++
false
false
10,400
h
MoleculeAttributes.h
/***************************************************************************** * * Copyright (c) 2000 - 2019, Lawrence Livermore National Security, LLC * Produced at the Lawrence Livermore National Laboratory * LLNL-CODE-442911 * All rights reserved. * * This file is part of VisIt. For details, see https://visit.llnl.gov/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or other materials provided with the distribution. * - Neither the name of the LLNS/LLNL nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, * LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * *****************************************************************************/ #ifndef MOLECULEATTRIBUTES_H #define MOLECULEATTRIBUTES_H #include <string> #include <AttributeSubject.h> #include <ColorAttribute.h> // **************************************************************************** // Class: MoleculeAttributes // // Purpose: // This class contains the plot attributes for the molecule plot. // // Notes: Autogenerated by xml2atts. // // Programmer: xml2atts // Creation: omitted // // Modifications: // // **************************************************************************** class MoleculeAttributes : public AttributeSubject { public: enum AtomRenderingMode { NoAtoms, SphereAtoms, ImposterAtoms }; enum RadiusType { Fixed, Covalent, Atomic, Variable }; enum BondColoringMode { ColorByAtom, SingleColor }; enum BondRenderingMode { NoBonds, LineBonds, CylinderBonds }; enum DetailLevel { Low, Medium, High, Super }; // These constructors are for objects of this class MoleculeAttributes(); MoleculeAttributes(const MoleculeAttributes &obj); protected: // These constructors are for objects derived from this class MoleculeAttributes(private_tmfs_t tmfs); MoleculeAttributes(const MoleculeAttributes &obj, private_tmfs_t tmfs); public: virtual ~MoleculeAttributes(); virtual MoleculeAttributes& operator = (const MoleculeAttributes &obj); virtual bool operator == (const MoleculeAttributes &obj) const; virtual bool operator != (const MoleculeAttributes &obj) const; private: void Init(); void Copy(const MoleculeAttributes &obj); public: virtual const std::string TypeName() const; virtual bool CopyAttributes(const AttributeGroup *); virtual AttributeSubject *CreateCompatible(const std::string &) const; virtual AttributeSubject *NewInstance(bool) const; // Property selection methods virtual void SelectAll(); void SelectBondSingleColor(); void SelectRadiusVariable(); void SelectElementColorTable(); void SelectResidueTypeColorTable(); void SelectResidueSequenceColorTable(); void SelectContinuousColorTable(); // Property setting methods void SetDrawAtomsAs(AtomRenderingMode drawAtomsAs_); void SetScaleRadiusBy(RadiusType scaleRadiusBy_); void SetDrawBondsAs(BondRenderingMode drawBondsAs_); void SetColorBonds(BondColoringMode colorBonds_); void SetBondSingleColor(const ColorAttribute &bondSingleColor_); void SetRadiusVariable(const std::string &radiusVariable_); void SetRadiusScaleFactor(float radiusScaleFactor_); void SetRadiusFixed(float radiusFixed_); void SetAtomSphereQuality(DetailLevel atomSphereQuality_); void SetBondCylinderQuality(DetailLevel bondCylinderQuality_); void SetBondRadius(float bondRadius_); void SetBondLineWidth(int bondLineWidth_); void SetElementColorTable(const std::string &elementColorTable_); void SetResidueTypeColorTable(const std::string &residueTypeColorTable_); void SetResidueSequenceColorTable(const std::string &residueSequenceColorTable_); void SetContinuousColorTable(const std::string &continuousColorTable_); void SetLegendFlag(bool legendFlag_); void SetMinFlag(bool minFlag_); void SetScalarMin(float scalarMin_); void SetMaxFlag(bool maxFlag_); void SetScalarMax(float scalarMax_); // Property getting methods AtomRenderingMode GetDrawAtomsAs() const; RadiusType GetScaleRadiusBy() const; BondRenderingMode GetDrawBondsAs() const; BondColoringMode GetColorBonds() const; const ColorAttribute &GetBondSingleColor() const; ColorAttribute &GetBondSingleColor(); const std::string &GetRadiusVariable() const; std::string &GetRadiusVariable(); float GetRadiusScaleFactor() const; float GetRadiusFixed() const; DetailLevel GetAtomSphereQuality() const; DetailLevel GetBondCylinderQuality() const; float GetBondRadius() const; int GetBondLineWidth() const; const std::string &GetElementColorTable() const; std::string &GetElementColorTable(); const std::string &GetResidueTypeColorTable() const; std::string &GetResidueTypeColorTable(); const std::string &GetResidueSequenceColorTable() const; std::string &GetResidueSequenceColorTable(); const std::string &GetContinuousColorTable() const; std::string &GetContinuousColorTable(); bool GetLegendFlag() const; bool GetMinFlag() const; float GetScalarMin() const; bool GetMaxFlag() const; float GetScalarMax() const; // Persistence methods virtual bool CreateNode(DataNode *node, bool completeSave, bool forceAdd); virtual void SetFromNode(DataNode *node); // Enum conversion functions static std::string AtomRenderingMode_ToString(AtomRenderingMode); static bool AtomRenderingMode_FromString(const std::string &, AtomRenderingMode &); protected: static std::string AtomRenderingMode_ToString(int); public: static std::string RadiusType_ToString(RadiusType); static bool RadiusType_FromString(const std::string &, RadiusType &); protected: static std::string RadiusType_ToString(int); public: static std::string BondColoringMode_ToString(BondColoringMode); static bool BondColoringMode_FromString(const std::string &, BondColoringMode &); protected: static std::string BondColoringMode_ToString(int); public: static std::string BondRenderingMode_ToString(BondRenderingMode); static bool BondRenderingMode_FromString(const std::string &, BondRenderingMode &); protected: static std::string BondRenderingMode_ToString(int); public: static std::string DetailLevel_ToString(DetailLevel); static bool DetailLevel_FromString(const std::string &, DetailLevel &); protected: static std::string DetailLevel_ToString(int); public: // Keyframing methods virtual std::string GetFieldName(int index) const; virtual AttributeGroup::FieldType GetFieldType(int index) const; virtual std::string GetFieldTypeName(int index) const; virtual bool FieldsEqual(int index, const AttributeGroup *rhs) const; // User-defined methods bool ChangesRequireRecalculation(const MoleculeAttributes &); // IDs that can be used to identify fields in case statements enum { ID_drawAtomsAs = 0, ID_scaleRadiusBy, ID_drawBondsAs, ID_colorBonds, ID_bondSingleColor, ID_radiusVariable, ID_radiusScaleFactor, ID_radiusFixed, ID_atomSphereQuality, ID_bondCylinderQuality, ID_bondRadius, ID_bondLineWidth, ID_elementColorTable, ID_residueTypeColorTable, ID_residueSequenceColorTable, ID_continuousColorTable, ID_legendFlag, ID_minFlag, ID_scalarMin, ID_maxFlag, ID_scalarMax, ID__LAST }; private: int drawAtomsAs; int scaleRadiusBy; int drawBondsAs; int colorBonds; ColorAttribute bondSingleColor; std::string radiusVariable; float radiusScaleFactor; float radiusFixed; int atomSphereQuality; int bondCylinderQuality; float bondRadius; int bondLineWidth; std::string elementColorTable; std::string residueTypeColorTable; std::string residueSequenceColorTable; std::string continuousColorTable; bool legendFlag; bool minFlag; float scalarMin; bool maxFlag; float scalarMax; // Static class format string for type map. static const char *TypeMapFormatString; static const private_tmfs_t TmfsStruct; }; #define MOLECULEATTRIBUTES_TMFS "iiiiasffiifissssbbfbf" #endif
7c5051c73c6c1a2ed4ef63301d95cf2072cde10e
32b3526952067b43e5f467d76ce7616a0b2b66f5
/amperson contra.cpp
04d995e5fe5b9d371c72850b5a2a8e179cae7b94
[]
no_license
luisenano90/Ejemplos-en-clase
8127e31a5f05670fca1905b877693545cec2fac5
95058813a0f1a56af74259f7cb632a01c968a207
refs/heads/main
2023-02-19T08:13:28.753704
2021-01-23T22:28:45
2021-01-23T22:28:45
311,540,670
0
0
null
null
null
null
UTF-8
C++
false
false
146
cpp
amperson contra.cpp
#include <iostream> int main() { int x{5}; std::cout<<x<<'\n'; std::cout<<&x<<'\n'; std::cout<<*(&x)<<'\n'; return 0; }
cc4f18e121aa83ba7310809109eaad30297b70c1
01ab791f54e388c62209ce0af66219bfbc030c3c
/253th/6/apple.cpp
379ddd7cd8e450ab28c28689d6080a1e16f2bf53
[]
no_license
warpdev/koi-exercise-2011-2016
d2335696d33fa23bcc9a3f5f33b0a1610d530989
d948f978a6d32e2e01aa1fdf8dc272e2a4c0384a
refs/heads/master
2023-04-06T06:58:51.031574
2021-04-14T07:27:32
2021-04-14T07:27:32
357,812,551
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
apple.cpp
#include <stdio.h> #define N 100 FILE *fp1,*fp2; int t,n,m; int cnt; void process(int x,int y) { int i,k,j,tm; k=x/y; for(i=0; i<=k; i++){ tm=x-(y*i); cnt+=tm/2+1; } } void input(void) { int i; fscanf(fp1,"%d",&t); for(i=1; i<=t; i++){ fscanf(fp1,"%d %d",&n,&m); cnt=0; process(n,m); fprintf(fp2,"%d\n",cnt); } } int main(void) { fp1=fopen("input.txt","r"); fp2=fopen("output.txt","w"); input(); return 0; }
9194caa605e232918f6c7222cde5e8db05310961
4e8018d32c8215c2565529ab8956c141ef1c582a
/Data-Structures/Array/leadersinanarray.cpp
4e49e8f8dc00f52d032d9ebdf912b1712fb9ad4a
[ "MIT" ]
permissive
Ronak55/algo_ds_101
1a898f3127b2c83fccba782d22e8d61347dc37ba
81836535369bef0a4f71cb2d7f3d67a49e08dd4e
refs/heads/main
2023-08-25T12:08:23.381418
2021-10-03T08:10:16
2021-10-03T08:10:16
413,011,973
0
0
MIT
2021-10-03T07:51:14
2021-10-03T07:51:13
null
UTF-8
C++
false
false
622
cpp
leadersinanarray.cpp
#include <iostream> using namespace std; /* C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { int max_from_right = arr[size - 1]; /* Rightmost element is always leader */ cout << max_from_right << " "; for (int i = size - 2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; cout << max_from_right << " "; } } } /* Driver program to test above function*/ int main() { int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr) / sizeof(arr[0]); printLeaders(arr, n); return 0; }
11b206e59631cb98e30e76e3366e486761c7d398
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1285485_0/C++/rlblaster/d.cpp
d4f6a2ee8bf861b8485edd959fe4c247d2d19243
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,792
cpp
d.cpp
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <utility> #include <valarray> #include <vector> using namespace std; #define ALL(x) (x).begin(), (x).end() #define MP make_pair #define SZ(x) ((int) (x).size()) #define maxit(x,y) ((x) = max((x),(y))) #define minit(x,y) ((x) = min((x),(y))) typedef long long LL; bool was[4][2000][2000]; bool wasat(int dir, int dr, int dc) { if (dr >= 2000 || dc >= 2000) return true; int g = __gcd(dr, dc); dr /= g; dc /= g; return was[dir][dr][dc]; } void setat(int dir, int dr, int dc) { if (dr >= 2000 || dc >= 2000) return; int g = __gcd(dr, dc); dr /= g; dc /= g; was[dir][dr][dc] = true; } int main() { setlinebuf(stdout); int cases; scanf("%d", &cases); for (int T = 1; T <= cases; ++T) { memset(was, 0, sizeof was); int R, C, D; int rr = -1, cc = -1; scanf("%d %d %d", &R, &C, &D); for (int r = 0; r < R; ++r) { char buf[256]; scanf("%s", buf); char *p = strchr(buf, 'X'); if (p != NULL) { rr = r; cc = p - buf; } } long r1 = 1 + 2*(rr - 1); long r2 = 1 + 2*(R-2 - rr); long c1 = 1 + 2*(cc - 1); long c2 = 1 + 2*(C-2 - cc); int result = 0; for (int r = 0; r < 1600; ++r) { for (int c = 0; c < 1600; ++c) { if (r == 0 && c == 0) continue; long dr1 = (r-1)*2*(R-2) + r1 + ((1-r%2)?r2:r1); long dr2 = (r-1)*2*(R-2) + r2 + ((1-r%2)?r1:r2); if (r == 0) dr1 = dr2 = 0; long dc1 = (c-1)*2*(C-2) + c1 + ((1-c%2)?c2:c1); long dc2 = (c-1)*2*(C-2) + c2 + ((1-c%2)?c1:c2); if (c == 0) dc1 = dc2 = 0; int cnt = 0; if (r == 0) { if (!wasat(0, dr1, dc1) && dc1*dc1 <= 4*D*D) cnt += 1; setat(0, dr1, dc1); if (!wasat(1, dr1, dc2) && dc2*dc2 <= 4*D*D) cnt += 1; setat(1, dr1, dc2); } else if (c == 0) { if (!wasat(2, dr1, dc1) && dr1*dr1 <= 4*D*D) cnt += 1; setat(2, dr1, dc1); if (!wasat(3, dr2, dc1) && dr2*dr2 <= 4*D*D) cnt += 1; setat(3, dr2, dc1); } else { if (!wasat(0, dr1, dc1) && dr1*dr1 + dc1*dc1 <= 4*D*D) cnt += 1; setat(0, dr1, dc1); if (!wasat(1, dr2, dc1) && dr2*dr2 + dc1*dc1 <= 4*D*D) cnt += 1; setat(1, dr2, dc1); if (!wasat(2, dr1, dc2) && dr1*dr1 + dc2*dc2 <= 4*D*D) cnt += 1; setat(2, dr1, dc2); if (!wasat(3, dr2, dc2) && dr2*dr2 + dc2*dc2 <= 4*D*D) cnt += 1; setat(3, dr2, dc2); } //if (cnt != 0) printf("%d %d => %d\n", r, c, cnt); result += cnt; } } printf("Case #%d: %d\n", T, result); } return 0; }
e23e72f8bd230edbaf7d2f835a3b0eb01ab7ad9c
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_1/processor28/constant/polyMesh/owner
bee479f8dbd6eeeb70ccdbe0c963550c09b6d9ca
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
1,306
owner
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class labelList; note "nPoints: 184 nCells: 36 nFaces: 194 nInternalFaces: 22"; location "constant/polyMesh"; object owner; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 194 ( 0 1 7 9 11 13 16 16 18 18 21 22 24 25 26 27 28 29 31 32 33 34 0 1 2 21 22 23 30 35 0 1 2 3 0 1 2 3 4 5 6 7 8 9 10 4 5 6 7 8 9 10 18 16 19 17 15 13 14 11 12 18 16 19 17 15 13 14 11 12 21 22 23 20 21 22 23 20 24 25 26 27 28 29 30 24 25 26 27 28 29 30 31 32 33 34 35 31 32 33 34 35 7 9 11 13 26 27 28 29 30 33 34 35 2 3 3 4 4 5 5 6 6 7 8 9 10 12 14 11 13 15 16 15 17 16 18 18 20 21 24 25 31 32 0 1 2 3 3 4 4 5 5 6 6 7 8 8 10 12 13 14 14 15 15 17 17 19 19 20 20 21 22 23 24 31 0 9 10 11 12 23 25 26 27 28 29 30 32 33 34 35 24 31 ) // ************************************************************************* //
ae8000b950fe0210d6fe37e9578a6c5db2ac4bd5
d115107dee446f2767bb76d0128f8210ca7666a4
/Fractional Knapsack.cpp
bd797e78628473f7472289554a1eb99f2c8d40d2
[]
no_license
jeevansingh901/HACKERBLOCKS
a86696c5accedbdbccb847a43b2f8f45e43f6b9f
9fefff3a65866d79daf578edbeb242fc670f63e0
refs/heads/master
2021-05-18T19:31:32.162971
2020-07-08T18:06:52
2020-07-08T18:06:52
251,379,451
1
0
null
null
null
null
UTF-8
C++
false
false
1,171
cpp
Fractional Knapsack.cpp
#include <iostream> #include<bits/stdc++.h> #include <algorithm> #include <vector> using namespace std; bool mycompare(pair<int, int> a, pair<int, int> b) { float a1 = (float)a.first / a.second; float b1 = (float)b.first / b.second; return a1 > b1; } void print(vector<pair<int, int>> &items) { for (auto p : items) { cout << p.first << " " << p.second << endl; } } int main() { int s, n; cin >> n >> s; vector<pair<int, int>> items; while (n--) { int sz, value; cin >> value>> sz; pair<int, int> a(value, sz); items.push_back(a); } sort(items.begin(), items.end(), mycompare); int currsize = 0; double maxvalue = 0.0; for (auto p : items) { if (currsize + p.second <= s) { maxvalue += p.first; currsize += p.second; } else { if(currsize != s) { int sizereq = s-currsize; maxvalue += sizereq*((float)p.first/p.second); currsize = s; } } } cout <<fixed<<setprecision(1)<< maxvalue << endl; }
9796becfe96f63f5f5a4ed117a0d98b96780a310
47db1f0373e632a22b885a5d7cc2457a6784a56f
/src/argparse_test/main.cpp
2885d404429ed97282da3985b41695fcc08fa301
[ "MIT" ]
permissive
wnsgml972/queryparse
e67d650b6b5b489ab6f419d8a7be92b33004f09f
1d41d9d1690ff6b912d40af6a03e16fe9662effc
refs/heads/master
2020-06-28T04:54:45.727203
2019-11-22T08:10:54
2019-11-22T08:10:54
200,147,136
0
1
null
null
null
null
UTF-8
C++
false
false
398
cpp
main.cpp
#define CATCH_CONFIG_MAIN #include <iostream> #include <argparse.hpp> #include <test_parse_args.hpp> #include <test_positional_arguments.hpp> #include <test_optional_arguments.hpp> #include <test_compound_arguments.hpp> #include <test_actions.hpp> #include <test_container_arguments.hpp> #include <test_parent_parsers.hpp> #include <test_invalid_arguments.hpp> #include <test_negative_numbers.hpp>
34b0f43ef4f873cb50b667ff37bbe9133507578e
297025a16ab829071cac29ce516026734a90c898
/ad7606_dsp/host/ipc/ring_buffer.cpp
f99786208cb15d32df2e32076e52b5a10709e981
[]
no_license
carloscn/omapl-netplot
c33d8d1de28c8f14316e1a3c02b5ab8653406f23
78b6161f9bf806d5ac56a0e8e6808e2e8c4f732c
refs/heads/master
2022-04-08T22:36:38.001162
2019-12-04T06:43:33
2019-12-04T06:43:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,181
cpp
ring_buffer.cpp
#include <stdlib.h> #include <string.h> #include "ring_buffer.h" #include <ti/syslink/RingIOShm.h> #include "log.h" RingBuffer::RingBuffer(uint32_t proc, const std::string &name, uint32_t share_region) : m_alive(false) { RingIOShm_Params params_create; RingIOShm_Params_init(&params_create); params_create.commonParams.name = strdup(name.c_str()); params_create.ctrlRegionId = share_region; params_create.dataRegionId = share_region; params_create.attrRegionId = share_region; params_create.attrSharedAddrSize = 16; params_create.dataSharedAddrSize = 0x900000; /* 9M 大小的数据区,最大为10M,这个可以在配置文件中配置 (../shared/config.bld) */ params_create.remoteProcId = proc; params_create.gateHandle = NULL; /* 使用默认的 Gate */ m_handle = RingIO_create(&params_create); if(m_handle == NULL) { LOG_ERROR("failed to create ring io %s", name.c_str()); m_alive = false; } else { RingIO_openParams params_open; params_open.openMode = RingIO_MODE_READER; params_open.flags = 0; if (RingIO_open (strdup(name.c_str()), &params_open, NULL, &m_read_handle) < 0) { /* 读模式打开 */ LOG_ERROR("failed to open ring io"); m_alive = false; } LOG_DEBUG("%s is ready", name.c_str()); m_alive = true; } } RingBuffer::~RingBuffer() { if (m_alive) { RingIO_close(&m_read_handle); RingIO_delete(&m_handle); } } void *RingBuffer::acquired(uint32_t size) { if (! m_alive) { LOG_WARN("ring buffer is not alive"); return NULL; } uint8_t *buf; if (RingIO_acquire(m_read_handle, (RingIO_BufPtr*)&buf, &size) != RingIO_S_SUCCESS) { LOG_ERROR("unstatified acquired, max is %d", size); return NULL; } return (void *)buf; } void RingBuffer::release(uint32_t size) { if (! m_alive) { LOG_WARN("ring buffer is not alive"); return; } if (RingIO_release(m_read_handle, size) < 0) LOG_ERROR("failed to release buffer"); }
2b08a98d7c3c7834baa2c7d80142b082facad3a7
de9740ac4f0843c22f9eee09981fd6a1d6045439
/SimpleC++/Lesson09: Arrays/9-3.cpp
2a037919e44e3291da5a6f37058495877c97742f
[]
no_license
7omich/cpp-practice
84a6a0e20a539b14f025d156b2f335f8d464b884
c29e5fa401d8a8cf25676d887fb927d7d7db9b5b
refs/heads/master
2020-03-13T16:27:48.676834
2019-01-05T13:28:36
2019-01-05T13:28:36
131,198,312
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
9-3.cpp
#include <iostream> using namespace std; int count(char str[], char ch); int main() { char str[100]; char ch; cout << "文字列を入力してください。\n"; cin >> str; cout << "文字列から探す文字を入力してください。\n"; cin >> ch; cout << str << "の中に" << ch << "は全部で" << count(str, ch) << "個あります。\n"; return 0; } int count(char str[], char ch) { int count = 0; for (int i = 0; str[i] != '\0'; i++) { if (str[i] == ch) { count++; } } return count; }
ccfbfcef65f3b3346bf6bc7af13ba0c881e612b1
da2c356810dc55182cb3c9857918a10e7615b91a
/1385.两个数组间的距离值.cpp
a33d752013679e3da4dcee01f1316b43db1f30c5
[]
no_license
FuChaolei/leetcode_ago
93305c239309f827d402d86f932847c1ccd61fbb
265f29d5e6fe4a040a90cab8c653ab52589a6c5f
refs/heads/main
2023-08-07T18:02:54.117463
2021-09-23T14:22:31
2021-09-23T14:22:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,229
cpp
1385.两个数组间的距离值.cpp
/* * @lc app=leetcode.cn id=1385 lang=cpp * * [1385] 两个数组间的距离值 * * https://leetcode-cn.com/problems/find-the-distance-value-between-two-arrays/description/ * * algorithms * Easy (70.43%) * Likes: 21 * Dislikes: 0 * Total Accepted: 12.1K * Total Submissions: 17.2K * Testcase Example: '[4,5,8]\n[10,9,1,8]\n2' * * 给你两个整数数组 arr1 , arr2 和一个整数 d ,请你返回两个数组之间的 距离值 。 * * 「距离值」 定义为符合此距离要求的元素数目:对于元素 arr1[i] ,不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= * d 。 * * * * 示例 1: * * 输入:arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 * 输出:2 * 解释: * 对于 arr1[0]=4 我们有: * |4-10|=6 > d=2 * |4-9|=5 > d=2 * |4-1|=3 > d=2 * |4-8|=4 > d=2 * 所以 arr1[0]=4 符合距离要求 * * 对于 arr1[1]=5 我们有: * |5-10|=5 > d=2 * |5-9|=4 > d=2 * |5-1|=4 > d=2 * |5-8|=3 > d=2 * 所以 arr1[1]=5 也符合距离要求 * * 对于 arr1[2]=8 我们有: * |8-10|=2 <= d=2 * |8-9|=1 <= d=2 * |8-1|=7 > d=2 * |8-8|=0 <= d=2 * 存在距离小于等于 2 的情况,不符合距离要求 * * 故而只有 arr1[0]=4 和 arr1[1]=5 两个符合距离要求,距离值为 2 * * 示例 2: * * 输入:arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3 * 输出:2 * * * 示例 3: * * 输入:arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6 * 输出:1 * * * * * 提示: * * * 1 <= arr1.length, arr2.length <= 500 * -10^3 <= arr1[i], arr2[j] <= 10^3 * 0 <= d <= 100 * * */ // @lc code=start class Solution { public: int findTheDistanceValue(vector<int> &arr1, vector<int> &arr2, int d) { int res = 0; for (int i = 0; i < arr1.size(); i++) { for (int j = 0; j < arr2.size(); j++) { if (abs(arr1[i] - arr2[j]) <= d) { break; } else { if (j == arr2.size() - 1) res++; } } } return res; } }; // @lc code=end
8c0809ed3c15cc9494d57c126f61dd716a744289
6923f79f1eaaba0ab28b25337ba6cb56be97d32d
/NumericalRecipes2/examples/xsvdcmp.cpp
33373094c337c466b7b9cc1bf60c91dcd6381b32
[]
no_license
burakbayramli/books
9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
refs/heads/master
2023-08-17T05:31:08.885134
2023-08-14T10:05:37
2023-08-14T10:05:37
72,460,321
223
174
null
2022-10-24T12:15:06
2016-10-31T17:24:00
Jupyter Notebook
UTF-8
C++
false
false
2,353
cpp
xsvdcmp.cpp
#include <string> #include <fstream> #include <iostream> #include <iomanip> #include "nr.h" using namespace std; // Driver for routine svdcmp int main(void) { int j,k,l,m,n; string txt; ifstream fp("matrx3.dat"); // read input matrices if (fp.fail()) NR::nrerror("Data file matrx3.dat not found"); getline(fp,txt); while (!fp.eof()) { getline(fp,txt); fp >> m >> n; getline(fp,txt); Vec_DP w(n); Mat_DP a(m,n),u(m,n),v(n,n); getline(fp,txt); // copy original matrix into u cout << fixed << setprecision(6); for (k=0;k<m;k++) for (l=0;l<n;l++) { fp >> a[k][l]; u[k][l]=a[k][l]; } getline(fp,txt); getline(fp,txt); // perform decomposition NR::svdcmp(u,w,v); // write results cout << "Decomposition matrices:" << endl; cout << "Matrix u" << endl; for (k=0;k<m;k++) { for (l=0;l<n;l++) cout << setw(12) << u[k][l]; cout << endl; } cout << "Diagonal of matrix w" << endl; for (k=0;k<n;k++) cout << setw(12) << w[k]; cout << endl << "Matrix v-transpose" << endl; for (k=0;k<n;k++) { for (l=0;l<n;l++) cout << setw(12) << v[l][k]; cout << endl; } cout << endl << "Check product against original matrix:" << endl; cout << "Original matrix:" << endl; for (k=0;k<m;k++) { for (l=0;l<n;l++) cout << setw(12) << a[k][l]; cout << endl; } cout << "Product u*w*(v-transpose):" << endl; for (k=0;k<m;k++) { for (l=0;l<n;l++) { a[k][l]=0.0; for (j=0;j<n;j++) a[k][l] += u[k][j]*w[j]*v[l][j]; } for (l=0;l<n;l++) cout << setw(12) << a[k][l]; cout << endl; } cout << "***********************************" << endl; cout << "press RETURN for next problem" << endl; cin.get(); } fp.close(); return 0; }
6d8a0d04f4f1475315a03c57ae47e9bb4c477632
f7fab58a21edf076208d5c74d978d3400e88f597
/The_tree_out_of_gate.cpp
e5b4eaa7fafbc77b9f164035272554b94ef25231
[]
no_license
iwits/C-Plus-Plus
96c551ac9f8bcdbcb8d491ae5f701512d06f3f32
7bbab21ac18f91f47712b3a94fc85e6fb70190ff
refs/heads/master
2020-12-15T19:25:06.846191
2016-08-22T08:40:19
2016-08-22T08:40:19
60,201,965
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
The_tree_out_of_gate.cpp
/*#include<iostream> using namespace std; int main() { int L, M, number = 0; while (cin >> L >> M) { int start[100], end[100], length[1000] = { 0 }; for (int i = 0; i < M; i++) { cin >> start[i] >> end[i]; for (int j = start[i]; j <= end[i]; j++) { length[j] = 1; } } for (int i = 0; i <= L; i++) { if (length[i] == 0) number++; } cout << number << endl; } return 0; }*/ #include<stdio.h> #include<iostream> using namespace std; int main() { int L, m, i, j; int a, b; int k[10002] = { 0 }; int s = 0; cin >> L >> m; for (i = 0; i<m; i++) { cin >> a >> b; for (j = a; j <= b; j++) { k[j] = 1; } } for (i = 0; i <= L; i++) { if (k[i] == 1) s++; } cout << L + 1 - s << endl; return 0; }
672eb25fbd75473ca0c6a1e66a41bd36ef6fc841
798ae73539d2125d4c57490c05db36bd1f792540
/OpenCLExtended/src/Wrapper/Context.h
88e2bce66fc20a423f6f32934222266a70629b40
[]
no_license
muellertobias/EmpyreanGlow
e904c8fe824ecc464d20719786804980011733df
4a91f1d1af1a8daf8b6d6abfbf2cfff014276bf9
refs/heads/master
2021-05-14T01:33:39.881718
2018-01-28T10:10:24
2018-01-28T10:10:24
116,568,603
0
0
null
null
null
null
UTF-8
C++
false
false
539
h
Context.h
#pragma once #include <CL\cl.hpp> #include <memory> namespace OpenCLExt { namespace Wrapper { class Context { public: Context(std::shared_ptr<cl::Context> context, cl::Device device); ~Context(); std::shared_ptr<cl::Context> getNative() { return _Context; } std::vector<cl_int> getProperties() { return _Properties; } cl::Device getDevice() { return _Device; } private: std::shared_ptr<cl::Context> _Context; std::vector<cl_int> _Properties; cl::Device _Device; }; } }
6191ae27dfeb491f4a23eca302410c73e2efcc2d
d3c1ae82c4fe2a6f15ab720a4f2ea1b88dbd19ef
/Evidyon/apps/shared/server-editor/swarmspawndescription.h
bf935c5f6290eaa9a11c307ad49ad4aa68f20780
[ "MIT" ]
permissive
karlgluck/evidyon-2.10
0f2b1950ee2412871b40e71fd6162efe2be4027d
632c863ecc95398dca2bbc84ba4eac9b8a83f01c
refs/heads/master
2020-05-18T09:24:40.855048
2014-12-02T17:55:14
2014-12-02T17:55:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,379
h
swarmspawndescription.h
#ifndef __SWARMSPAWNDESCRIPTION_H__ #define __SWARMSPAWNDESCRIPTION_H__ namespace Evidyon { // Always <= 32 because there are only 32 bits in the spawn location mask static const unsigned int MAX_SWARM_SPAWNS_PER_WORLD_REGION = 32; struct CompiledRegionSwarmSpawn { int ai_lifeform_type; // This is based on the average level of monsters in this region. It has // N paired bits (N <= 16) in the high and low WORDs set to 0. The random // treasure generation value is ANDed with this mask before checking to // see how many bits match. // By setting N higher, treasure is more more valuable on average. unsigned int treasure_randomizer_mask; // count from 0->activate period, then: // if spawn counter >= 0, decrement spawn counter by granularity // if spawn counter < 0 // spawn a monster // spawn counter++ // if spawn counter == 0, spawn counter = spawn_counter_reset_value unsigned int spawn_counter_activate_period; unsigned int spawn_counter_granularity; unsigned int spawn_counter_reset_value; // bit set to 1 if this swarm type can create an actor at // the corresponding location unsigned int spawn_location_mask; }; struct CompiledSwarmSpawnLocationInfo { int x, y; // location at which to spawn int level;// level of monster to spawn here }; extern const float SWARM_SPAWN_PERIOD; } #endif
2454ab392549dfa3259a91dc9df08cc86b71fc51
a5938b70a2db3763365e57f5adae334c4dd5953c
/network/netdetective_server/third_party/socket_module/socket/SocketHelper.cpp
d5747ee875fd60718d8fc30e5efd35b983a55f10
[]
no_license
jerryhanhuan/test-code-backup
7dea8a8eb4209dc241dae1864df6b1eb1a48c7bd
2ebf0b1cb6715f66ea4c0b3153d426652ce9235f
refs/heads/master
2021-01-22T22:57:25.097424
2014-09-17T02:31:47
2014-09-17T02:31:47
null
0
0
null
null
null
null
GB18030
C++
false
false
6,731
cpp
SocketHelper.cpp
#include "stdafx.h" #include "SocketHelper.h" #include <mstcpip.h> #ifndef _WIN32_WCE #pragma comment(lib, "ws2_32") #else #pragma comment(lib, "ws2") #endif /////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL IsIPAddress(LPCTSTR lpszAddress) { if(!lpszAddress) return FALSE; size_t len = lstrlen(lpszAddress) + 1; if(len > 15) return false; int iDotIndex = 0; int iDotCount = 0; for(size_t i = 0; i < len; ++i) { TCHAR c = lpszAddress[i]; if((c < '0' || c > '9') && c != '.' && c != '\0') return FALSE; else if(c == '.' || c == '\0') { size_t iSubLen = i - iDotIndex; if(iSubLen < 1 || iSubLen > 3) return FALSE; TCHAR szSub[4] = {0}; _tcsncpy(szSub, lpszAddress + iDotIndex, iSubLen); int iSub = _ttoi(szSub); if(iSub < 0 || iSub > 255) return FALSE; if(c == '.') { iDotIndex = i + 1; ++iDotCount; } } } return (iDotCount == 3 || iDotCount == 5); } BOOL GetIPAddress(LPCTSTR lpszHost, CStringA& strIP) { BOOL isOK = TRUE; if(IsIPAddress(lpszHost)) strIP = lpszHost; else { hostent* host = ::gethostbyname(CT2A(lpszHost)); if(!host) return FALSE; strIP = inet_ntoa(*(struct in_addr *)*host->h_addr_list); } return TRUE; } //获取扩展函数指针 PVOID GetExtensionFuncPtr(SOCKET sock, GUID guid) { DWORD dwBytes; PVOID pfn = NULL; //I/O控制命令winsock1版是ioctlsocket与winsock2版是WSAIoctl,传一个套接字进来即可 //通过WSAIoctl() (选项参数为SIO_GET_EXTENSION_FUNCTION_POINTER)动态获得函数的指针 ::WSAIoctl ( sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &pfn, sizeof(pfn), &dwBytes, NULL, NULL ); return pfn; } //AcceptEx函数 接受连接 //功能:1、接受新连接 2、新连接的本地地址和远程地址都会返回 3、接收到了远程主机发来的第一块数据 LPFN_ACCEPTEX Get_AcceptEx_FuncPtr(SOCKET sock) { GUID guid = WSAID_ACCEPTEX; //AcceptEx函数 return (LPFN_ACCEPTEX)GetExtensionFuncPtr(sock, guid); } LPFN_GETACCEPTEXSOCKADDRS Get_GetAcceptExSockaddrs_FuncPtr(SOCKET sock) { GUID guid = WSAID_GETACCEPTEXSOCKADDRS; //GetAcceptExSockAddrs return (LPFN_GETACCEPTEXSOCKADDRS)GetExtensionFuncPtr(sock, guid); } LPFN_CONNECTEX Get_ConnectEx_FuncPtr(SOCKET sock) { GUID guid = WSAID_CONNECTEX; //Connectex return (LPFN_CONNECTEX)GetExtensionFuncPtr(sock, guid); } LPFN_TRANSMITFILE Get_TransmitFile_FuncPtr(SOCKET sock) { GUID guid = WSAID_TRANSMITFILE; //TransmitFile return (LPFN_TRANSMITFILE)GetExtensionFuncPtr(sock, guid); } /////////////////////////////////////////////////////////////////////////////////////////////////////// //当 AcceptEx函数完成操作并且SO_UPDATE_ACCEPT_CONTEXT选项在被接受的socket中被设置时, socket相关的本地地址(local address )可以使用getsockname函数获 int SSO_UpdateAcceptContext(SOCKET soClient, SOCKET soBind) { return setsockopt(soClient, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (CHAR*)&soBind, sizeof(SOCKET)); } int SSO_UpdateConnectContext(SOCKET soClient, int iOption) { return setsockopt(soClient, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, (CHAR*)&iOption, sizeof(int)); } int SSO_NoDelay(SOCKET sock, BOOL bNoDelay) { return setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (CHAR*)&bNoDelay, sizeof(BOOL)); } int SSO_DontLinger(SOCKET sock, BOOL bDont) { return setsockopt(sock, SOL_SOCKET, SO_DONTLINGER, (CHAR*)&bDont, sizeof(BOOL)); } int SSO_Linger(SOCKET sock, USHORT l_onoff, USHORT l_linger) { linger ln = {l_onoff, l_linger}; //此选项指定函数close对面向连接的协议如何操作(如TCP)。 // 内核缺省close操作是立即返回,如果有数据残留在套接口缓冲区中则系统将试着将这些数据发送给对方。 return setsockopt(sock, SOL_SOCKET, SO_LINGER, (CHAR*)&ln, sizeof(linger)); } int SSO_KeepAlive(SOCKET sock, BOOL bKeepAlive) { return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (CHAR*)&bKeepAlive, sizeof(BOOL)); } int SSO_KeepAliveVals(SOCKET sock, u_long onoff, u_long time, u_long interval) { DWORD dwBytes; tcp_keepalive out; tcp_keepalive in = {onoff, time, interval}; return ::WSAIoctl( sock, SIO_KEEPALIVE_VALS, (LPVOID)&in, sizeof(in), (LPVOID)&out, sizeof(out), &dwBytes, NULL, NULL ); } int SSO_RecvBuffSize(SOCKET sock, int size) { return setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (CHAR*)&size, sizeof(int)); } int SSO_SendBuffSize(SOCKET sock, int size) { return setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (CHAR*)&size, sizeof(int)); } int SSO_ReuseAddress(SOCKET sock, BOOL bReuse) { return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (CHAR*)&bReuse, sizeof(BOOL)); } /////////////////////////////////////////////////////////////////////////////////////////////////////// int ManualCloseSocket(SOCKET sock, BOOL bGraceful, BOOL bReuseAddress) { if(!bGraceful) SSO_Linger(sock, 1, 0); if(bReuseAddress) SSO_ReuseAddress(sock, bReuseAddress); return closesocket(sock); } int PostAccept(LPFN_ACCEPTEX pfnAcceptEx, SOCKET soListen, SOCKET soClient, TBufferObj* pBufferObj) { int result = NO_ERROR; pBufferObj->operation = SO_ACCEPT; pBufferObj->client = soClient; if(!pfnAcceptEx ( soListen, soClient, pBufferObj->buff.buf, 0, sizeof(SOCKADDR_IN) + 16, sizeof(SOCKADDR_IN) + 16, NULL, &pBufferObj->ov ) ) { result = ::WSAGetLastError(); if(result == WSA_IO_PENDING) result = NO_ERROR; } return result; } int PostSend(TSocketObj* pSocketObj, TBufferObj* pBufferObj) { int result = NO_ERROR; pBufferObj->operation = SO_SEND; DWORD dwBytes; if(::WSASend( pSocketObj->socket, &pBufferObj->buff, 1, &dwBytes, 0, &pBufferObj->ov, NULL ) == SOCKET_ERROR) { result = ::WSAGetLastError(); if(result == WSA_IO_PENDING) result = NO_ERROR; } return result; } int PostReceive(TSocketObj* pSocketObj, TBufferObj* pBufferObj) { int result = NO_ERROR; pBufferObj->operation = SO_RECEIVE; DWORD dwBytes, dwFlag = 0; if(::WSARecv( pSocketObj->socket, &pBufferObj->buff, 1, &dwBytes, &dwFlag, &pBufferObj->ov, NULL ) == SOCKET_ERROR) { result = ::WSAGetLastError(); if(result == WSA_IO_PENDING) result = NO_ERROR; } return result; }
565e0d4489476fde40d59fb69f7c79818bf2dc11
6af1d76d5c1506a62e7be265d01e9aad10bacff1
/Minggu 8/wifisetup_and_mqtt/webserver_callback.ino
550ec217c3d765843901488e1985ffa0e682e699
[]
no_license
bontorhumala/KP-M2M-Tritronik-2020
0b681caf4b39fcafac26211b061e64adc497879b
cb6f218ff3558f663bf408ca33f5eec54f4553f5
refs/heads/master
2022-12-06T12:27:46.148788
2020-08-09T03:59:02
2020-08-09T03:59:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
280
ino
webserver_callback.ino
// Callback: send homepage void handle_OnConnect() { if (!server.authenticate(www_username, www_password)) { return server.requestAuthentication(); } server.send(200, "text/html", ptr); } void hande_OnNotFound() { server.send(404, "text/plain", "Not found"); }
70a7082c6a1bc6837bb39a3c51dee0359e29b397
18e9db71a0e207dbc7654135123bceaa7b3339e4
/7.代码练习/noip入门组/97求和2.cpp
a376a76868a0c2844675712a0d674286aeef264d
[]
no_license
TheIslland/learning-in-collegelife
358490cc74914b87d4d626a6485c2fe1ff06462f
1794e18addfd05e32cf8108895ac1585586394e1
refs/heads/master
2021-07-08T00:51:00.908370
2020-07-11T01:04:35
2020-07-11T01:04:35
144,252,958
2
0
null
null
null
null
UTF-8
C++
false
false
468
cpp
97求和2.cpp
/************************************************************************* > File Name: 97求和2.cpp > Author: TheIslland > Mail: voidland@163.com, 861436930@qq.com > Created Time: Fri Nov 1 20:37:48 2019 ************************************************************************/ #include<iostream> #include<algorithm> using namespace std; int main() { long long int n, ans; cin >> n; ans = n * (n + 1) / 2; cout << ans << endl; return 0; }
2a14c1fd4dd02af8d1f2bbc04e228fc808266e6c
8465159705a71cede7f2e9970904aeba83e4fc6c
/src_change_the_layout/com/powerlink/POWERLINK_MN.h
fb6ebdbc2e34023cb7fb54c4e07b3bc6269de5bc
[]
no_license
TuojianLYU/forte_IO_OPCUA_Integration
051591b61f902258e3d0d6608bf68e2302f67ac1
4a3aed7b89f8a7d5f9554ac5937cf0a93607a4c6
refs/heads/main
2023-08-20T16:17:58.147635
2021-10-27T05:34:43
2021-10-27T05:34:43
419,704,624
1
0
null
null
null
null
UTF-8
C++
false
false
2,270
h
POWERLINK_MN.h
/******************************************************************************* * Copyright (c) 2012 AIT * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Filip Andren - initial API and implementation and/or initial documentation *******************************************************************************/ #ifndef _POWERLINK_MN_H_ #define _POWERLINK_MN_H_ #include <funcbloc.h> class FORTE_POWERLINK_MN : public CFunctionBlock{ DECLARE_FIRMWARE_FB(FORTE_POWERLINK_MN) private: static const CStringDictionary::TStringId scm_anDataInputNames[]; static const CStringDictionary::TStringId scm_anDataInputTypeIds[]; CIEC_BOOL &QI(){ return *static_cast<CIEC_BOOL*>(getDI(0)); } ; CIEC_STRING &CDC_CFG(){ return *static_cast<CIEC_STRING*>(getDI(1)); } ; CIEC_STRING &APP_CFG(){ return *static_cast<CIEC_STRING*>(getDI(2)); } ; CIEC_STRING &DEV_NAME(){ return *static_cast<CIEC_STRING*>(getDI(3)); } ; static const CStringDictionary::TStringId scm_anDataOutputNames[]; static const CStringDictionary::TStringId scm_anDataOutputTypeIds[]; CIEC_BOOL &QO(){ return *static_cast<CIEC_BOOL*>(getDO(0)); } ; CIEC_STRING &STATUS(){ return *static_cast<CIEC_STRING*>(getDO(1)); } ; static const TEventID scm_nEventINITID = 0; static const TForteInt16 scm_anEIWithIndexes[]; static const TDataIOID scm_anEIWith[]; static const CStringDictionary::TStringId scm_anEventInputNames[]; static const TEventID scm_nEventINITOID = 0; static const TForteInt16 scm_anEOWithIndexes[]; static const TDataIOID scm_anEOWith[]; static const CStringDictionary::TStringId scm_anEventOutputNames[]; static const SFBInterfaceSpec scm_stFBInterfaceSpec; FORTE_FB_DATA_ARRAY(1, 4, 2, 0) ; void executeEvent(int pa_nEIID); void shutdownStack(); public: FUNCTION_BLOCK_CTOR(FORTE_POWERLINK_MN){ }; virtual ~FORTE_POWERLINK_MN(); }; #endif //close the ifdef sequence from the beginning of the file
05ba5f5dab466b43d691bab09f32985857780532
0ff8b11c7fd4acd870ef0005ddc93ed73879ecc7
/Graphics Project/building.cpp
f13a14a64d76a8883c8fa944f8aa95728d08e78c
[]
no_license
shahnawroz/grpahics
ba26c74cfecbbcf70749f060520c72b8bc2afbb3
5f13275ba1bfcb5482b0f4fc74127cf346c68b0e
refs/heads/main
2023-04-13T11:45:50.799931
2021-05-01T05:14:10
2021-05-01T05:14:10
363,327,361
0
0
null
null
null
null
UTF-8
C++
false
false
10,059
cpp
building.cpp
#include <iostream> #include <stdlib.h> #include <math.h> #include <GL/gl.h> #include <GL/glut.h> float _angle = 0.0; float _angle1 = 0.0; void balcony() { ///left balcony start glPushMatrix(); //door glPushMatrix(); glColor3ub(140,20,240); glScalef(0.3,1.1,0.01); glTranslatef(-0.34,-0.037,30); glutSolidCube(0.2); glPopMatrix(); //window glPushMatrix(); glColor3ub(240,240,240); glScalef(0.54,0.5,0.01); glTranslatef(-0.4,0.035,30); glutSolidCube(0.2); glPopMatrix(); //floor glPushMatrix(); glColor3ub(0,250,0); glScalef(1.2,0.06,0.3); glTranslatef(-0.15,-2.6,1.1); glutSolidCube(0.2); glPopMatrix(); //right wall glPushMatrix(); glColor3ub(120,100,120); glScalef(0.05,0.5,0.25); glTranslatef(-1.3,-0.2,1.3); glutSolidCube(0.2); glPopMatrix(); //left wall glPushMatrix(); glColor3ub(120,100,120); glScalef(0.05,0.5,0.25); glTranslatef(-5.9,-0.2,1.3); glutSolidCube(0.2); glPopMatrix(); //front wall glPushMatrix(); glColor3ub(20,20,240); glScalef(1.2,0.5,0.05); glTranslatef(-0.15,-0.2,7.1); glutSolidCube(0.2); glPopMatrix(); glPopMatrix(); ///left balcony end ///right balcony start glPushMatrix(); glTranslatef(0.36,0,0); //door glPushMatrix(); glColor3ub(140,20,240); glScalef(0.3,1.1,0.01); glTranslatef(-0.86,-0.037,30); glutSolidCube(0.2); glPopMatrix(); //window glPushMatrix(); glColor3ub(240,240,240); glScalef(0.54,0.5,0.01); glTranslatef(-0.27,0.035,30); glutSolidCube(0.2); glPopMatrix(); //floor glPushMatrix(); glColor3ub(0,250,0); glScalef(1.2,0.06,0.3); glTranslatef(-0.15,-2.6,1.1); glutSolidCube(0.2); glPopMatrix(); //right wall glPushMatrix(); glColor3ub(120,100,120); glScalef(0.05,0.5,0.25); glTranslatef(-1.3,-0.2,1.3); glutSolidCube(0.2); glPopMatrix(); //left wall glPushMatrix(); glColor3ub(120,100,120); glScalef(0.05,0.5,0.25); glTranslatef(-5.9,-0.2,1.3); glutSolidCube(0.2); glPopMatrix(); //front wall glPushMatrix(); glColor3ub(20,20,240); glScalef(1.2,0.5,0.05); glTranslatef(-0.15,-0.2,7.1); glutSolidCube(0.2); glPopMatrix(); glPopMatrix(); ///right balcony end } void left_window() { ///left window 1 glPushMatrix(); glColor3ub(240,240,240); glScalef(0.01,0.5,0.5); glTranslatef(-30.1,0,0.3); glutSolidCube(0.2); glPopMatrix(); ///left window 2 glPushMatrix(); glColor3ub(240,240,240); glScalef(0.01,0.5,0.5); glTranslatef(-30.1,0,-0.3); glutSolidCube(0.2); glPopMatrix(); } void right_window() { ///right window 1 glPushMatrix(); glColor3ub(240,240,240); glScalef(0.01,0.5,0.5); glTranslatef(30.1,0,0.3); glutSolidCube(0.2); glPopMatrix(); ///right window 2 glPushMatrix(); glColor3ub(240,240,240); glScalef(0.01,0.5,0.5); glTranslatef(30.1,0,-0.3); glutSolidCube(0.2); glPopMatrix(); } void back_window() { ///back window glPushMatrix(); glColor3ub(240,240,240); glScalef(0.2,0.8,0.01); glTranslatef(0,0,-30.1); glutSolidCube(0.2); glPopMatrix(); } void floor_body() { ///body glPushMatrix(); glColor3ub(255,220,120); glScalef(1,0.5,1); glutSolidCube(0.6); glPopMatrix(); ///floor glPushMatrix(); glColor3ub(255,0,0); glScalef(1.04,0.02,1); glTranslatef(0,-7.8,0); glutSolidCube(0.6); glPopMatrix(); } void building(){ /// start of building glPushMatrix(); //glScalef(3,3,3); //glRotatef(_angle1, 0.0, 1.0, 0.0); glTranslatef(0,-0.8,0); //glRotatef(90, 0.0, 1.0, 0.0); ///ground floor glPushMatrix(); //body glPushMatrix(); glColor3ub(255,220,120); glScalef(1,0.5,1); glutSolidCube(0.6); glPopMatrix(); //floor glPushMatrix(); glColor3ub(255,0,0); glScalef(1.02,0.03,1.02); glTranslatef(0,-5.3,0); glutSolidCube(0.6); glPopMatrix(); ///main gate //ground part glPushMatrix(); glColor3ub(139, 0, 0); glScalef(2.5,0.1,0.6); glTranslatef(0,-1.6,0.6); glutSolidCube(0.2); glPopMatrix(); //gate glPushMatrix(); glColor3ub(140,20,240); glScalef(2.3,1.1,0.01); glTranslatef(0,-0.035,30); glutSolidCube(0.2); glPopMatrix(); //sub gate glPushMatrix(); glColor3ub(139, 0, 139); glScalef(0.4,0.9,0.01); glTranslatef(0.45,-0.065,30); glutSolidCube(0.2); glPopMatrix(); //left pillar glPushMatrix(); glColor3ub(139, 0, 0); glScalef(0.15,1.1,0.21); glTranslatef(-1.57,-0.035,1.54); glutSolidCube(0.2); glPopMatrix(); //middle pillar glPushMatrix(); glColor3ub(139, 0, 0); glScalef(0.15,1.1,0.21); glTranslatef(0.7,-0.035,1.54); glutSolidCube(0.2); glPopMatrix(); //right pillar glPushMatrix(); glColor3ub(139, 0, 0); glScalef(0.15,1.1,0.21); glTranslatef(1.57,-0.035,1.54); glutSolidCube(0.2); glPopMatrix(); //pillar roof glPushMatrix(); glColor3ub(139, 0, 0); glScalef(2.5,0.2,0.21); glTranslatef(0,0.45,1.54); glutSolidCube(0.2); glPopMatrix(); glPopMatrix(); ///1st floor glPushMatrix(); glTranslatef(0,0.31,0); back_window(); right_window(); floor_body(); balcony(); left_window(); glPopMatrix(); ///2nd floor glPushMatrix(); glTranslatef(0,0.62,0); back_window(); right_window(); floor_body(); balcony(); left_window(); glPopMatrix(); ///3rd floor glPushMatrix(); glTranslatef(0,0.93,0); back_window(); right_window(); floor_body(); balcony(); left_window(); glPopMatrix(); ///4th floor glPushMatrix(); glTranslatef(0,1.24,0); back_window(); right_window(); floor_body(); balcony(); left_window(); glPopMatrix(); ///roof glPushMatrix(); glColor3ub(255,0,0); glScalef(1.05,0.02,1.2); glTranslatef(0,69.8,0.025); glutSolidCube(0.6); glPopMatrix(); ///roof back wall glPushMatrix(); glColor3ub(20,20,240); glScalef(3,0.5,0.05); glTranslatef(0,2.905,-6.2); glutSolidCube(0.2); glPopMatrix(); ///roof entrance glPushMatrix(); //body glPushMatrix(); glColor3ub(0,220,120); glScalef(1,1.2,1.05); glTranslatef(0,1.27,-0.15); glutSolidCube(0.2); glPopMatrix(); //roof glPushMatrix(); glColor3ub(255,0,0); glScalef(1.1,0.06,1.2); glTranslatef(0,27.5,-0.13); glutSolidCube(0.2); glPopMatrix(); //door glPushMatrix(); glColor3ub(140,20,240); glScalef(0.4,1.0,0.01); glTranslatef(0,1.51,-5.2); glutSolidCube(0.2); glPopMatrix(); glPopMatrix(); /// water tank 1 glPushMatrix(); //body glPushMatrix(); glColor3ub(0, 255, 255); glScalef(0.5,1.7,0.5); glTranslatef(0.4,0.876,-0.15); glRotatef(90,1,0,0); glutSolidTorus(0.05,0.05,25,25); glPopMatrix(); //cap glPushMatrix(); glColor3ub(255, 0, 0); glScalef(0.2,0.1,0.2); glTranslatef(1.01,15.76,-0.36); glRotatef(90,1,0,0); glutSolidTorus(0.05,0.05,25,25); glPopMatrix(); glPopMatrix(); /// water tank 2 glPushMatrix(); //body glPushMatrix(); glColor3ub(0, 255, 255); glScalef(0.5,1.7,0.5); glTranslatef(0.4,0.876,0.08); glRotatef(90,1,0,0); glutSolidTorus(0.05,0.05,25,25); glPopMatrix(); //cap glPushMatrix(); glColor3ub(255, 0, 0); glScalef(0.2,0.1,0.2); glTranslatef(1.01,15.76,0.22); glRotatef(90,1,0,0); glutSolidTorus(0.05,0.05,25,25); glPopMatrix(); glPopMatrix(); ///roof left wall glPushMatrix(); glColor3ub(120,100,120); glScalef(0.05,0.5,3.31); glTranslatef(-5.89,2.905,0.009); glutSolidCube(0.2); glPopMatrix(); ///roof right wall glPushMatrix(); glColor3ub(120,100,120); glScalef(0.05,0.5,3.31); glTranslatef(5.89,2.905,0.009); glutSolidCube(0.2); glPopMatrix(); ///roof front wall glPushMatrix(); glColor3ub(20,20,240); glScalef(3,0.5,0.05); glTranslatef(0,2.905,7.3); glutSolidCube(0.2); glPopMatrix(); glPopMatrix(); /// end of building } void display () { /* clear window */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* future matrix manipulations should affect the modelview matrix */ glMatrixMode(GL_MODELVIEW); /* draw scene */ glPushMatrix(); building(); glPopMatrix(); /* flush drawing routines to the window */ //glFlush(); glutSwapBuffers(); } void reshape ( int width, int height ) { /* define the viewport transformation */ glViewport(0,0,width,height); } void myInit() { GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat mat_shininess[] = { 100.0 }; GLfloat light_position[] = { .20, 0.50, 1.0, 0.0 }; GLfloat white_light[] = { 0.20, 0.60, 1.0, 0.0 }; glClearColor (0.60, 0.50, 0.0, 1.0); glShadeModel (GL_SMOOTH); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); /* set up depth-buffering */ glEnable(GL_DEPTH_TEST); /* turn on default lighting */ glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); /* define the projection transformation */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(40,1,4,20); /* define the viewing transformation */ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(10.0,5.0,0.0,0.0,0.0,0.0,0.0,2.0,0.0); //gluLookAt(10,10,10,0.0,0.0,0.0,0.0,2.0,0.0); } void update(int value) { _angle += 2.0f; if (_angle > 360) { _angle -= 360; } _angle1 += 0.5f; if (_angle1 > 360) { _angle1 -= 360; } glutPostRedisplay(); //Tell GLUT that the display has changed //Tell GLUT to call update again in 25 milliseconds glutTimerFunc(25, update, 0); } int main ( int argc, char * argv[] ) { /* initialize GLUT, using any commandline parameters passed to the program */ glutInit(&argc,argv); /* setup the size, position, and display mode for new windows */ glutInitWindowSize(1000,700); glutInitWindowPosition(0,0); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); /* create and set up a window */ glutCreateWindow("building"); glutDisplayFunc(display); glutReshapeFunc(reshape); // myInit(); glutTimerFunc(25,update,0); /* tell GLUT to wait for events */ glutMainLoop(); }
0a81fa6b13f81a895de2b0f7571eb19005b16a82
ef7ad96103876b24bbb45be8dfba7e80771c76e7
/ui-qt/Pretreatment/PretreatMentListCollect/PretreatmentSummaryDialog.cpp
fd2b6be63469ac6d7155a32c970118867a765039
[ "MIT" ]
permissive
TinySlik/FPGA-Industrial-Smart-Camera
ecb6274f4ef16cf9174cd73812486644f821152a
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
refs/heads/master
2021-06-25T11:09:21.212466
2017-09-01T07:23:58
2017-09-01T07:23:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,796
cpp
PretreatmentSummaryDialog.cpp
#include "PretreatmentSummaryDialog.h" #include "ui_PretreatmentSummaryDialog.h" #include <QMessageBox> #include <stdio.h> #include "AcceCommon.h" PretreatmentSummaryDialog::PretreatmentSummaryDialog(QWidget *parent) : QDialog(parent), ui(new Ui::PretreatmentSummaryDialog) { ui->setupUi(this); IniListData(); } PretreatmentSummaryDialog::~PretreatmentSummaryDialog() { delete ui; } void PretreatmentSummaryDialog::SetLocation(int x, int y) { this->move(x,y); } void PretreatmentSummaryDialog::on_btnOk_clicked() { int row = ui->listWidget->currentRow(); if(row >=0) { m_str_name = ui->listWidget->item(row)->text(); m_index = m_vt_index[row]; /*CGetImageThread *imageThread = CGetImageThread::Instance(); if(imageThread->m_iSensorType == SENSORTYPEBW) { if(m_index == ACCE_COLOR_EXTRACT_MODLE_ID)//20 { QMessageBox::about(NULL,tr("提示"),tr("此功能为彩色相机功能")); return; } }*/ }else { QMessageBox::about(NULL,tr("Information"),tr("Please Select row")); return ; } QDialog::accept(); } void PretreatmentSummaryDialog::IniListData() { ui->listWidget->setStyleSheet("QListWidget{background:rgba(255,255,255,255);color:#19649F;border:0px solid gray;padding:0px -2px 5px -2px;}" "QListWidget::item{width:321;height:40px;border:1px solid white;padding-left:0px;}" "QListWidget::item:!selected{background:#b4b4b4;}" "QListWidget::item:selected:active{background:#b2d1ff;color:#19649F;border-width:-1;}" "QListWidget::item:selected{background:#b2d1ff;color:#19649F;}"); m_vt_strName.append(tr("CPT模块"));//图像预处理转换 m_vt_strName.append(tr("图像预处理转换"));//图像预处理转换 m_vt_strName.append(tr("二值化处理"));//二值化处理 m_vt_strName.append(tr("轮廓匹配"));//轮廓匹配 m_vt_strName.append(tr("边沿提取"));//边沿提取 m_vt_strName.append(tr("连通域"));//连通域 m_vt_strName.append(tr("色彩提取"));//色彩提取 m_vt_strName.append(tr("区域筛选"));//区域筛选 m_vt_strName.append(tr("直方图统计")); //直方图统计 m_vt_index.append(ACCE_CPT_MODEL_ID); m_vt_index.append(ACCE_PRE_MODEL_ID); m_vt_index.append(ACCE_BW_PROC_MODEL_ID); m_vt_index.append(ACCE_SKE_MATCH_MODLE_ID); m_vt_index.append(ACCE_EDGE_EXTRACT_MODLE_ID); m_vt_index.append(ACCE_CONNECT_REGION_MODLE_ID); m_vt_index.append(ACCE_COLOR_EXTRACT_MODLE_ID); m_vt_index.append(ACCE_AREA_SELECT_MODEL_ID); m_vt_index.append(ACCE_HIST_MODEL_ID); ui->listWidget->addItem(m_vt_strName[0]);//cpt ui->listWidget->addItem(m_vt_strName[1]);//图像预处理转换 ui->listWidget->addItem(m_vt_strName[2]);//二值化处理 ui->listWidget->addItem(m_vt_strName[3]);//轮廓匹配 ui->listWidget->addItem(m_vt_strName[4]);//边沿提取 ui->listWidget->addItem(m_vt_strName[5]);//连通域 ui->listWidget->addItem(m_vt_strName[6]);//色彩提取 ui->listWidget->addItem(m_vt_strName[7]);//区域筛选 ui->listWidget->addItem(m_vt_strName[8]);//直方图统计 } void PretreatmentSummaryDialog::on_btnQuit_clicked() { QDialog::reject(); } int PretreatmentSummaryDialog::GetNameIndexById(int id) { int count = m_vt_index.count(); int ret = -1; for(int i = 0; i<count;i++) { if(m_vt_index[i] == id) { ret = i; break; } } return ret; } QString PretreatmentSummaryDialog::GetStrNameByArrIndex(int index) { return m_vt_strName[index]; }
cc1048d9dddc90b7b063a705120b6365c7cf9ab1
0837ceea6758a53b5e15da8d094a082fcda78bb2
/qtjs/oboy_headers/oboy_headers.h
48218e124b0c6dc5bf4acd3afeb98cf772dafc95
[]
no_license
nikhilm/confkdein11
2d6454906db1b8cdb5785a019d3602e76009916d
9d01e94c67bd4f405a0a145457a5176f26b00830
refs/heads/master
2021-01-23T13:50:18.311718
2011-03-12T04:34:32
2011-03-12T04:34:32
1,305,781
0
1
null
null
null
null
UTF-8
C++
false
false
500
h
oboy_headers.h
#ifndef OBOY #define OBOY #include <QtScript> #include <QMetaType> #include <QHash> class QHttpServer; class QHttpRequest; class QHttpResponse; class Oboy : public QObject { Q_OBJECT public: Oboy(QScriptValue callback); ~Oboy(); Q_INVOKABLE void listen(const QString &host, quint16 port); Q_INVOKABLE void listen(quint16 port); private slots: void handle(QHttpRequest *req, QHttpResponse *res); private: QScriptValue m_callback; QHttpServer *m_server; }; #endif
fecc5e0a0578d7a454c0d6c4d022b766778ed865
367e8612cb116ac46d08856127a05d78d1fc03f1
/Engine/OGF-Core/Core/Graphics/Text/Font.cpp
549ac8d2a51334c594cf59ebcb45500555ff6a80
[ "MIT" ]
permissive
simon-bourque/OpenGameFramework
a1c848ec9b203d23831a07dbca978b93495fb41d
e0fed3895000a5ae244fc1ef696f4256af29865b
refs/heads/master
2023-02-08T17:44:21.387079
2020-12-22T20:52:48
2020-12-22T20:52:48
83,928,624
5
0
MIT
2020-12-22T20:52:50
2017-03-04T22:24:01
C++
UTF-8
C++
false
false
692
cpp
Font.cpp
#include "Font.h" Font::Font(TextureRef bitmap, const Glyph& invalidCharacter) : m_bitmap(bitmap), m_invalidCharacter(invalidCharacter) {} Font::Font(TextureRef bitmap, const Glyph& invalidCharacter, std::pair<char, Glyph>* characterMap, uint32 characterMapSize) : m_bitmap(bitmap), m_invalidCharacter(invalidCharacter) { for (uint32 i = 0; i < characterMapSize; i++) { m_glyphMap[characterMap[i].first] = characterMap[i].second; } } void Font::addCharacterMapping(char c, const Glyph& glyph) { m_glyphMap[c] = glyph; } const Glyph& Font::getCharacterMapping(char c) const { auto iter = m_glyphMap.find(c); return (iter == m_glyphMap.end()) ? m_invalidCharacter : iter->second; }
87db2222df692c03ca571e6cbb58ca3051d1bfe9
f5ad9981d50a0a70257fc90b538308dea5f80b48
/Cluster_cRMSD/Centroid.cpp
476e776c40a92d9ac4e501c781904905ca02d5bc
[]
no_license
dimitriskon95/Molecular-Conformation
02c5166c45dec1acb7f73c2325f0395bdc6091b6
7b731be4e09230cb424197504751a5aec75872a6
refs/heads/master
2021-05-06T06:38:14.712331
2017-12-11T15:22:06
2017-12-11T15:22:06
113,873,618
0
0
null
null
null
null
UTF-8
C++
false
false
747
cpp
Centroid.cpp
#include <fstream> #include <iostream> #include <math.h> #include <string.h> #include "Centroid.h" #include "Node.h" using namespace std; template <class T> Centroid<T>::Centroid() { // cout << "A Centroid was constructed." << endl; } template <class T> Centroid<T>::~Centroid() { //cout << "A Centroid was destructed." << endl; } template <class T> void Centroid<T>::set_CNode(Node<T> *node) { center = node; center->set_CentroidValue(); } template <class T> Node<T>* Centroid<T>::get_center() { return center; } template <class T> void Centroid<T>::printCentroid() { center->printNode(); } template class Centroid<int>; template class Centroid<char>; template class Centroid<double>;
167bb08570529fb4a8905072ad02ae2c4c1cca8c
8ea94027697b625b738f72bdb6a84ec84beacf34
/common/cpp/src/google_smart_card_common/logging/hex_dumping_unittest.cc
c819e1930edad2269244bafa8a251c84c5d05341
[ "LGPL-2.1-only", "LGPL-2.0-or-later", "Apache-2.0" ]
permissive
isabella232/chromeos_smart_card_connector
db16b13add16220eb33c3a519d7d7ec00e4d36af
0749d7208a8b9ace2236cf760dddb78307edae2b
refs/heads/master
2023-03-20T04:17:43.883467
2020-12-15T14:55:23
2020-12-15T14:55:23
322,266,506
0
0
Apache-2.0
2021-02-23T22:37:17
2020-12-17T10:57:18
null
UTF-8
C++
false
false
3,923
cc
hex_dumping_unittest.cc
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdint.h> #include <string> #include <gtest/gtest.h> #include <google_smart_card_common/logging/hex_dumping.h> namespace google_smart_card { TEST(LoggingHexDumpingTest, HexDumpByte) { EXPECT_EQ("0x00", HexDumpByte(static_cast<int8_t>(0))); EXPECT_EQ("0x00", HexDumpByte(static_cast<uint8_t>(0))); EXPECT_EQ("0x01", HexDumpByte(static_cast<int8_t>(1))); EXPECT_EQ("0x01", HexDumpByte(static_cast<uint8_t>(1))); EXPECT_EQ("0x64", HexDumpByte(static_cast<int8_t>(100))); EXPECT_EQ("0x64", HexDumpByte(static_cast<uint8_t>(100))); EXPECT_EQ("0xFF", HexDumpByte(static_cast<int8_t>(-1))); EXPECT_EQ("0xFF", HexDumpByte(static_cast<uint8_t>(255))); } TEST(LoggingHexDumpingTest, HexDumpQuadlet) { EXPECT_EQ("0x00000000", HexDumpQuadlet(static_cast<int32_t>(0))); EXPECT_EQ("0x00000000", HexDumpQuadlet(static_cast<uint32_t>(0))); EXPECT_EQ("0xFFFFFFFF", HexDumpQuadlet(static_cast<int32_t>(-1))); EXPECT_EQ("0xFFFFFFFF", HexDumpQuadlet(static_cast<uint32_t>(-1))); } TEST(LoggingHexDumpingTest, HexDumpOctlet) { EXPECT_EQ("0x0000000000000000", HexDumpOctlet(static_cast<int64_t>(0))); EXPECT_EQ("0x0000000000000000", HexDumpOctlet(static_cast<uint64_t>(0))); EXPECT_EQ("0xFFFFFFFFFFFFFFFF", HexDumpOctlet(static_cast<int64_t>(-1))); EXPECT_EQ("0xFFFFFFFFFFFFFFFF", HexDumpOctlet(static_cast<uint64_t>(-1))); } TEST(LoggingHexDumpingTest, HexDumpInteger) { EXPECT_EQ("0x00", HexDumpInteger(static_cast<int8_t>(0))); EXPECT_EQ("0x00", HexDumpInteger(static_cast<uint8_t>(0))); EXPECT_EQ("0x00000000", HexDumpInteger(static_cast<int32_t>(0))); EXPECT_EQ("0x00000000", HexDumpInteger(static_cast<uint32_t>(0))); EXPECT_EQ("0x0000000000000000", HexDumpInteger(static_cast<int64_t>(0))); EXPECT_EQ("0x0000000000000000", HexDumpInteger(static_cast<uint64_t>(0))); } TEST(LoggingHexDumpingTest, HexDumpUnknownSizeInteger) { EXPECT_EQ("0x00", HexDumpUnknownSizeInteger(static_cast<int64_t>(0))); EXPECT_EQ("0x00", HexDumpUnknownSizeInteger(static_cast<uint64_t>(0))); EXPECT_EQ("0xFF", HexDumpUnknownSizeInteger(static_cast<int64_t>(255))); EXPECT_EQ("0xFF", HexDumpUnknownSizeInteger(static_cast<uint64_t>(255))); EXPECT_EQ("0x00000100", HexDumpUnknownSizeInteger(static_cast<int64_t>(256))); EXPECT_EQ("0x00000100", HexDumpUnknownSizeInteger(static_cast<uint64_t>(256))); EXPECT_EQ("0xFFFFFFFF", HexDumpUnknownSizeInteger(static_cast<int64_t>((1LL << 32) - 1))); EXPECT_EQ(HexDumpUnknownSizeInteger(static_cast<uint64_t>((1LL << 32) - 1)), "0xFFFFFFFF"); EXPECT_EQ("0x0000000100000000", HexDumpUnknownSizeInteger(static_cast<int64_t>(1LL << 32))); EXPECT_EQ("0x0000000100000000", HexDumpUnknownSizeInteger(static_cast<uint64_t>(1LL << 32))); EXPECT_EQ("0x7FFFFFFFFFFFFFFF", HexDumpUnknownSizeInteger(std::numeric_limits<int64_t>::max())); EXPECT_EQ("0xFFFFFFFFFFFFFFFF", HexDumpUnknownSizeInteger(static_cast<uint64_t>(-1))); EXPECT_EQ("0xFF", HexDumpUnknownSizeInteger(static_cast<int64_t>(-1))); EXPECT_EQ("0xFFFFFF00", HexDumpUnknownSizeInteger(static_cast<int64_t>(-256))); EXPECT_EQ("0x8000000000000000", HexDumpUnknownSizeInteger(std::numeric_limits<int64_t>::min())); } } // namespace google_smart_card
e3b0e3976f3cd0c17881215595e95ebb21674177
a799a6350a3a3398cd4d301e0252f32b21ebc0d5
/Utility/searchAction.h
bab8ba64b7ff2accad94b8b7e67e3aff38921ce7
[]
no_license
winstic/AntennaLDO
e4a50f579b9c98b3d86735c26df87482c90dad0c
21b9d8f5c0292fa83b5a5977d79d1f57176548b8
refs/heads/master
2021-01-24T08:28:39.150166
2017-02-21T13:34:17
2017-02-21T13:34:17
69,466,466
2
0
null
null
null
null
UTF-8
C++
false
false
327
h
searchAction.h
#ifndef SEARCHACTION_H #define SEARCHACTION_H #include <QtWidgets> class searchAction :public QWidgetAction { public: searchAction(QWidget *parent = 0); ~searchAction(){} //QWidget * createWidget(QWidget *parent); QString getEditValue() const; private: QLineEdit *searchEdit; private slots: }; #endif
71c1ba9ed887f9a194ca88848bb80b1506d894bd
3a7318be247e62541140b6fec14a8d06f1c94552
/Q1712/1712.cpp
f7f02d8479ed98091b5a9229fee1bfedc1ce61da
[]
no_license
JunSuHeo/Algorithm
ee3d2e105dd2e4bcc6e548f98a04c656cb95ef8d
5e152c7eada30b2c0328ffa9a74f0ab8674b9d6a
refs/heads/master
2021-08-06T16:52:05.388936
2021-06-22T01:32:47
2021-06-22T01:32:47
148,972,849
0
1
null
2021-06-06T08:10:47
2018-09-16T07:19:14
C++
UHC
C++
false
false
1,831
cpp
1712.cpp
//백준 1712번 /* 문제 월드전자는 노트북을 제조하고 판매하는 회사이다.노트북 판매 대수에 상관없이 매년 임대료, 재산세, 보험료, 급여 등 A만원의 고정 비용이 들며, 한 대의 노트북을 생산하는 데에는 재료비와 인건비 등 총 B만원의 가변 비용이 든다고 한다. 예를 들어 A = 1, 000, B = 70이라고 하자.이 경우 노트북을 한 대 생산하는 데는 총 1, 070만원이 들며, 열 대 생산하는 데는 총 1, 700만원이 든다. 노트북 가격이 C만원으로 책정되었다고 한다.일반적으로 생산 대수를 늘려 가다 보면 어느 순간 총 수입(판매비용)이 총 비용(= 고정비용 + 가변비용)보다 많아지게 된다.최초로 총 수입이 총 비용보다 많아져 이익이 발생하는 지점을 손익분기점(BREAK - EVEN POINT)이라고 한다. A, B, C가 주어졌을 때, 손익분기점을 구하는 프로그램을 작성하시오. 입력 첫째 줄에 A, B, C가 빈 칸을 사이에 두고 순서대로 주어진다.A, B, C는 21억 이하의 자연수이다. 출력 첫 번째 줄에 손익분기점 즉 최초로 이익이 발생하는 판매량을 출력한다.손익분기점이 존재하지 않으면 - 1을 출력한다. */ #include <iostream> int main() { unsigned int a, b, c; //a : 고정비용 b : 노트북 재료비,인건비 c : 노트북 판매비 unsigned int tmp; std::cin >> a >> b >> c; if (b >= c) { //재료비와 인건비가 판매비보다 더 크거나 같을때는 손익분기점 발생하지 않음 std::cout << "-1"; } else { //노트북 판매비와 재료비,인건비를 뺀 값에서 고정비용을 나누고 1을 더해주는것이 손익분기점 발생시점 tmp = a / (c - b); std::cout << tmp + 1; } return 0; }
ca1b0172c81e92f6303ab8f2039c0bab01afa7d5
a871da148c720bc4d0962900712dba2df432243f
/Week_02/剑指 Offer 40. 最小的k个数--sort.cpp
74f615eb563c3820f111a68db5d8c4bd55b42919
[]
no_license
stephenhe/algorithm016
452687da68055598a188a7c869da455cf15fbfdc
a1de418fec29b3704a82d1aa749c87454ebce203
refs/heads/master
2023-01-27T20:47:15.452813
2020-12-08T13:41:45
2020-12-08T13:41:45
293,403,372
0
0
null
2020-09-07T02:32:38
2020-09-07T02:32:37
null
UTF-8
C++
false
false
381
cpp
剑指 Offer 40. 最小的k个数--sort.cpp
/* * @lc app=leetcode.cn id=283 lang=cpp * * [283] 移动零 */ // @lc code=start class Solution { public: vector<int> getLeastNumbers(vector<int>& arr, int k) { vector<int> ret; sort(arr.begin(), arr.end()); for (int i = 0; i < k && i < arr.size(); i++) { ret.push_back(arr[i]); } return ret; } }; // @lc code=end
a17d5b341c69e2136cac67dfe3559be4be2c67a3
78ff5fe20fb23039ce11fa4f0b5ea66beafdb218
/old/BufferChainList/Control.cpp
159c3d099d127d75612bec1fc58f8094fad06fe4
[]
no_license
blackgreymon/Learn-CPP
704d6c22c9214a4a5aa73cfee32945d640a41bd4
13e281f87b77d74b10e3e485c825d18b97d5ae4b
refs/heads/master
2020-12-25T03:30:42.372822
2015-06-23T01:33:38
2015-06-23T01:33:38
null
0
0
null
null
null
null
GB18030
C++
false
false
2,409
cpp
Control.cpp
#include "Control.h" Control::Control() { map_head = NULL; pro_id = 0; pro_offset = 0; pro_data = NULL; } void Control::ReceiveDataBag(DataBag data) {//接收数据包并将数据包信息记录下来 pro_id = data.get_id(); pro_offset = data.get_offset(); pro_data = data.get_data(); } void Control::PreHandle() {//预处理数据包,将数据包下发给节目对象 if (NULL == map_head) {//判断映射表是否为空,如果为空则创建新的映射节点 MapNode *temp; temp->pro_id = pro_id; //给映射节点申请新的节目对象 temp->pro_addr = new Program(pro_id); temp->buffer_head = NULL; temp->next = NULL; temp->buffer_head = temp->pro_addr->get_buffer_list(); map_head = map_tail =temp; //调用节目对象缓存接口接收数据 map_head->pro_addr->ReceiveData(pro_offset, pro_data); } else {//映射表不为空时判断是否已经有该节目的节点 int flag = 0; MapNode *temp = map_head; while (NULL != temp) { if (temp->pro_id == pro_id) {//查找节点,找到则调用接口接受数据 flag = 1; temp->pro_addr->ReceiveData(pro_offset, pro_data); break; } else { temp = temp->next; } } if (!flag) {//没有找到节目记录则创建新的映射节点 temp = new MapNode; temp->next = NULL; temp->pro_id = pro_id; temp->pro_addr = new Program(pro_id); temp->buffer_head = NULL; map_tail->next = temp; map_tail = temp; temp->buffer_head = temp->pro_addr->get_buffer_list(); map_tail->pro_addr->ReceiveData(pro_offset, pro_data); } } } void Control::EndHandle(int id) {//当一个节目接收完毕时处理结尾数据 //传入参数为节目id //从所有缓存区中取出剩余数据并释放缓存和节目空间 MapNode* temp = map_head; MapNode* t = temp->next; //在映射表中找节目节点 if (map_head->pro_id == id) {//头节点为所找节点时 //调用结束写入接口,将缓存区剩余数据写入文件 map_head->pro_addr->EndToWrite(); //释放结束节点的空间 delete map_head; map_head = t; } else {//头节点不是所找节点时 while (NULL != t) { if (t->pro_id == id) { temp->next = t->next; //调用结束写入接口,将缓存区剩余数据写入文件 t->pro_addr->EndToWrite(); //释放结束节点的空间 delete t; } else { t = t->next; } } } }
04bda772e0be9f0d1f4d65afcdd538813576aded
b72ed1c5b7e2aa9d71caa5c4f58e92f13546581c
/GeoProgram/ui/logger.h
7d28eb1e371f5467a0502f42fa523810687b6d1a
[]
no_license
n0rthern-light/GeoProgram
d4a167ddd191e62e813cdc4b0222d8181b5b2d15
2015db1d1a5eb78ae253ddc5eeab5dcf2a6e14f2
refs/heads/master
2022-11-02T06:46:51.588602
2020-06-10T10:24:16
2020-06-10T10:24:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
376
h
logger.h
#ifndef _LOGGER_H_ #define _LOGGER_H_ #include <string> #include <vector> class logger { std::vector<std::string> logs; public: static logger* get() { static logger _logger; return &_logger; } logger() { this->logs = std::vector<std::string>(); } std::vector<std::string>* get_logs(); void clear_logs(); void add_log(const std::string& log_line); }; #endif
a300d0393a7f45c99341a5c05214cd1fc4005ec3
c199654f7c04fb0e62ba8bb16ed002b7260ffe52
/src/Log/LogUtils.cpp
68e658967a1feb1cee4f8f8ef1d2afa80891724c
[]
no_license
qiniu/cpp-sdk
d19a9eaf113140a6ab853d2f48410c4798910cd7
eb16382ac1b67a7239b66db6b9c8ac2f8a7de21d
refs/heads/develop
2023-06-12T09:13:25.781237
2014-07-09T13:42:07
2014-07-09T13:42:07
16,835,472
2
2
null
2014-07-09T13:42:07
2014-02-14T11:31:04
C
UTF-8
C++
false
false
2,884
cpp
LogUtils.cpp
/******************************************************************************* * @file LogUtils.cpp 2013\12\12 10:30:49 $ * @author Wang Xiaotao<wangxiaotao1980@gmail.com> (中文编码测试) ******************************************************************************/ #include "Log/LogUtils.h" #include "Log/LogError.h" #include <string> #include <fstream> #include <iostream> #include "Misc/EncodeAndDecode.h" #include "boost/thread.hpp" #include "boost/filesystem.hpp" /******************************************************************************/ namespace { std::ofstream* s_pLogFile = 0; std::streambuf* s_std_clogbuf = 0; boost::mutex s_readLogMutex; } CPS_LOG_NAMESPACE_BEGIN LogCode Initialize(const Utf8Char* pFilepath) { LogCode resultCode = LOG_OK; //USING_STD_CLOG : 使用 std::clog作为输出 # if !defined(USING_STD_CLOG) #if defined(CPS_OS_WINDOWS) #if defined(CPS_STDLIB_DINKUMWARE) std::string pathName(pFilepath); std::wstring pathNameStr; CPS_MISC_NAMESPACE::UTF8ToUCS2(pathNameStr, pathName.c_str(), pathName.size()); #else // windows :: 非 dinkumware C++ stdlib, std::string pathNameStr(pFilepath); #endif //(CPS_STDLIB_DINKUMWARE) #else std::string pathNameStr(pFilepath); #endif //CPS_OS_WINDOW boost::filesystem::path thePath(pathNameStr); if (!boost::filesystem::exists(thePath.parent_path())) { boost::filesystem::create_directories(thePath.parent_path()); } s_pLogFile = new std::ofstream(pathNameStr.c_str(), std::ios::ate|std::ios::out); if (!(s_pLogFile->is_open())) { delete s_pLogFile; s_pLogFile = 0; resultCode = LOG_OPEN_LOG_FILE_FAIL; return resultCode; } s_std_clogbuf = std::clog.rdbuf(s_pLogFile->rdbuf()); // redirection std::clog to the log file // write the utf-8 bom for windows #if defined(CPS_OS_WINDOWS) char bom[] = {0xEF, 0xBB, 0xBF}; std::clog.write(bom, 3); #endif #endif return resultCode; } void Terminate() { # if !defined(USING_STD_CLOG) std::clog.rdbuf(s_std_clogbuf); // redircition std::clog s_std_clogbuf = 0; s_pLogFile->close(); delete s_pLogFile; s_pLogFile = 0; #endif } // ----------------------------------------------------------------------------- // class : inherit from : // public void LogLock() { s_readLogMutex.lock(); } void LogUnLock() { s_readLogMutex.unlock(); } CPS_LOG_NAMESPACE_END // // -----------------------------------------------------------------------------
b8f966a5a764cfa53c04236309878264c6b0dd2e
d4512117d8eef39734d5d9b522370538d629eba1
/modelBuild/Step1-skeletonExtraction/Product/Include_back - Copy/SkeletonAnalysis/CLimbPicker.h
a2e69a16be25e164bcbad63c278c7b7495e6e654
[]
no_license
TYWZ-milk/MyWorld
c9a39c57ebf8d609ee6c7bcc0e36e67693a9c9b4
2270bea4370f48480627de4a654432e29d040593
refs/heads/master
2021-04-06T12:07:55.421279
2018-06-22T02:39:35
2018-06-22T02:39:35
124,720,157
0
0
null
null
null
null
UTF-8
C++
false
false
4,385
h
CLimbPicker.h
// ----------------------------------------------------------------------------- // Copyright (c) 2007 Power studio. All rights reserved. // Permission is granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software") // for non-commercial use only, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // For commercial use of this software, please concat author. // History: // 12/10/2007 Qilin.Ren Created. // ----------------------------------------------------------------------------- #ifndef CLIMBPICKER_113112102007_H #define CLIMBPICKER_113112102007_H #include "CDiskContainer.h" #include "CMeshGroup.h" #include "Utility/StlDeque.h" WING_BEGIN class CLimbPicker { public: AnalysisExport CLimbPicker(); AnalysisExport virtual ~CLimbPicker(); AnalysisExport void Destroy(); // set configurations AnalysisExport void SetEdgeDistanceEpsilon(real edgeDistanceEpsilon); AnalysisExport void SetNegativeAlphaThreshold(real negativeAlphaDegreeThreshold); AnalysisExport void SetPositiveAlphaThreshold(real positiveAlphaDegreeThreshold); AnalysisExport void SetBetaThreshold(real betaDegreeThreshold); AnalysisExport void SetSameFaceEpsilon(real sameFaceEpsilon); AnalysisExport bool BeginPickLimbs( IN TriMesh& mesh, IN CMeshGroup& meshGroup, IN CDiskContainer& diskContainer); AnalysisExport bool PickNextLimbDisk(); AnalysisExport void RenderLimbConnections(const RenderSystemPtr& pRenderSystem); inline size_t GetPickedLimbCount() const; inline size_t GetPickedLimbDiskCount(size_t limbIndex) const; inline size_t GetPickedLimbDisk(size_t limbIndex, size_t diskIndex) const; private: AnalysisExport void NewPickLimbData(); AnalysisExport bool PickNextLimbDisk( OUT size_t& pickedDiskIndex, IN size_t prevStartIndex, IN size_t prevEndIndex, IN bool acropetal); AnalysisExport bool PickMaximalRadiusDisk(OUT size_t& maximalRadiusDisk); // member output: // - m_diskDistance // - m_possibleDiskTanAlpha // - m_possibleDiskCosBeta // - m_possibleDisks AnalysisExport void SearchPossibleDisks( IN size_t selectedDiskIndex, IN const Vector3* pPreviousDirection, IN bool acropetal); AnalysisExport bool CheckCollision( IN const LimbDisk& from_disk, IN const LimbDisk& dest_disk1, IN const LimbDisk& dest_disk2); private: AnalysisExport void CleanMembers(); private: // configurations real m_edge_distance_epsilon; real m_edge_distance_epsilonSq; real m_negative_alpha_threshold; real m_positive_alpha_threshold; real m_beta_threshold; real m_tangent_negative_alpha_threshold; real m_tangent_positive_alpha_threshold; real m_cos_beta_threshold; real m_same_face_epsilon; private: // source data TriMesh* m_pMesh; CMeshGroup* m_pMeshGroup; CDiskContainer* m_pDiskContainer; private: // temporary data vector<real> m_diskDistance; // --------------------------------- // Tangent alpha // --------------------------------- // disk2 // __ // / \ | // / \ | // / \A| // / \| // ------------ // disk1 vector<real> m_possibleDiskTanAlpha; // --------------------------------- // Cosine beta // --------------------------------- // disk2 // | / // | / // |B/ // |/ // disk1 vector<real> m_possibleDiskCosBeta; vector<uint32> m_possibleDisks; vector<uint32> m_tempararyPossibleDisks; private: struct PickLimbData { size_t m_prevStartIndex; size_t m_prevEndIndex; size_t m_pickedDiskIndex; size_t m_firstTwoDiskIndex[2]; size_t m_picked_count; bool m_bAcropetalOver; bool m_bCounterpetalOver; deque<size_t> m_pickedDisks; bool m_bDebugVerticesDirty; vector<UserPrimitiveVertex> m_debugVertices; }; // output data vector<PickLimbData> m_pickData; }; inline size_t CLimbPicker::GetPickedLimbCount() const { return m_pickData.size(); } inline size_t CLimbPicker::GetPickedLimbDiskCount(size_t limbIndex) const { return m_pickData[limbIndex].m_pickedDisks.size(); } inline size_t CLimbPicker::GetPickedLimbDisk(size_t limbIndex, size_t diskIndex) const { return m_pickData[limbIndex].m_pickedDisks[diskIndex]; } WING_END #endif // #ifndef CLIMBPICKER_113112102007_H
a0413d9864a41114f9d17526782f26d95a2725bb
93343c49771b6e6f2952d03df7e62e6a4ea063bb
/HDOJ/3580_autoAC.cpp
60224d6f9c9d4efd5ebb61e95f469718a708b8db
[]
no_license
Kiritow/OJ-Problems-Source
5aab2c57ab5df01a520073462f5de48ad7cb5b22
1be36799dda7d0e60bd00448f3906b69e7c79b26
refs/heads/master
2022-10-21T08:55:45.581935
2022-09-24T06:13:47
2022-09-24T06:13:47
55,874,477
36
9
null
2018-07-07T00:03:15
2016-04-10T01:06:42
C++
UTF-8
C++
false
false
1,503
cpp
3580_autoAC.cpp
#include<stdio.h> #include<stdlib.h> #include<string.h> int alp[52][52]; bool mark[26]; int num[26]; int size; int dir[8][4]={{-1, 0, 1, 1}, {1, 0, -1, 1}, {1, 0, -1, -1}, {-1, 0, 1, -1}, {-1, 1, 1, 0}, {1, 1, 0, -1}, {-1, -1, 1, 0}, {-1, 1, 0, -1}}; bool ok(int x, int y, int k, int d) { int i=x, j=y, len, l; i+=dir[k][0]*d;j+=dir[k][1]*d; if(k<4)len=d+1; else len=2*d+1; for(l=0; l<len; l++, i+=dir[k][2], j+=dir[k][3]){ if(i<0||i>size||j<0||j>size||alp[i][j]!=alp[x][y])return false; } num[alp[x][y]-'A']++; return true; } int main() { int t, ca, i, j, k, deep; scanf("%d",&t); for(ca=1; ca<=t; ca++){ scanf("%d", &size); getchar(); memset(mark, false, sizeof(mark)); memset(alp, 0, sizeof(alp)); for(i=0; i<size; i++){ for(j=0; j<size; j++){ scanf("%c", &alp[i][j]); mark[alp[i][j]-'A']=true; } getchar(); } memset(num, 0, sizeof(num)); for(i=0; i<size; i++){ for(j=0; j<size; j++){ for(k=0; k<=7; k++){ deep=1; while(ok(i, j, k, deep)){ deep++; } } } } printf("Case %d:\n", ca); for(i=0; i<26; i++) if(mark[i]) printf("%c %d\n", i+'A', num[i]); } return 0; }
b2d5a9f3e9782450f3c6b214c0ebb80b40a10b58
5677a7e4a711a0087c4b594086c1ee5d0643494c
/GameDemo/player.cpp
2f66bf82396d60ec6c0609f8af2f05d2ea4d6223
[]
no_license
Oldalf/programmeringsmetodik_invaders
968bdd24b2eaf8afad2cda21a51067a0fa154ef6
990aec96bcfa9529e6b36a1ef72c4e4dc98b8c4d
refs/heads/master
2021-07-15T05:23:58.064828
2017-10-22T12:27:52
2017-10-22T12:27:52
104,865,288
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,835
cpp
player.cpp
#include "entity.h" player::player(sf::Vector2f position, sf::Vector2f size, sf::Color color, float maxVelX) : entity(position, size, color, maxVelX), _playerClock(),_lastFire(_playerClock.getElapsedTime()) { _type = 0; _damage = 1; _renderPrio = 0; } void player::update(entity::entVec &ents, int width, int height, int level) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { accelerate(sf::Vector2f(-2, _velocity.y)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { accelerate(sf::Vector2f(2, _velocity.y)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { accelerate(sf::Vector2f(_velocity.x, 2)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { accelerate(sf::Vector2f(_velocity.x, -2)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { if (LastFire().asMilliseconds() >= 500) { sf::Vector2f tempPos = _boxObj.getPosition(); sf::Vector2f tempSize = _boxObj.getSize(); ents.push_back(new Lazer(sf::Vector2f( tempPos.x + tempSize.x / 2, tempPos.y - 5))); ents[ents.size() - 1]->accelerate(sf::Vector2f(0, -3)); ents.push_back(new Lazer(sf::Vector2f( tempPos.x + tempSize.x / 2, tempPos.y - 5))); ents[ents.size() - 1]->accelerate(sf::Vector2f(2, -3)); ents.push_back(new Lazer(sf::Vector2f( tempPos.x + tempSize.x / 2, tempPos.y - 5))); ents[ents.size() - 1]->accelerate(sf::Vector2f(-2, -3)); resetLastFire(); } } _boxObj.setPosition(_boxObj.getPosition().x + _velocity.x, _boxObj.getPosition().y + _velocity.y); //För att slippa pacman movement. accelerate(sf::Vector2f(0, 0)); if (_boxObj.getPosition().x + _boxObj.getSize().x > width) { _boxObj.setPosition(sf::Vector2f(width - _boxObj.getSize().x, _boxObj.getPosition().y)); } if (_boxObj.getPosition().x < 0) { _boxObj.setPosition(sf::Vector2f(0, _boxObj.getPosition().y)); } if (_boxObj.getPosition().y < 0) { _boxObj.setPosition(sf::Vector2f(_boxObj.getPosition().x, 0)); } if (_boxObj.getPosition().y > (height - _boxObj.getSize().y)) { _boxObj.setPosition(sf::Vector2f(_boxObj.getPosition().x, height - _boxObj.getSize().y)); } } void player::accelerate(sf::Vector2f newVel, int level) { if (newVel.x <= _maxVelX || newVel.x >= -_maxVelX) { _velocity.x = newVel.x; } _velocity.y = newVel.y; } int player::collide(entity *ent) { bool hit = collision(ent); if (hit && (ent->getType() == 1 || ent->getType() == 3)) { return 1; } else { return 0; } } sf::Time player::LastFire(){ _lastFire = _playerClock.getElapsedTime(); return _lastFire; } void player::resetLastFire() { _lastFire = _playerClock.restart(); }
7513b5071518eabe4a2819822eb30191b817b4c2
cd4e3f96ce07d94b09a2434c727260fc3ab9cb14
/src/Renderer.cpp
e0c77b2b305665c8cc64b1404d58075f25c76498
[ "MIT" ]
permissive
hmkum/HMK-OpenGL-Demo
afa276bc75b9db8675eb61705e1c80d0bb81ff1e
254f5814ed1c552dd0ab348cd3ab9332c9d1ef70
refs/heads/master
2021-01-20T11:21:44.257512
2021-01-07T11:57:22
2021-01-07T11:57:22
25,045,363
0
0
null
null
null
null
UTF-8
C++
false
false
3,344
cpp
Renderer.cpp
#include "Renderer.h" #include "ShaderManager.h" #include <iostream> using namespace hmk; Renderer::Renderer() { m_camera = nullptr; m_terrain = nullptr; m_fog = nullptr; m_fogEnable = false; m_ambientLightColor = glm::vec3(0.05f); } void Renderer::render() { // Render meshes for(uint32 i = 0; i < m_meshes.size(); i++) { std::vector<hmk::Mesh*> meshes = m_meshes[i]->getMeshes(); for(uint32 j = 0; j < meshes.size(); j++) { hmk::Mesh *mesh = meshes[j]; mesh->render("basic"); } } // Render camera if(m_camera) { GLint lastProgram = hmk::ShaderManager::getInstance()->getActiveProgram(); hmk::ShaderManager::getInstance()->use("basic"); hmk::ShaderManager::getInstance()->setUniformf("worldToCameraMatrix", m_camera->getView()); hmk::ShaderManager::getInstance()->setUniformf("cameraToClipMatrix", m_camera->getProjection()); hmk::ShaderManager::getInstance()->use(""); hmk::ShaderManager::getInstance()->use(lastProgram); } // Render terrain if(m_terrain) { m_terrain->render(GL_TRIANGLES); } // Render fog if(m_fogEnable) { GLint lastProgram = hmk::ShaderManager::getInstance()->getActiveProgram(); hmk::ShaderManager::getInstance()->use("basic"); hmk::ShaderManager::getInstance()->setUniformf("fogParams.color", m_fog->getColor()); hmk::ShaderManager::getInstance()->setUniformi("fogParams.equation", m_fog->getEquation()); hmk::ShaderManager::getInstance()->setUniformf("fogParams.start", m_fog->getStart()); hmk::ShaderManager::getInstance()->setUniformf("fogParams.end", m_fog->getEnd()); hmk::ShaderManager::getInstance()->use(lastProgram); } } void Renderer::addMeshLibrary(hmk::MeshLibrary *mesh) { m_meshes.push_back(mesh); } void Renderer::addCamera(hmk::Camera *camera) { assert(camera != nullptr); m_camera = camera; } void Renderer::addTerrain(hmk::Terrain *terrain) { assert(terrain != nullptr); m_terrain = terrain; } void Renderer::addFog(Fog *fog) { assert(fog != nullptr); m_fog = fog; } void Renderer::setEnableFog(bool fogEnable) { m_fogEnable = fogEnable; if(m_fogEnable) { GLint lastProgram = hmk::ShaderManager::getInstance()->getActiveProgram(); hmk::ShaderManager::getInstance()->use("basic"); hmk::ShaderManager::getInstance()->setUniformi("isFogEnable", 1); hmk::ShaderManager::getInstance()->use(lastProgram); } else { GLint lastProgram = hmk::ShaderManager::getInstance()->getActiveProgram(); hmk::ShaderManager::getInstance()->use("basic"); hmk::ShaderManager::getInstance()->setUniformi("isFogEnable", 0); hmk::ShaderManager::getInstance()->use(lastProgram); } } bool Renderer::isFogEnable() const { return m_fogEnable; } void Renderer::setAmbientLightColor(glm::vec3 color) { m_ambientLightColor = color; // Render ambient light GLint lastProgram = hmk::ShaderManager::getInstance()->getActiveProgram(); hmk::ShaderManager::getInstance()->use("basic"); hmk::ShaderManager::getInstance()->setUniformf("ambientLight", m_ambientLightColor); hmk::ShaderManager::getInstance()->use(lastProgram); }
4ded725622f0b56cd2bace6d17ec05731d955858
acaa4d5c51ba45bd0393677599003c8aa92c6704
/output/resnet50/c_verifier.cpp
1127305819ff0a256864d6091d5e5946bf4921aa
[]
no_license
Hamidu68/dnn-acceleration
5f947ca65e05540bd73b33c78b691bf70fcf12fe
307fb40498b4edc316ead0f142e3048695557dae
refs/heads/master
2022-07-28T05:47:05.188700
2019-08-27T13:11:15
2019-08-27T13:11:15
203,512,237
0
0
null
null
null
null
UTF-8
C++
false
false
15,349
cpp
c_verifier.cpp
#include <stdio.h> #include <iostream> #include <stdlib.h> #include <string> #include <string.h> #include <math.h> using namespace std; typedef float DATA_T; // define functions of each layer void SW_conv1_pad(DATA_T I[3][13][13],DATA_T O[3][19][19]) { int m, x, y, i, j; for (m = 0; m < 3; m++) { for (x = 0; x < 19; x++) { for (y = 0; y < 19; y++) { O[m][x][y] = 0; } } } for (m = 0; m < 3; m++) { for (x = 0; x < 13; x++) { for (y = 0; y < 13; y++) { O[m][x+ 3][y+ 3] = I[m][x][y]; } } } } void SW_conv1(DATA_T I[3][19][19], DATA_T O[4][7][7], DATA_T W[4][3][7][7], DATA_T B[4]) { int m, x, y, i, j, k; DATA_T ifm, ofm; for (m = 0; m<4; m++) { for (x = 0; x<7; x++) { for (y = 0; y<7; y++) { ofm = B[m]; for (k = 0; k<3; k++) { for (i = 0; i<7; i++) { for (j = 0; j<7; j++) { if (x + i <= 19 && y + j <= 19) { ifm = I[k][x*2 + i][y*2 + j]; } ofm = ofm + ifm * W[m][k][i][j]; } } } if (ofm < 0) O[m][x][y] = 0; else O[m][x][y] = ofm; } } } } void SW_activation_1(DATA_T I[4][7][7], DATA_T O[4][7][7]) { int m, x, y, i, j, k; for (m = 0; m<4; m++) { for (x = 0; x<7; x++) { for (y = 0; y<7; y++) { if (I[m][x][y] < 0) O[m][x][y] = 0; else O[m][x][y] = I[m][x][y]; } } } } void SW_max_pooling2d_1(DATA_T I[4][7][7], DATA_T O[4][3][3]) { int m, x, y, i, j; DATA_T max; for (m = 0; m<4; m++) { for (x = 0; x<3; x++) { for (y = 0; y<3; y++) { max = I[m][x*2][y*2]; for (i = 0; i<3; i++) { for (j = 0; j<3; j++) { if (I[m][x*2 + i][y*2 + j] > max) { max = I[m][x*2 + i][y*2 + j]; } } } O[m][x][y] = max; } } } } void SW_res2a_branch2a(DATA_T I[4][3][3], DATA_T O[4][3][3], DATA_T W[4][4][1][1], DATA_T B[4]) { int m, x, y, i, j, k; DATA_T ifm, ofm; for (m = 0; m<4; m++) { for (x = 0; x<3; x++) { for (y = 0; y<3; y++) { ofm = B[m]; for (k = 0; k<4; k++) { for (i = 0; i<1; i++) { for (j = 0; j<1; j++) { if (x + i <= 3 && y + j <= 3) { ifm = I[k][x*1 + i][y*1 + j]; } ofm = ofm + ifm * W[m][k][i][j]; } } } if (ofm < 0) O[m][x][y] = 0; else O[m][x][y] = ofm; } } } } void SW_activation_2(DATA_T I[4][3][3], DATA_T O[4][3][3]) { int m, x, y, i, j, k; for (m = 0; m<4; m++) { for (x = 0; x<3; x++) { for (y = 0; y<3; y++) { if (I[m][x][y] < 0) O[m][x][y] = 0; else O[m][x][y] = I[m][x][y]; } } } } void SW_res2a_branch2b(DATA_T I[4][3][3], DATA_T O[4][3][3], DATA_T W[4][4][3][3], DATA_T B[4]) { int m, x, y, i, j, k; DATA_T ifm, ofm; int p = (1 *(3 - 1) - 3 + 3)/2; for (m = 0; m<4; m++) { for (x = 0; x<3; x++) { for (y = 0; y<3; y++) { ofm = B[m]; for (k = 0; k<4; k++) { for (i = 0; i<3; i++) { for (j = 0; j<3; j++) { if (x*1 + i < 3 + p && y*1 + j < 3 + p && x*1 + i -p >= 0 && y*1 + j -p >= 0) { ifm = I[k][x*1 + i - p][y*1 + j -p]; } else { ifm = 0; // zero padding } ofm = ofm + ifm * W[m][k][i][j]; } } } if (ofm < 0) O[m][x][y] = 0; else O[m][x][y] = ofm; } } } } void SW_activation_3(DATA_T I[4][3][3], DATA_T O[4][3][3]) { int m, x, y, i, j, k; for (m = 0; m<4; m++) { for (x = 0; x<3; x++) { for (y = 0; y<3; y++) { if (I[m][x][y] < 0) O[m][x][y] = 0; else O[m][x][y] = I[m][x][y]; } } } } void SW_res2a_branch2c(DATA_T I[4][3][3], DATA_T O[5][3][3], DATA_T W[5][4][1][1], DATA_T B[5]) { int m, x, y, i, j, k; DATA_T ifm, ofm; for (m = 0; m<5; m++) { for (x = 0; x<3; x++) { for (y = 0; y<3; y++) { ofm = B[m]; for (k = 0; k<4; k++) { for (i = 0; i<1; i++) { for (j = 0; j<1; j++) { if (x + i <= 3 && y + j <= 3) { ifm = I[k][x*1 + i][y*1 + j]; } ofm = ofm + ifm * W[m][k][i][j]; } } } if (ofm < 0) O[m][x][y] = 0; else O[m][x][y] = ofm; } } } } void SW_res2a_branch1(DATA_T I[4][3][3], DATA_T O[5][3][3], DATA_T W[5][4][1][1], DATA_T B[5]) { int m, x, y, i, j, k; DATA_T ifm, ofm; for (m = 0; m<5; m++) { for (x = 0; x<3; x++) { for (y = 0; y<3; y++) { ofm = B[m]; for (k = 0; k<4; k++) { for (i = 0; i<1; i++) { for (j = 0; j<1; j++) { if (x + i <= 3 && y + j <= 3) { ifm = I[k][x*1 + i][y*1 + j]; } ofm = ofm + ifm * W[m][k][i][j]; } } } if (ofm < 0) O[m][x][y] = 0; else O[m][x][y] = ofm; } } } } void SW_add_1(DATA_T I1[5][3][3], DATA_T I2[5][3][3], DATA_T O[5][3][3]) { int m, x, y; for (m = 0; m< 5; m++) { for (x = 0; x < 3; x++) { for(y = 0; y < 3; y++) { O[m][x][y] = I1[m][x][y] + I2[m][x][y]; } } } } //argv[1] = init_weight.txt, argv[2] = init_input.txt int main(int argc, char *argv[]){ DATA_T temp; int m, x, y, i, j, k, l; int trash; // declare array variables of input, weight and bias (static variables) static DATA_T I[3][13][13]; static DATA_T W2[4][3][7][7]; static DATA_T B2[4]; static DATA_T W5[4][4][1][1]; static DATA_T B5[4]; static DATA_T W7[4][4][3][3]; static DATA_T B7[4]; static DATA_T W9[5][4][1][1]; static DATA_T B9[5]; static DATA_T W10[5][4][1][1]; static DATA_T B10[5]; // declare array variables of output (static variables) static DATA_T O0_SW[3][13][13]; static DATA_T O1_SW[3][19][19]; static DATA_T O2_SW[4][7][7]; static DATA_T O3_SW[4][7][7]; static DATA_T O4_SW[4][3][3]; static DATA_T O5_SW[4][3][3]; static DATA_T O6_SW[4][3][3]; static DATA_T O7_SW[4][3][3]; static DATA_T O8_SW[4][3][3]; static DATA_T O9_SW[5][3][3]; static DATA_T O10_SW[5][3][3]; static DATA_T O11_SW[5][3][3]; FILE *w_stream = fopen(argv[1], "rb"); if (w_stream == NULL) printf("weight file was not opened"); FILE *i_stream = fopen(argv[2], "rb"); if (i_stream == NULL) printf("input file was not opened"); FILE *o_stream = fopen("./output/resnet50/output_value/c_output.txt", "w"); if (o_stream == NULL) printf("Output file was not opened"); FILE *c_num = fopen("./output/resnet50/output_value/c_output_num.txt", "w"); if (c_num == NULL) printf("Output file was not opened"); // initialize input, weight, bias variables using fread printf("[c_verifier.cpp]Start Initialzation\n"); for (k = 0; k < 13 ; k++) { for (x = 0; x < 13 ; x++) { for(y = 0; y < 3 ; y++) { fread(&trash, sizeof(int), 1, i_stream); I[y][k][x] = (DATA_T) trash; O0_SW[y][k][x] = (DATA_T) trash; } } } for (m = 0; m < 7 ; m++) { for (k = 0; k < 7 ; k++) { for (i = 0; i < 3 ; i++) { for (j = 0; j < 4 ; j++) { fread(&trash, sizeof(int), 1, w_stream); W2[j][i][m][k] = (DATA_T) trash; } } } } for (m = 0; m < 4 ; m++) { fread(&trash, sizeof(int), 1, w_stream); B2[m] = (DATA_T) trash; } for (m = 0; m < 1 ; m++) { for (k = 0; k < 1 ; k++) { for (i = 0; i < 4 ; i++) { for (j = 0; j < 4 ; j++) { fread(&trash, sizeof(int), 1, w_stream); W5[j][i][m][k] = (DATA_T) trash; } } } } for (m = 0; m < 4 ; m++) { fread(&trash, sizeof(int), 1, w_stream); B5[m] = (DATA_T) trash; } for (m = 0; m < 3 ; m++) { for (k = 0; k < 3 ; k++) { for (i = 0; i < 4 ; i++) { for (j = 0; j < 4 ; j++) { fread(&trash, sizeof(int), 1, w_stream); W7[j][i][m][k] = (DATA_T) trash; } } } } for (m = 0; m < 4 ; m++) { fread(&trash, sizeof(int), 1, w_stream); B7[m] = (DATA_T) trash; } for (m = 0; m < 1 ; m++) { for (k = 0; k < 1 ; k++) { for (i = 0; i < 4 ; i++) { for (j = 0; j < 5 ; j++) { fread(&trash, sizeof(int), 1, w_stream); W9[j][i][m][k] = (DATA_T) trash; } } } } for (m = 0; m < 5 ; m++) { fread(&trash, sizeof(int), 1, w_stream); B9[m] = (DATA_T) trash; } for (m = 0; m < 1 ; m++) { for (k = 0; k < 1 ; k++) { for (i = 0; i < 4 ; i++) { for (j = 0; j < 5 ; j++) { fread(&trash, sizeof(int), 1, w_stream); W10[j][i][m][k] = (DATA_T) trash; } } } } for (m = 0; m < 5 ; m++) { fread(&trash, sizeof(int), 1, w_stream); B10[m] = (DATA_T) trash; } printf("[c_verifier.cpp]Finish Initialization\n"); // call function of each layer based on csv file which containts layer information printf("[c_verifier.cpp]InputLayer\n"); printf("[c_verifier.cpp]Calculate ZeroPadding2D1\n"); SW_conv1_pad(O0_SW,O1_SW); printf("[c_verifier.cpp]Calculate Conv2D2\n"); SW_conv1(O1_SW,O2_SW,W2,B2); printf("[c_verifier.cpp]Calculate Activation(Relu)3\n"); SW_activation_1(O2_SW,O3_SW); printf("[c_verifier.cpp]Calculate MaxPooling2D4\n"); SW_max_pooling2d_1(O3_SW,O4_SW); printf("[c_verifier.cpp]Calculate Conv2D5\n"); SW_res2a_branch2a(O4_SW,O5_SW,W5,B5); printf("[c_verifier.cpp]Calculate Activation(Relu)6\n"); SW_activation_2(O5_SW,O6_SW); printf("[c_verifier.cpp]Calculate Conv2D7\n"); SW_res2a_branch2b(O6_SW,O7_SW,W7,B7); printf("[c_verifier.cpp]Calculate Activation(Relu)8\n"); SW_activation_3(O7_SW,O8_SW); printf("[c_verifier.cpp]Calculate Conv2D9\n"); SW_res2a_branch2c(O8_SW,O9_SW,W9,B9); printf("[c_verifier.cpp]Calculate Conv2D10\n"); SW_res2a_branch1(O4_SW,O10_SW,W10,B10); printf("[c_verifier.cpp]Calculate Add11\n"); SW_add_1(O9_SW,O10_SW,O11_SW); // print each element of output variables printf("[c_verifier.cpp]Print Result\n"); fprintf(o_stream,"%s","InputLayer : [["); for (k = 0; k < 13 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 13 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 3 ; y++) { fprintf(o_stream,"%.6f ",(float)O0_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O0_SW[y][k][x]); } if(x != 13 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 13 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","ZeroPadding2D : [["); for (k = 0; k < 19 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 19 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 3 ; y++) { fprintf(o_stream,"%.6f ",(float)O1_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O1_SW[y][k][x]); } if(x != 19 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 19 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Conv2D : [["); for (k = 0; k < 7 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 7 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 4 ; y++) { fprintf(o_stream,"%.6f ",(float)O2_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O2_SW[y][k][x]); } if(x != 7 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 7 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Activation : [["); for (k = 0; k < 7 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 7 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 4 ; y++) { fprintf(o_stream,"%.6f ",(float)O3_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O3_SW[y][k][x]); } if(x != 7 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 7 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","MaxPooling2D : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 4 ; y++) { fprintf(o_stream,"%.6f ",(float)O4_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O4_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Conv2D : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 4 ; y++) { fprintf(o_stream,"%.6f ",(float)O5_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O5_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Activation : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 4 ; y++) { fprintf(o_stream,"%.6f ",(float)O6_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O6_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Conv2D : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 4 ; y++) { fprintf(o_stream,"%.6f ",(float)O7_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O7_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Activation : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 4 ; y++) { fprintf(o_stream,"%.6f ",(float)O8_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O8_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Conv2D : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 5 ; y++) { fprintf(o_stream,"%.6f ",(float)O9_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O9_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Conv2D : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 5 ; y++) { fprintf(o_stream,"%.6f ",(float)O10_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O10_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fprintf(o_stream,"%s","Add : [["); for (k = 0; k < 3 ; k++) { fprintf(o_stream,"%s","["); for (x = 0; x < 3 ; x++) { fprintf(o_stream,"%s","["); for(y = 0; y < 5 ; y++) { fprintf(o_stream,"%.6f ",(float)O11_SW[y][k][x]); fprintf(c_num,"%.6f ",(float)O11_SW[y][k][x]); } if(x != 3 -1 ) fprintf(o_stream,"%s","]\n "); else fprintf(o_stream,"%s","]"); } if(k != 3 -1 ) fprintf(o_stream,"%s","]\n\n "); } fprintf(o_stream,"%s","]]]\n\n"); fclose(w_stream); fclose(i_stream); fclose(o_stream); fclose(c_num); return 0; }
3876af259d78c8cf625fa52000888bf90811370f
16a04a189c2f14d6d28a78d774a8c0ad8fb3bf28
/LibCppSim - Multipoint communication HPCS/network/NETWORK.h
0d89a1d6503dc0b3b9aabb7aae384354dfad88b0
[]
no_license
F951/Models-HPCS
7895b9d708df04f7b2fe70c9e14c46ac32dd3d67
64b24311499b8ffd7e86c3698389494f0f5a8787
refs/heads/main
2023-03-07T16:02:02.620133
2021-02-24T15:38:44
2021-02-24T15:38:44
341,332,053
0
0
null
null
null
null
UTF-8
C++
false
false
1,727
h
NETWORK.h
#ifndef NETWORK_H #define NETWORK_H #include "../glob.h" #include "../Observer.h" #include "../server/Message.h" #include "../server/SERVER.h" class CLIENT; class Observer; class SERVER; class NETWORK: public process { protected: list<Message *> queue_in; handle<Observer> *observer; bool busy; void inner_body( void ); int flag_terminar; handle<Observer>* obs; public: int param_network; public: vector<handle<CLIENT> *> clientes_server_Peers; int NP; vector<handle<SERVER> *> server; int nro_servers; ~NETWORK() { } NETWORK ( const string& name, int _NP ,int _nro_servers, handle<Observer>* _obs): process( name ) { busy = false; NP = _NP; flag_terminar=0; nro_servers = _nro_servers; obs=_obs; } void add_peer(handle<CLIENT> * p) { clientes_server_Peers.push_back(p); } bool get_busy() { return busy; } void add_message( Message *m ) { queue_in.push_back( m ); } void add_server( handle<SERVER> *_server ) { server.push_back( _server ); } void print() { cout << "NETWORK" << endl; } void set_handle_obs(handle<Observer> *_obs) { observer=_obs; } void printMSG(Message *m); void terminar( ){ flag_terminar=1; } double get_random_time_exp(double par, double multiplicador){ //------------------------------------------------------------------------------ int seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::exponential_distribution<double> distribution(par); double delay = multiplicador*distribution(generator); //------------------------------------------------------------------------------ return delay; } }; #endif
4c93e79b4e4a074f9ea5a92dc93b250f53b33f9f
37fd62cabffa130f99cd13031644ff36395e8fc7
/main/sell_information.cpp
a24e12bbdca9d303844ef484a2070f7d82cf0b58
[]
no_license
wacban/SellingInformation
5094e683a66aa02268899e72b3cf077289e93631
888c8b4683bdb48b47abfb66ede21c4ebcd8b2be
refs/heads/master
2021-01-13T02:16:07.128018
2016-02-14T22:43:50
2016-02-14T22:43:50
41,244,929
1
0
null
null
null
null
UTF-8
C++
false
false
11,342
cpp
sell_information.cpp
#include "sell_information.h" #include "../cut_and_choose/cut_and_choose.h" #include "../timed_commitment/bit_utils.h" #include "../timed_commitment/timed_commitment.h" #include "../sha_commitment/sha_commitment.h" #include "../common/aes.h" #include "../common/log.h" #include <vector> #include <set> #include <iostream> #include <numeric> #include <thread> #include <unistd.h> using namespace CryptoPP; using namespace std; namespace sell_information { using common::L; using common::T; void Seller::findRoots() { for(unsigned i = 0; i < common::L; ++i){ array<Integer, 4> roots = square_root.all_square_roots(y[i]); r1[i] = roots[0]; r2[i] = roots[1]; if (common::rng().GenerateBit() == 1) { swap(r1[i], r2[i]); } if (r1[i] == -1) { // TODO random } if (r2[i] == -1) { // TODO random } } } void Seller::encryptRoots() { for(unsigned i = 0; i < L; ++i) { c1[i] = common::enc(single_seller.keys_commits[i].m, common::to_bytes(r1[i])); c2[i] = common::enc(single_seller.keys_commits[i].m, common::to_bytes(r2[i])); } } void Seller::setupCommit() { for(unsigned i = 0; i < L; ++i) { d1[i].m = c1[i]; d2[i].m = c2[i]; } } array<unsigned, L/2> Seller::acceptSubset(const std::array<unsigned, common::L/2>& indices, const std::array<CryptoPP::Integer, common::L/2>& values) { array<unsigned, L/2> commitment_indices; // which of c1, c2 shoudl be opened ? for(unsigned i = 0; i < L/2; ++i) { unsigned ind = indices[i]; Integer val = values[i]; if (val >= n/2) { Log("val:"); Log(val); Log("n/2"); Log(n/2); throw ProtocolException("xi >= n/2"); } if ((val*val) % n != y[ind]) { throw ProtocolException("xi is not a square root of yi"); } commitment_indices[i] = 5; // TODO if (val == r1[ind]) { commitment_indices[i] = 1; } if (val == r2[ind]) { commitment_indices[i] = 2; } } return commitment_indices; } void Seller::accept_T1(const Transaction& T1) { Log("accept t1"); this->T1 = T1; bool res = single_seller.base_party.client.verifyTransaction( T1, common::integer2string(single_seller.shared_signature_s.get_Q().x), common::integer2string(single_seller.shared_signature_s.get_Q().y), price ); if (!res) { throw ProtocolException("verify T1 failed!"); } else { Log("verify transaction worked!"); } /* TODO verify T2 */ res = single_seller.base_party.client.waitForTransaction(T1, 1); // TODO better security if (!res) { throw ProtocolException("wait for t1 failed!"); } else { Log("wait for t1 worked!"); } } void Seller::accept_payment() { if (cheat){ return ; } bool res = single_seller.base_party.client.broadcastTransaction( single_seller.getT2() ); if (!res) { throw ProtocolException("accept payment failed!"); } else { Log("accept payment worked!"); } } void Buyer::pickR(){ this->r = Integer(common::rng(), 0, T-1).ConvertToLong(); } void Buyer::pickSubset() { indices.resize(L); std::iota(indices.begin(), indices.end(), 0); common::rng().Shuffle(indices.begin(), indices.end()); indices.resize(L/2); } array<unsigned, L/2> Buyer::getSubsetIndices() { array<unsigned, L/2> res; copy(indices.begin(), indices.end(), res.begin()); return res; } array<Integer, L/2> Buyer::getSubsetValues() { array<Integer, L/2> res; for(unsigned i = 0; i < L/2; ++i) { res[i] = x[indices[i]]; } return res; } void Buyer::verifyRoot(unsigned ind, const vector<byte>& key, const vector<byte>& c) { vector<byte> x_encoded = common::dec(key, c); Integer x(x_encoded.data(), x_encoded.size()); if (x != this->x[ind]) { throw ProtocolException("verifyRoot failed"); } } void Buyer::make_payment() { Log("make payment"); bool res = single_buyer.base_party.client.broadcastTransaction( single_buyer.getT1() ); if (!res) { throw ProtocolException("make payment failed"); } else { Log("payment succesfull"); } } void Buyer::solve_time_lock(atomic_bool &finished) { Log("solve time lock started"); auto ds_bytes = this->single_buyer.timed_commitment_receiver.force_open_smart(); Log("solve time lock finished"); BaseParty base_party(9092); Integer ds = BitUtils::bits_to_integer(ds_bytes); Integer d = ds * this->single_buyer.shared_signature_b.get_db(); d = d % single_buyer.shared_signature_b.get_n(); bool res = base_party.client.redeemTransaction( single_buyer.getT1(), common::integer2string(d), common::integer2string(single_buyer.shared_signature_b.get_Q().x), common::integer2string(single_buyer.shared_signature_b.get_Q().y) ); if (!res) { // TODO what should happen at this point? Log("solve time lock - redeem transaction failed"); Log("solve time sleeping forever!!!"); while(true) { sleep(1); } } Log("Hurray!"); Log("solved time lock and got money back"); finished = true; } void Buyer::get_signature(atomic_bool &finished) { Log("get signature"); bool res; BaseParty base_party(9092); res = base_party.client.waitForTransactionByOutput(single_buyer.getSellerAddress(), 1); // TODO better security if (!res) { throw ProtocolException("wait for transaction by output failed"); } bitcoin_utils::IntegerPair signature; base_party.client.getSignature(signature, single_buyer.getSellerAddress()); Integer r = Integer((byte*) signature.r.data(), signature.r.size()); Integer s = Integer((byte*) signature.s.data(), signature.s.size()); this->signature = shared_signature::encode_signature(r, s); Log("-------------------------------------------"); Log("Signature from btc"); Log(common::string2hex(common::v2string(this->signature))); Log("-- r s"); Log(r); Log(s); Log("-------------------------------------------"); factorise(); finished = true; } void Buyer::wait_for_signature_or_time_lock() { atomic_bool signature_finished(false); atomic_bool time_lock_finished(false); thread solve_time_lock(&Buyer::solve_time_lock, this, ref(time_lock_finished)); thread get_signature(&Buyer::get_signature, this, ref(signature_finished)); Log("wait_for_signature_or_time_lock waiting"); while(!signature_finished && !time_lock_finished) { sleep(1); } Log("wait_for_signature_or_time_lock finished"); if (signature_finished) { get_signature.join(); solve_time_lock.detach(); Log("signature finished"); } else { Log("time lock finished"); get_signature.detach(); solve_time_lock.join(); } } void Buyer::factorise() { vector<byte> sig(signature.begin(), signature.end()); auto keys = genKeys(sig); // TODO negate signature for(unsigned i = 0; i < L; ++i) { if (d1[i].m.empty() || d2[i].m.empty()) continue; auto r1_bytes = common::dec(keys[i], d1[i].m); auto r2_bytes = common::dec(keys[i], d2[i].m); Integer r1(r1_bytes.data(), r1_bytes.size()); Integer r2(r2_bytes.data(), r2_bytes.size()); if (r1 < 0) r1 = -r1; if (r2 < 0) r2 = -r2; Integer p = GCD(n + r1 - r2, n); Integer q = GCD(r1 + r2, n);; if (p * q == n) { this->p = p; this->q = q; return; } } throw ProtocolException("Factorization failed!"); } void SellInformationProtocol::init(Seller *seller, Buyer *buyer) { if (seller->get_n() != buyer->get_n()){ throw ProtocolException("Not matching n"); } if (seller->get_price() != buyer->get_price()){ throw ProtocolException("Not matching price"); } /* if (!verify(seller->get_address())){ throw ProtocolException("Seller has invalid bitcoin address"); } */ /* if (!verify(buyer->get_address())){ throw ProtocolException("Buyer has invalid bitcoin address"); } */ } void SellInformationProtocol::exec(Seller *seller, Buyer *buyer){ Log("sell information protocol exec"); SingleSellInformationProtocol single_sell_information; shared_signature::S shared_signature_s; shared_signature::B shared_signature_b( shared_signature_s.get_paillier_n(), shared_signature_s.get_paillier_g() ); SingleSeller single_seller(shared_signature_s); SingleBuyer single_buyer(shared_signature_b); vector<SingleSeller> single_sellers(T, single_seller); vector<SingleBuyer> single_buyers(T, single_buyer); cut_and_choose::Prover<SingleSeller> prover; prover.v = single_sellers; cut_and_choose::Verifier<SingleBuyer> verifier; verifier.v = single_buyers; buyer->pickR(); verifier.i = buyer->getR(); cut_and_choose::cut_and_choose<SingleSellInformationProtocol, SingleSeller, SingleBuyer, T > (&prover, &verifier); if (!verifier.res) { // TODO throw ProtocolException("Generating signatures and keys failed!"); } Log("finished cut and choose"); seller->setSingleSeller(prover.v[verifier.i]); Log("-------------------------------------------"); Log("Generated signature:"); Log( common::string2hex( common::v2string( seller->single_seller.shared_signature_s.get_signature() ) ) ); Log(seller->single_seller.shared_signature_s.get_r()); Log(seller->single_seller.shared_signature_s.get_s()); Log("-------------------------------------------"); buyer->setSingleBuyer(verifier.v[verifier.i]); buyer->genSquares(); seller->acceptSquares(buyer->getSquares()); seller->findRoots(); seller->encryptRoots(); seller->setupCommit(); sha_commitment::ShaCommitment sha_commitment_protocol; for(unsigned i = 0; i < L; ++i) { sha_commitment_protocol.init(&seller->d1[i], &buyer->d1[i]); sha_commitment_protocol.init(&seller->d2[i], &buyer->d2[i]); sha_commitment_protocol.exec(&seller->d1[i], &buyer->d1[i]); sha_commitment_protocol.exec(&seller->d2[i], &buyer->d2[i]); } buyer->pickSubset(); auto indices = buyer->getSubsetIndices(); auto values = buyer->getSubsetValues(); set<unsigned> indices_set(indices.begin(), indices.end()); if (indices_set.size() != L/2) { Log(indices); throw ProtocolException("invalid indices size"); } for(unsigned ind: indices_set) { if (ind >= L) { throw ProtocolException("invalid commitment_indices value"); } } auto commitment_indices = seller->acceptSubset(indices, values); for(unsigned i = 0; i < L/2; ++i) { unsigned ind = indices[i]; Integer val = values[i]; unsigned commit_ind = commitment_indices[i]; sha_commitment_protocol.open(&seller->single_seller.keys_commits[ind], &buyer->single_buyer.keys_commits[ind]); vector<byte> key = buyer->single_buyer.keys_commits[ind].m; vector<byte> c; switch (commit_ind) { case 1: sha_commitment_protocol.open(&seller->d1[ind], &buyer->d1[ind]); c = buyer->d1[ind].m; break; case 2: sha_commitment_protocol.open(&seller->d2[ind], &buyer->d2[ind]); c = buyer->d2[ind].m; break; default: throw ProtocolException("matching roots to values didn't work"); } buyer->verifyRoot(ind, key, c); } for(unsigned ind = 0; ind < L; ++ind){ if (indices_set.find(ind) == indices_set.end()) { sha_commitment_protocol.open(&seller->d1[ind], &buyer->d1[ind]); sha_commitment_protocol.open(&seller->d2[ind], &buyer->d2[ind]); } } buyer->make_payment(); seller->accept_T1(buyer->single_buyer.getT1()); seller->accept_payment(); // last function for seller buyer->wait_for_signature_or_time_lock(); // last function for buyer } void SellInformationProtocol::open(Seller *seller, Buyer *buyer){ } }
ef1a9704a2f179a8c0af870d65f966807db81ec2
ccd7b1ff51459c6a713cd92892dd72d1bba33cf3
/programs/sumofsubsets.cpp
47b23cc25c15cd5140c200ce60b140db18a3ab09
[]
no_license
tusharkushwaha/DSA-Competitive
ebd2e77f4d2e33ba5a962026995d575d97d7b160
8955df752696383635df41a34ef867c11127e4d0
refs/heads/main
2023-06-19T04:03:25.196318
2021-07-23T10:51:26
2021-07-23T10:51:26
378,831,405
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
sumofsubsets.cpp
#include <iostream> #include <vector> using namespace std; void printTargetSumSubsets(vector<int> nums, int sum, int pointer, int target, vector<int> path) { if (pointer == nums.size()) return; int temp = 0; temp = sum + nums[pointer]; if (temp == target) { cout << "{"; for (auto &i : path) { cout << i << " "; } cout << nums[pointer] << "}" << endl; } vector<int> path1 = path; path1.push_back(nums[pointer]); printTargetSumSubsets(nums, temp, pointer + 1, target, path1); printTargetSumSubsets(nums, sum, pointer + 1, target, path); } int main() { vector<int> nums = {10, 20, 30, -10, 40, 50, 20, -10 , 60}; int target = 60; int sum = 0; vector<int> path; printTargetSumSubsets(nums, sum, 0, target, path); return 0; }
9ab28538d37157aaa031143533acd5e828c11ddf
bee4964f6b2f831ea222df914191459562ea9219
/codeforces/team.cpp
cb24abcc90dfeee424c2b81a7cab463feb48ce87
[]
no_license
kimkim480/cpp-studies
00adb0645ea0a528afc952fac2a69da3502912e7
513d3a6703fd32224170a0329524157d81a5df3c
refs/heads/master
2023-03-02T01:56:51.695093
2021-02-11T17:14:15
2021-02-11T17:14:15
287,035,819
0
0
null
null
null
null
UTF-8
C++
false
false
286
cpp
team.cpp
#include <iostream> int main(){ int n; int p, v, t; int c{0}; std::cin >> n; for(int i=0; i<n; i++){ std::cin >> p >> v >> t; if((p && t && v) || (p && t) || (p && v) || (t && v)){ c++; } } std::cout << c; return 0; }
baa5676932f3e27218b6c4e2087afedb4bef2ade
6463da9a716e1267cf0505e230b5801bc5b175aa
/UNIX/setjmp/setjmptest.cpp
86f8be3adc0bfd1e0dc653efc710bede1eda1464
[ "LicenseRef-scancode-public-domain" ]
permissive
lianzeng/cplusplus11.Examples
c333948f70a16b84ce139f1e5812ab9f0ba45afe
f27335ec622938d0af17d664877f5934e418dcd3
refs/heads/master
2021-01-24T18:38:42.216365
2016-11-16T17:13:53
2016-11-16T17:13:53
84,463,090
0
1
null
2018-01-31T04:22:41
2017-03-09T16:15:43
C++
UTF-8
C++
false
false
960
cpp
setjmptest.cpp
#include<iostream> #include<setjmp.h> jmp_buf j_val; int testF1(int x) { if(x == 1) longjmp(j_val, 1); // #1 jump from here back to setjmp return value 1 ++x; return x; } int rtVal(int val) { int x_val = testF1(val); if(x_val == 1) { std::cout << "Value is: 1\n"; } return x_val; } int main(int argc, char **argv) { std::cout << "Pass no arguments to test longjmp pass at least 1 to complete function\nEnter test: "; switch(setjmp(j_val)) { // first call retuns 0 after that value passed to longjmp case 0: { std::cout << "Returned after inital call.\n"; if(rtVal(argc) == 3) { std::cout << "value is 3\n"; } else { std::cout << "value is not 3\n"; } } break; case 1: { std::cout << "We jumped back from testF1.\n"; } break; } return EXIT_SUCCESS; }
905cfa341bdc4eda625a040c545386409327f704
960faa024a6dffbdc1fcac214eb3c22723e70cce
/Sources/Kore/Network/Http.h
09cfb6a12e8513ac6bddbd7aafc6661981bb6df6
[ "Zlib" ]
permissive
Kode/Kore
76fd9181be6c2865ac3c94b8930e1a3b872dac29
24fae6f8386a8956ed793f22e99f7e6c48a52021
refs/heads/main
2023-08-17T05:32:01.601464
2023-08-07T20:28:57
2023-08-07T20:28:57
516,546,380
8
0
Zlib
2023-05-26T19:24:43
2022-07-21T23:11:13
C++
UTF-8
C++
false
false
400
h
Http.h
#pragma once namespace Kore { enum HttpMethod { GET, POST, PUT, DELETE }; typedef void (*HttpCallback)(int error, int response, const char *body, void *callbackdata); void httpRequest(const char *url, const char *path, const char *data, int port = 80, bool secure = false, HttpMethod method = GET, const char *header = 0, HttpCallback callback = 0, void *callbackdata = 0); }
c92f0d1355de852b1b9631386e169946f5d25d56
e1ca147c0e24a24a2d695d3575e2e1fbcbd98477
/main.cpp
432fc42056f70292ccb289dae0d9a34ae7c9787a
[]
no_license
Luichoo/Finite_Automata
5effa166f3e414aefc6205224e46c4c0cf8b3629
4e4290f7cc0881d926a940e01a543e46104a1455
refs/heads/master
2023-09-01T15:04:52.856220
2021-10-21T03:09:10
2021-10-21T03:09:10
415,568,731
1
0
null
null
null
null
UTF-8
C++
false
false
3,909
cpp
main.cpp
/** * @file main.cpp * @authors Luis Blanco - Alejandro Salas * @brief Management of a finite automata * @version 0.1 * @date 2021-10-09 * * */ #include <iostream> #include <string.h> #include "graph.h" #include "filecheck.h" using namespace std; #define MAXDATA 100 void message(){ cout<<" /$$$$$$ /$$ /$$ "<<endl; cout<<" /$$__ $$ | $$ | $$ "<<endl; cout<<"| $$ \\ $$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$/$$$$ /$$$$$$ /$$$$$$ /$$$$$$ "<<endl; cout<<"| $$$$$$$$| $$ | $$|_ $$_/ /$$__ $$| $$_ $$_ $$ |____ $$|_ $$_/ |____ $$"<<endl; cout<<"| $$__ $$| $$ | $$ | $$ | $$ \\ $$| $$ \\ $$ \\ $$ /$$$$$$$ | $$ /$$$$$$$"<<endl; cout<<"| $$ | $$| $$ | $$ | $$ /$$| $$ | $$| $$ | $$ | $$ /$$__ $$ | $$ /$$ /$$__ $$"<<endl; cout<<"| $$ | $$| $$$$$$/ | $$$$/| $$$$$$/| $$ | $$ | $$| $$$$$$$ | $$$$/| $$$$$$$"<<endl; cout<<"|__/ |__/ \\______/ \\___/ \\______/ |__/ |__/ |__/ \\_______/ \\___/ \\_______/"<<endl; } int main(){ N *states; states = NULL; string value; string state; bool check = true; int data=0; char *V=new char[MAXDATA]; system("cls"); if(fcharge(&states,V,&data)) cout << "\nThe Automata is ready\n"<< endl; int opc = 0,times = 0; while(true){ message(); cout << "Menu\n1.Insert States\n2.Insert Connections\n3.Display States\n4.Display Final States\n5.Display matrix\n0.Exit" << endl; validateInput(&opc); system("cls"); message(); cout<<endl; switch(opc){ case 1: cout<<"Option 1: insert state\n"<<endl; times = 0; validateInput(&state); check = node_exist(states,state); while(check && times < 2) { cout << "invalid input, the state already exist" << endl; validateInput(&state); check = node_exist(states,state); times += 1; } if(times == 2 && check){ cout << "Too many errors, going back to menu" << endl; break; } check = insert_state(&states,state,false); cout << endl; if(check){ cout << "Success" << endl; } else{ cout << "Fail" << endl; } break; case 2: cout<<"Option 2: insert Connections\n"<<endl; if(states){ check = insert_adj(&states,V,&data); cout << endl; if(check){ cout << "Success" << endl; } else{ cout << "Fail" << endl; } } else cout << "The automata is empty" << endl << endl; break; case 3: cout<<"Option 3: Display all\n"<<endl; if(states) display_ALL(states); else cout << "The automata is empty" << endl << endl; break; case 4: cout<<"Option 4: Display final states\n"<<endl; if(states) display_final_States(states); else cout << "The automata is empty" << endl << endl; break; case 5: cout<<"Option 5: Display matrix\n"<<endl; if(states) automata_matrix(states,data,V); else cout << "The automata is empty" << endl << endl; break; case 0: cout << "Tschusss"; exit(EXIT_SUCCESS); break; default: cout << "\nInvalid option" << endl; } system("pause"); system("cls"); } return EXIT_FAILURE; }
53622fe450add1d08b0fa006df8d8e70fa4d962c
91fcd8a3237f64ad2d206c88c4451d12af2bc992
/Arduino UNO Code/servo.ino
db508280b06dde74b08a1443eae3aee0257dfbc0
[]
no_license
VIPINMAHAWAR007/hackathon4
422b5bb2560aa4afdb9cb8daadf0a44c67945637
266ddbbc8d18c817539edd1257bed688f38e61fb
refs/heads/master
2021-09-10T03:43:13.393590
2018-03-20T22:05:42
2018-03-20T22:05:42
126,085,279
0
0
null
null
null
null
UTF-8
C++
false
false
429
ino
servo.ino
#include <Servo.h> // including servo library. Servo servo_1; int t=999; void setup (){ Serial.begin(9600); servo_1.attach(3); servo_1.write (135); } void loop(){ if(Serial.available()){ t = Serial.read(); Serial.println(t); if(t == 48){//Close-0 servo_1.write (135); } else if(t == 49){//Open-1 servo_1.write (45); // Servo will move to 45 degree angle. } delay(500); } }
ee52d0829babe2940471dc9e9b385ece8b0cf4dd
3c21a9a0f849e42adf1579c7798b420eeaeaf51c
/Sha1.cpp
b6811a03d72f4ee0c8b6c2293415424aa096ba4a
[]
no_license
DavidRich09/Sha1_MD5_Algs
9d1c4ce8e8bbff0bc234d1dbfc7884efe47b5b4f
8b7fafa3b05ff1e5d3e609cb0628ca2ba46f78c8
refs/heads/main
2023-05-29T17:55:27.689871
2021-06-12T05:29:43
2021-06-12T05:29:43
375,243,325
0
0
null
null
null
null
UTF-8
C++
false
false
2,735
cpp
Sha1.cpp
/** * @file SHA1.cpp contiene el código de los métodos de SHA1. */ #include "Sha1.h" using namespace std; int SHA1::LShift(unsigned int x, int n) { return x >> (32 - n) | (x << n); } void SHA1::Add(std::string m) { // creacón del texto packets = (m.size() + 8) / 64 + 1; xVector.resize(packets * 64); int i = 0; for (; i < m.size(); i++) { xVector[i] = m[i]; } xVector[i++] = 0x80; while (i < xVector.size() - 8) { xVector[i] = 0; i++; } long long int a = m.size() * 8; for (i = xVector.size() - 1; i >= xVector.size() - 8; i--) { xVector[i] = a % 256; a /= 256; } } void SHA1::array(std::vector<int> m, int n) { n *= 64; for (int i = 0; i < 16; i++) { W[i] = (m[n + 4 * i] << 24) + (m[n + 4 * i + 1] << 16) + (m[n + 4 * i + 2] << 8) + m[n + 4 * i + 3]; } for (int i = 16; i < 80; i++) { W[i] = LShift(W[i - 16] ^ W[i - 14] ^ W[i - 8] ^ W[i - 3], 1); } } int SHA1::ft(int t) {//ft(pB,pC,pD) function if (t < 20) return (pB & pC) | ((~pB) & pD); else if (t < 40) return pB ^ pC ^ pD; else if (t < 60) return (pB & pC) | (pB & pD) | (pC & pD); else return pB ^ pC ^ pD; } int SHA1::Kt(int t) { //constant K if (t < 20) return 0x5a827999; else if (t < 40) return 0x6ed9eba1; else if (t < 60) return 0x8f1bbcdc; else return 0xca62c1d6; } void SHA1::Run(std::string text) { buffa1 = pA = 0x67452301; buffb1 = pB = 0xefcdab89; buffc1 = pC = 0x98badcfe; buffd1 = pD = 0x10325476; buffe1 = pE = 0xc3d2e1f0; Add(text); for (int i = 0; i < packets; i++) { array(xVector, i); for (int t = 0; t < 80; t++) { int temp = pE + ft(t) + LShift(pA, 5) + W[t] + Kt(t); pE = pD; pD = pC; pC = LShift(pB, 30); pB = pA; pA = temp; } buffa1 = pA = pA + buffa1; buffb1 = pB = pB + buffb1; buffc1 = pC = pC + buffc1; buffd1 = pD = pD + buffd1; buffe1 = pE = pE + buffe1; } Files::AddSHA1Hash(text, getHashStr()); cout << "El hash de \"" << text << "\" es " << getHashStr() << std::endl; } std::string SHA1::getHashStr() { std::stringstream buff1; std::stringstream buff2; std::stringstream buff3; std::stringstream buff4; std::stringstream buff5; buff1 << std::hex << this->buffa1; buff2 << std::hex << this->buffb1; buff3 << std::hex << this->buffc1; buff4 << std::hex << this->buffd1; buff5 << std::hex << this->buffe1; return buff1.str() + buff2.str() + buff3.str() + buff4.str() + buff5.str(); }
73d07b91453970a0185b0bf2acd002a5ac6ee1bd
8297b32611378127f7a8582cd0f47fe2d8545e3b
/W32_API_Test/Tile.cpp
9d4991c93004785d4027b96533a1fe13e120973e
[]
no_license
albinopapa/Win32-API
5e5dd3e03eedd30d91cc48441b92d5e61fd214c7
be9fe34c9291e98106eabcb679ef382e5b1ad687
refs/heads/master
2021-01-18T18:28:23.461494
2016-07-06T18:32:40
2016-07-06T18:32:40
62,743,727
0
0
null
null
null
null
UTF-8
C++
false
false
1,645
cpp
Tile.cpp
#include "Tile.h" Tile::Tile() {} Tile::Tile( const cRectU &Clip, TileType Type ) : type(Type), clip(Clip), color(type != Passable ? D2D1::ColorF::Black : D2D1::ColorF::Navy ) { color.a = type == Passable ? 0.f : 1.f; } Tile::Tile( const Tile & Right ) : type( Right.type ), clip( Right.clip ), color( Right.color ) {} Tile::Tile( Tile && Right ) : type( Right.type ), clip( Right.clip ), color( Right.color ) {} Tile::~Tile() {} Tile & Tile::operator=( const Tile & Right ) { type = Right.type; clip = Right.clip; color = Right.color; return *this; } Tile & Tile::operator=( Tile && Right ) { type = Right.type; clip = Right.clip; color = Right.color; return *this; } BOOL Tile::IsPassable() const { return type == Passable; } BOOL Tile::HasType( TileType Type ) const { BOOL same = type & Type; BOOL has_type = same > 0 ? TRUE : FALSE; return has_type; } TileType Tile::GetType() const { return type; } cRectU Tile::GetClip() const { return clip; } cRectU Tile::GetClipInPixels() const { auto point = Utilities::PointU( clip.position.x * clip.size.width, clip.position.y * clip.size.height ); return cRectU( point, clip.size ); } void Tile::Draw( const Camera &Cam, const Graphics & Gfx )const { auto rect = GetClipInPixels(); auto view = Cam.GetViewRect(); auto point = Utilities::PointF( rect.position.x >= view.position.x ? rect.position.x - view.position.x : 0, rect.position.y >= view.position.y ? rect.position.y - view.position.y : 0 ); auto size = Utilities::SizeF( rect.size.width, rect.size.height ); Gfx.DrawFilledRect( Utilities::RectF( point, size), color ); }
aa010064873645a2e5a4057505cb03ff012389de
e11b2493f55c60685c3ea76f900be73e6a454b2f
/compilers/lexer/lexer.cpp
87acb8440d7814f7d46efea67e2016afe0da4cf3
[]
no_license
zpoint/Reading-Exercises-Notes
29e566dd86d97eadb84d7bb6f8f640b85486557c
31b38fe927232ba8e6f6a0e7ab9c58026eefcffb
refs/heads/master
2021-06-04T08:12:42.777309
2021-04-19T02:12:22
2021-04-19T02:12:22
70,507,489
0
0
null
null
null
null
UTF-8
C++
false
false
2,950
cpp
lexer.cpp
#include <iostream> #include <string> #include <map> inline int char2int(char c) { return c - (static_cast<int>('0') - 0); } inline bool isletter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } inline bool isdigit(char c) { return c >= '0' and c <= '9'; } struct Token { Token() { /*std::cout << "Call default constructor of Token" << std::endl;*/ } Token(int t): tag(t) { } int tag = 0; }; struct Tag { static const int NUM = 256, ID = 257, TRUE = 258, FALSE = 259; const std::string operator[](const int num) { switch (num) { case NUM: return "NUM"; case ID: return "ID"; case TRUE: return "TRUE"; case FALSE: return "FALSE"; default: return "NOT A VALID TAG"; } } }; struct Num : Token { Num(int v): Token(v), value(v) { } int value; }; struct Word : Token { std::string lexeme; Word(int t, std::string s): Token(t), lexeme(s) { } Word() { /* std::cout << "Call default constructor of Word" << std::endl;*/ } }; struct Lexer { public: int line = 1; Lexer(); Token scan(); private: char peek = ' '; bool comment_tag = false; int comment_type = 1; // 1 ==> // , 2 ==> /* std::map<std::string, Word> words; void reserve(Word t) { words[t.lexeme] = t; } }; Lexer::Lexer() { reserve(Word(Tag::TRUE, "true")); reserve(Word(Tag::FALSE, "false")); }; Token Lexer::scan() { while (comment_tag) { std::string str; std::cin.get(peek); str += peek; std::size_t size = str.size(); if (peek == '\n' and comment_type == 1) comment_tag = false; else if (size >= 2 and str.substr(size - 2) == (comment_type == 1 ? "//" : "/*")) comment_tag = false; } for ( ; ; std::cin.get(peek)) { if (peek == ' ' || peek == '\t') continue; else if (peek == '\n') line += 1; else break; } if (isdigit(peek)) { int v = 0; do { v = 10 * v + char2int(peek); std::cin.get(peek); } while (isdigit(peek)); return Num(v); } if (isletter(peek)) { std::string str; do { str += peek; std::cin.get(peek); } while (isdigit(peek) || isletter(peek)); std::map<std::string, Word>::iterator iter = words.find(str); if (iter != words.end()) { return (*iter).second; } else { Word new_word(Tag::ID, str); words[str] = new_word; return new_word; } } if (peek == '/') { char next_char = std::cin.peek(); if (next_char == '/') { comment_type = 1; comment_tag = true; std::cin.get(peek); } else if (next_char == '*') { comment_type = 2; comment_tag = true; std::cin.get(peek); } } Token t(peek); peek = ' '; return t; } int main() { Lexer l; Tag tag; while (true) { Token t = l.scan(); std::cout << tag[t.tag] << std::endl; } }
a2279ee16bae000025af7bd2200f02c4cc0bed75
77db7f6d5cee7dbead860ef01fb943262e2b9580
/ProjectFlightSchool/ProjectFlightSchool/Entry.cpp
acba8fc7a2d76a02d3781ade3bc8ccae78bdbe29
[]
no_license
SvinSimpe/Project-Flight-School
e4f5e06c95f7024cd6fb9f5fd5b01ecfaf7cfb59
00a64d06be2bba985ba195aabf8f4fa4bf109e1f
refs/heads/development
2020-12-24T15:13:54.535124
2015-03-20T09:36:38
2015-03-20T09:36:38
26,538,774
0
3
null
2015-03-24T12:33:59
2014-11-12T14:06:46
C++
UTF-8
C++
false
false
463
cpp
Entry.cpp
#include "Entry.h" bool Entry::Initialize( float x, float y, float width, float height ) { mUpperLeft.x = (UINT)x; mUpperLeft.y = (UINT)y; mLowerRight.x = (UINT)x + (UINT)width; mLowerRight.y = (UINT)y + (UINT)height; mWidth = width; mHeight = height; return true; } void Entry::Release() { } Entry::Entry() { mUpperLeft.x = 0; mUpperLeft.y = 0; mLowerRight.x = 0; mLowerRight.y = 0; mWidth = 0.0f; mHeight = 0.0f; } Entry::~Entry() { }